# Question
Title: Connecting Seeeduino XIAO 3.3 V out to dual H-bridge driver module (L298N) with TTL compatible inputs
The H-bridge module uses TTL compatible logic, but the chip allows these values (based on the L298N data sheet):

| Symbol | Parameter | Min. | Max. |
| --- | --- | --- | --- |
| ViL | Input Low Voltage (pin 5, 7, 10, and 12) | -0.3 V | 1.5 V |
| ViH | Input High Voltage (pin 5, 7, 10, and 12) | 2.3 V | VSS |

Am I correct to assume that I do not need to step-up the logic signal (from 3.3 V to 5 V) for this to work, but can I connect straight to the input?

Schematic in mind:

# Answer
> 2 votes
> Am I correct to assume that I do not need to step-up the logic signal (from 3.3V to 5V) for this to work, but can connect straight to the input?

You are correct. The input has to be above 2.3V to register as HIGH and below 1.5V to register as LOW. You have 3.3V for HIGH and near 0V for LOW, which fits those criteria perfectly.

---
Tags: h-bridge
---


# Question
Title: Temperature Sensor not giving proper values
In my current project I am reading temperature through sensor which is having only two wires.

To read sensor values, I have used below schematic which I have found on Arduino Project Hub site.

In my project I am using below Arduino program.

```
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2

// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();
}

void loop(void)
{
  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");

  Serial.print("Temperature is: ");
  Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
    // You can have more than one IC on the same bus.
    // 0 refers to the first IC on the wire
    delay(1000);
}

```

After doing all this I am getting this output on serial monitor.

At which step I am doing wrong?

# Answer
The -127 for your temperature reading is actually the error code for `DEVICE_DISCONNECTED_C`.

In the library's example code, they put an if that checks for this error code before printing the temperature:

```
if(tempC != DEVICE_DISCONNECTED_C)
{
  Serial.print("Temperature for the device 1 (index 0) is: ");
  Serial.println(tempC);
}

```

Since your sensor has only 2 wires, according to Wikipedia, you need a capacitor to power the sensor:

> One distinctive feature of the bus is the possibility of using only two wires — data and ground. To accomplish this, 1-Wire devices include an 800 pF capacitor to store charge and power the device during periods when the data line is active.

This should hopefully resolve your issues.
> 1 votes

---
Tags: arduino-uno, temperature-sensor, ds18b20, lm35
---


# Question
Title: How do I resolve error message "assignment of function 'void digitalWrite (uint8_t, uint_8)"?
I am a beginner in using Arduino and programming in c/c++. I am trying to connect a 10-segment LED and a moisture sensor to my Arduino Uno, and when the moisture level is very low, the first 2 red LEDs will be turned on, when it is slightly higher, the next three orange LEDs will be turned on, when it is slightly higher the next three green LEDs will be turned on, and finally when the moisture level is above the threshold for the green LEDs, the final blue LED segment will turn on.
I have written a program that works, and I have tested both the moisture sensor and the 10 segment LED separately to ensure they are working. Although the program works how I intend it, about 30-40% of the time I am unable to run the program due to an error message in the process of uploading. To be clear, I do not change the code at all from the working state of the code to the error message appearing. I wanted to know why this message appears, and how to avoid/resolve this issue.
I have included my code below:

```
/*
   Arduino LED Bar Graph with Moisture Sensor
   Started June 25, 2020

   edited 6/28
    (added blue LED)
*/

int redLED = 13;
int yellowLED = 12;
int greenLED = 11;
int blueLED = 10;

#define SensorPin A0
float sensorValue = 0;
float moistureLevel = 0;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(redLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(blueLED, OUTPUT);
}

void loop()
{
  if  (Serial.available() > 900)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (redLED, HIGH);
    digitalWrite = (yellowLED, LOW);
    digitalWrite = (greenLED, LOW);
    digitalWrite = (blueLED, LOW)
  }
  else if (Serial.available() > 750)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (yellowLED, HIGH);
    digitalWrite = (redLED, LOW);
    digitalWrite = (greenLED, LOW);

  }
  else(Serial.available() > 550)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (greenLED, HIGH);
    digitalWrite = (redLED, LOW);
    digitalWrite = (yellowLED, LOW);
    digitalWrite = (blueLED, LOW);
  }
  else(Serial.available() < 549)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (greenLED, HIGH);
    digitalWrite = (redLED, LOW);
    digitalWrite = (yellowLED, LOW);
    digitalWrite = (blueLED, HIGH);
  }
  for (int i = 0; i <= 100; i++)
  {
    sensorValue = sensorValue + analogRead(SensorPin);
    delay(1);
  }
  sensorValue = sensorValue / 100.0;
  Serial.println(sensorValue);
  delay(100);
}

```

And here is a copy of the exact error message:

```
/tmp/777165248/sketch_jun25a/sketch_jun25a.ino: In function 'void loop()':

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:33:33: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = {redLED, HIGH};

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:33:33: error: cannot convert '<brace-enclosed initializer list>' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:34:35: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (yellowLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:34:35: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:35:34: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (greenLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:35:34: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:36:33: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (blueLED, LOW)

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:36:33: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:41:36: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (yellowLED, HIGH);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:41:36: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:42:32: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (redLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:42:32: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:43:34: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (greenLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:43:34: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:47:3: error: expected ';' before '{' token

{

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:54:3: error: 'else' without a previous 'if'

else(Serial.available() < 549)

^~~~

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:55:3: error: expected ';' before '{' token

{

^

exit status 1

```

# Answer
You have:

```
digitalWrite = (redLED, HIGH);

```

This is incorrect since digitalWrite is a function not a variable. Instead you likely want:

```
digitalWrite(redLED, HIGH);

```

This calls the digitalWrite function with the two arguments.
> 2 votes

---
Tags: arduino-uno, arduino-ide, sensors, c++, ide
---


# Question
Title: Memory allocation on Arduino Due never returns NULL
I'm working on a project that uses quite a bit of RAM to store and analyze data that is sent from the PC. The program heavily relies on `malloc`/`free`, which normally works just fine. However, if the data set gets to big - which I can't tell beforehand - the Arduino just dies. Some analysis found that it has to do with memory management. Running a simple sketch which just does

```
void loop() {
  int SIZE_TO_TEST = (1024 * 10);
  int* mem = (int*)malloc(SIZE_TO_TEST);
  if (mem == nullptr)
  {
    // This never happens
    Serial.print("Allocation failed\r\n");
    return;
  }
  Serial.print("Allocation succeeded\r\n");
  Serial.print((int)mem, HEX); // this always prints 0x200712E0, regardless of the size
  Serial.println();
  for (int i = 0; i < SIZE_TO_TEST / 4; i++)
  {
    mem[i] = i;
  }

  for (int i = 0; i < SIZE_TO_TEST / 4; i++)
  {
    if (mem[i] != i)
    {
      // You better get a new board if this happens
      Serial.print("HARDWARE ERROR: Memory broken\r\n");
    }
  }
  free(mem);
}

```

works fine and repeatedly prints "Allocation succeeded". When I start increasing the `SIZE_TO_TEST`, the CPU crashes when the value is over the effective memory size of 96k. The weird thing is, that even when the value is 1000k (far beyond what the uP actually has), the pointer returned by `malloc()` is still the same memory address, not `NULL`, as one would expect. The crash also does *not* occur if the allocated memory is not used (if the two for loops are commented out), so I suspect the actual crash occurs because the program tries to write to memory that is not actually there.

How do I find out that the memory is exhausted? Why does `malloc()` never return `NULL`?

(Note: I know about the problems of memory fragmentation with small micro controllers, but I can work around that issue)

# Answer
# Why

This is a partial answer, for now, mostly with regard to:

> Why does malloc() never return NULL?

So, the Due appears to use Newlib as its libc implementation; that is the systems C (standard and some non-standard) runtime that includes `malloc()`, or the greater part of `malloc()` anyway. The Newlib `malloc()` relies on an `sbrk()` function which is implemented by the specific system, the Due in this case. This name and basic idea comes out of Unix; you can read about the interplay between malloc and sbrk some without it having to be in connection with Newlib or the Due specifically. In short, `sbrk` extends the area that `malloc` has to work with and `malloc` divides that area into requested chunks. Here is Newlib's documentation for sbrk and a sample implementation.

The Due (SAM) core for Arduino implements sbrk as:

```
extern caddr_t _sbrk ( int incr )
{
    static unsigned char *heap = NULL ;
    unsigned char *prev_heap ;

    if ( heap == NULL )
    {
        heap = (unsigned char *)&_end ;
    }
    prev_heap = heap;

    heap += incr ;

    return (caddr_t) prev_heap ;
}

```

This is a kind of degenerate implementation of `_sbrk` that just blindly says, "You want more memory, sure here you go" **without limit**. If you look at the sample `sbrk` implementation for Newlib, you'll see it just calls `abort()` instead of a proper failure that would result in `malloc` returning `NULL`, which is admittedly not great, but at least it's not pretending that everything is fine.

There should be a condition somewhere in this code that check so see if there's any more space to be had and sets `errno = ENOMEM` and effectively does `return -1` if there is not.

I modified this code to allow me to set a variable from the sketch that could force the next call to `_sbrk` to fail as described above. And sure enough, on the next call to `malloc()` it returned `NULL` because `_sbrk` had indicated failure.

So the `_sbrk` implementation provided by the Due/sam core should be changed so that `malloc` fails when appropriate. That said, I'm not precisely sure how that should be done. So I'm going to hold off on making specific recommendations about it. Maybe I look into it more I'll come back and update this with something more useful, addressing your other question of:

> How do I find out that the memory is exhausted?

In rough terms though, the answer going to be that you modify that function so it returns `-1` with `ENOMEM` under the right conditions.

---

# How

This is the previously mentioned update with some details on the *how*:

> How do I find out that the memory is exhausted?

So I've made something to give you an idea what the condition would look like. I'm not strictly recommending you use it; for one thing it's barely been tested.

From the ATSAM3X8E's family datasheet:

> SRAM0 is accessible over the system Cortex-M3 bus at address 0x2000 0000 and SRAM1 at address 0x2008 0000. **The user can see the SRAM as contiguous thanks to mirror effect, giving 0x2007 0000 - 0x2008 7FFF for SAM3X/A8**

The stack pointer starts near the top of memory 0x2008 7FFF and grows downward. The `_end` symbol marks the end of the mutable static storage duration variables or the beginning of the heap. Somewhere closer to 0x2007 0000; the fewer of these variables the closer.

On this system, which has a fairly common layout, the heap grows up with positive increments to sbrk as the stack pointer grows down with stack frames (local variables, return addresses etc). So, "the end" of memory happens when the heap would otherwise allocate over the stack or the stack runs into the heap as your pushing things onto it.

So a typical thing to do is to check to see whether or not the `sbrk`'s argument would cause the edge of the heap to get "too close" to the stack.

In the the `/.arduino15/packages/arduino/hardware/sam/1.6.12/cores/arduino/syscalls_sam3.c`, I've include some extra headers:

```
#include <errno.h>
#include <stdlib.h>

```

And put the following as a replacement `_sbrk()`:

```
size_t __malloc_margin = 4 * (size_t)1024;
extern caddr_t _sbrk (int incr) {
    static const unsigned char *       heap      = (unsigned char *)&_end ;
    /****/ const unsigned char * const prev_heap = heap;

    if (incr > 0) {
        // Extra checks for stack growing

        if (incr >= 96 * (size_t)1024) {
            // The Due only has 96K of ram,
            // so any request for 96K or greater
            // is a failure out of the gate.
            errno = ENOMEM;
            return (caddr_t)-1;
        }

        unsigned char *stack_ptr;

        asm volatile(
            "mov %[sp_out], sp"
            : [sp_out] "=r" (stack_ptr)
            :
        );

        if (stack_ptr < heap) {
            // We're already in real trouble.
            abort();
        }

        if (stack_ptr - heap  <  incr + __malloc_margin) {
            // Not enough memory considering safety margin.
            errno = ENOMEM;
            return (caddr_t)-1;
        }
    }

    heap      += incr ;
    return (caddr_t) prev_heap ;
}

```

`__malloc_margin` was used as a variable name just because it's the name that avr-libc uses for the same purpose, namely to tune the minimum distance between the stack and heap during an allocation that the break to increase. *By the way, you can see this same kind of check happen in avr-libc's implementation of malloc (which also takes `sbrk`'s role.)* Why is `__malloc_margin` 4K ? No really scientific reason. It's about 4% of memory, so it's not large, and it's not completely inconceivable *to me* that someone would try to put local variable(s) approaching 4k in a stack frame on a system that has 96kb total memory. 4K may not be an appropriate default though; more thought should go into that. Having it in a variable like this allows it to be tuned at runtime; usually there would be a header that provides an `extern` declaration for it.

I may add more later to explain, but it short if the break is being increased, this `sbrk` looks to see if the new break would get within `__malloc_margin` of the stack pointer on a request, an if it would it returns the `-1` value and `errno = ENOMEM` to cause `malloc` to behave correctly from the user's perspective.

Before anyone bothers to mention: Yes, I know you can take the address of a local to get a stack pointer value. Yes, the check to see if the single allocation is larger than 96K is probably unnecessary. Yup, it has Due specific stuff in it even though it's not strictly a Due; there are probably identifiers that could be used instead. It should probably `abort()` if sbrk tries to go below 0 sized heap. It's just a somewhat working *illustration* of what should be in `_sbrk()`. More thought and at least one change should be put into it before general use.

# Regarding abort()

It occurs to me in *some* cases `abort()` may be an appropriate way to handle this. If you believe that you can characterize the system (or the sketch if you like) at runtime so well that `malloc()` failing can be regarded as a major oversight, then calling `abort()` in `sbrk()` could make sense. Or at least providing the option to do that.

In the comments you asked:

> What does abort() exactly \[do\] on the Due?

Well, Newlib documentation says:

> Before terminating your program, abort raises the exception SIGABRT (using ‘raise(SIGABRT)’).

and then further down:

> Supporting OS subroutines required: \_exit and optionally, write.

The `SIGABRT` and `_exit` parts are more or less standard behaviour. So it will call your signal handler for `SIGABRT` if you have one.

So then what does `_exit` do? It loops forever.

I called `abort()` in a sketch and dumped the following via an arm version of the binutils objdump with `-dS` command-line options.

Here's the relevant `abort()` code:

```
00081b98 <abort>:
   81b98:   b508        push    {r3, lr}
   81b9a:   2006        movs    r0, #6
   81b9c:   f000 fb5c   bl  82258 <raise>
   81ba0:   2001        movs    r0, #1
   81ba2:   f7fe fec5   bl  80930 <_exit>
   81ba6:   bf00        nop

```

`bl <raise>` would in turn call your signal handler. and `bl <_exit>` calls exit which displays as:

```
00080930 <_exit>:

extern void _exit( int status )
{
   80930:   e7fe        b.n 80930 <_exit>

00080932 <_kill>:

    for ( ; ; ) ;
}

```

It appears the optimizer has combined some things here, but essentially `_exit` has an instruction that jumps (branches) to itself, equivelent to `for(;;);`.

I half-expected the `abort();` code to disable interrupts before calling `_exit()`. If you do plan on `abort()` in your `_sbrk()` that might be something to think about. You may also want to provide a global flag that can be inspected from `SIGABRT` that allows the signal handler to do something diagnostically appropriate specifically for `_sbrk()` failures.
Perhaps `sbrk` should set a flag in a no-init data section and then set the watchdog timer and let it expire (or provide the `SIGABRT` handler with the information to do that). Lots of things to consider.
> 7 votes

# Answer
I think I found a workaround. It relies on the fact that on simple program architectures such as the one used on most microcontrollers, the heap grows upwards while the stack grows backwards.

```
const int MIN_FREE_STACK = 512;

void* mallocEx(int size)
{
  void* stackPtr = alloca(4); // This returns a pointer to the current bottom of the stack
  PrintAddress("StackPtr ", stackPtr);
  void* ptr = malloc(size);
  PrintAddress("NewInstance ", ptr);
  if ((byte*)ptr + size > ((byte*)stackPtr - MIN_FREE_STACK))
  {
    free(ptr); // This memory location is not really valid
    return nullptr;
  }
  return ptr;
}

```

The method checks, on each attempt to allocate memory, whether the newly allocated block would reach into the call stack (+ some safety margin). If so, the pointer is freed again and null is returned.

I tried with this a bit more demanding test, and it seems to work as expected (allocates a bunch of blocks until it fails at around 91k, then restarts)

```

void ValidateMemoryManager()
{
  const int oneK = 1024;
  const int maxMemToTest = 100; // the arduino due has 96k of memory
  void* ptrs[maxMemToTest];
  int idx = 0;
  int totalAllocsSucceeded = 0;
  while (idx < maxMemToTest)
  {
    void* mem = mallocEx(oneK);
    ptrs[idx] = mem;
    if (mem == nullptr)
    {
      break;
    }
    idx++;
  }

  // Happens in simulation
  if (idx == maxMemToTest)
  {
    idx--;
  }

  totalAllocsSucceeded = idx;
  while (idx >= 0)
  {
    free(ptrs[idx]);
    idx--;
  }

   Serial.print("Total usable memory: ");
   Serial.print(totalAllocsSucceeded * oneK, DEC);
   Serial.println();
}

```
> 2 votes

---
Tags: arduino-due, memory-usage
---


title: Problem using Optiga Trust X I2C

text:
# Question
Title: Problem using Optiga Trust X I2C
Did someone ever used the Infineon Optiga Trust X module with Arduino using any I2C library ?

Here is the technical documentation of the Trust X module.

I'm trying to get the I2C\_STATE register data but I don't receive anything after the Wire.requestFrom().

I also tried with the DSS Circuits I2C Master Library, same results.

Thanks

Full code :

```
#include <Wire.h>
#define PIN_RST 8
#define PIN_VDD 9

void setup() {
  pinMode(PIN_RST, OUTPUT);
  pinMode(PIN_VDD, OUTPUT);
  digitalWrite(PIN_RST,LOW);
  digitalWrite(PIN_VDD,LOW);

  Serial.begin(115200);
  delay(2000);
  Wire.begin(); // join i2c bus (address optional for master)

  digitalWrite(PIN_VDD,HIGH);  // sartup the Trust X module
  digitalWrite(PIN_RST,HIGH);

  delay(15);  // startup min delay
}

long val = 9999;

void loop() {
  Wire.beginTransmission(48); // transmit to device #48 (0x30)
  Wire.write(byte(0x82));            // sends instruction byte
  Wire.endTransmission();     // stop transmitting

  Wire.requestFrom(48, 4);
  while(Wire.available()==0){}

  val = Wire.read(); // Reads the data from the register
  Serial.print("val = ");
  Serial.println(val);

  delay(5000);

}

```

# Answer
> 1 votes
So I finally succeeded to read a register value. I don't really know where was the problem. Here is the code if it can help someone (the scanner still does not work btw) :

```
#include <Wire.h>

#define DEVICE_ADDRESS 0x30

#define PIN_RST 8
#define PIN_VDD 9

void printOutput(byte *out, int out_len){
   int y=0;
  Serial.print("out = ");
  for(;y<out_len;y++){
    Serial.print(out[y],HEX);
  }
  Serial.println("");
}

void coldReset(){
  pinMode(PIN_RST, OUTPUT);
  pinMode(PIN_VDD, OUTPUT);
  digitalWrite(PIN_VDD,LOW);
  digitalWrite(PIN_RST,LOW);
  delayMicroseconds(2000);
  digitalWrite(PIN_VDD,HIGH);  // sartup the Trust X module
  digitalWrite(PIN_RST,HIGH);
}

int I2C_get(byte reg, byte *out, int out_len){
  int i=0, nbSend=0, nbAvailable=0, ret=0;
  Wire.beginTransmission(DEVICE_ADDRESS); // transmit to device #48 (0x30)
  nbSend=Wire.write(reg);            // sends instruction byte
  Wire.endTransmission();     // stop transmitting
//  Serial.print("nb send = ");
//  Serial.println(nbSend);

  delayMicroseconds(50);
  Wire.requestFrom(DEVICE_ADDRESS, out_len);

//  nbAvailable=Wire.available();
//  Serial.print("nb available = ");
//  Serial.println(nbAvailable);

  if(Wire.available()==out_len){
    for(;i<out_len;i++){
      out[i]=Wire.read();
    }
  }
  else ret=-1;

  return ret;
}

void setup() {

  Serial.begin(115200);
//  Wire.begin(); // join i2c bus (address optional for master)
//  coldReset();
//  delayMicroseconds(15000); // Startup time
}

void loop() {
  int y=0, out_len, ret;
  byte res1[]={0x00,0x00,0x00,0x00};

  Wire.begin(); // join i2c bus (address optional for master)
  Wire.setClock(400000);
  coldReset();
  delayMicroseconds(15000); // Startup time

  out_len=4;
  ret=I2C_get(byte(0x84),res1,out_len);
  if(ret!=-1){
    printOutput(res1,out_len);
  }
  else{
    Serial.println("Error I2C_get");
  }

  Wire.end();
  Serial.println("");
  delay(5000);
}

```

# Answer
> 1 votes
It looks like the answer is a bit delayed, but if somebody else sees this issue once again.

It might not be directly visible in the documentation (Datasheet or Solution Reference Manual), but here what you can find in the Trust M Datasheet Annex B (Section 11): "The OPTIGA™ Trust M will not acknowledge the slave address sent by a host if it is either busy or in idle state. Hence the host must retry or repeat the transaction until it is successful or timed out for 100 milliseconds (extreme case). The specified guard time must be applied between each attempt of write / read operation by the Host I2C driver."

The chip always goes into an idle or sleep state if no command is issued in a defined time period, unless a Sleep Activation Delay isn't changed.

---
Tags: arduino-uno, i2c
---


title: MFRC522 Communication Failure

text:
# Question
Title: MFRC522 Communication Failure
I'm using TTGO ESP32 and I've got an MFRC522 from AliExpress.

I've soldered connector pins to the board itself (both for ESP32 and MFRC522) and I'm using jumper wires female-to-female to connect themselves.

However, using an example sketch (DumpInfo) from miguelbalboa's RFID library, it says communication failure and scanning 3 different key cards or the key fob doesn't output anything.

```
Firmware Version: 0xFF = (unknown)
WARNING: Communication failure, is the MFRC522 properly connected?

```

This is my current pinout scheme:

```
(MFRC - ESP32)
SDA (SS) -> 33
SCK -> 25
MISO -> 27
MOSI -> 26
RST -> 32

```

And, of course also GND to G and 3.3V to 3.3V.

I've also tried SDA and SCK to connect to 21 and 22, respectively but no luck. Though I have a DS1307 RTC module and microSD card adapter module and connected accordingly and it's working fine, by using Dupont wires, with the same method.

A manufacturer's defect or still I'm making an error somewhere?

You can see TTGO's ESP32 pinout diagram and also a picture of MFRC522 here wired using jumper wires. I may be using (again) the wrong pins. The red LED on the MFRC522 is stable, though.

Thank you in advance.

# Answer
> 2 votes
**UPDATE!** The issue has been fixed, just after finding this stackoverflow answer by bat macumba. I'll leave the question here, in case someone stumbles into the same problem.

---
Tags: esp32, rfid
---


# Question
Title: Voltage, current measurement from solar panel using INA219 and ESP-12F
I recently started tinkering with ESP-12F thus I am a novice here. As a standard novice project, I am making a standalone weather station for my living room. I want to use solar panels to charge the batteries which power up the ESP-12F via USB. I am using ESP-12F as a controller and sending data to Rpi using MQTT.

I am using the following items:

1. ESP-12 F powered by USB
2. 2.5W 5V solar panel ( I want to connected two in parallel but for now using only one )
3. RPi 3B
4. INA219A to measure voltage and current generated by solar panel.
5. IN4001 diode as blocking
6. DHT11 sensor for temp and humidity values
7. Battery pack to charge 2 x 2500mAh batteries ( This is not done yet )

I am quite confused by the connections to INA219 and the data its providing. Thus, ESP-12F is still connected to independent usb power source and my goal is for now to understand and monitor the voltage and current generated by solar panel.

The INA219 Vcc, GND, SDA, SCL are connected to ESP-12F. I can read the values and observe them on serial monitor or mqtt panel.

***1. Below is the breadboard connection when INA219 Vin+ is NOT connected.***

The voltage measurement sent via MQTT is as below:

Ignore graph, I was pluging in/out Vin wire too many times thus very bizzare lines.

Current connections are as below:

Solar Panel (-) --\> INA219 Vin (-) and breadboard to power LED

Solar Panel (+) --\> Only to breadboard to power LED \[INA219 Vin+ NOT connected\]

ESP-12F 3V --\> INA219 Vcc

ESP-12F GND --\> INA219 GND

ESP-12F D1 --\> INA219 SCL

ESP-12F D2 --\> INA219 SDA

**ESP-12F is powered by separated USB power source**

Code using which the values are computed: I have used Adafruit\_INA219 library.

```
  shuntvoltage = ina219.getShuntVoltage_mV();
  busvoltage = ina219.getBusVoltage_V();
  current_mA = ina219.getCurrent_mA();
  power_mW = ina219.getPower_mW();
  loadvoltage = busvoltage + (shuntvoltage / 1000);

```

I dont understand the values sent by INA219 and have no idea how to interpret them. At this point, INA219 is connected to ESP-12F 3V power (Vcc) and GND. It does not have any Vin. Why there is a load voltage of -1.9 and current?

***2. When INA219 has Vin(+) and Vin(-) connected***

When I connect the Vin+ and Vin- of INA219 I dont have any voltage/current on the breadboard. You can see the LED if OFF. I dont understand why this happens. The whole circuit on breadboard is redundant once I connect INA219 Vin pins to solar panel output pins.

Current connections are as below:

Solar Panel (-) --\> INA219 Vin (-) and breadboard to power LED

Solar Panel (+) --\> INA219 Vin(+) and breadboard to power LED

ESP-12F 3V --\> INA219 Vcc

ESP-12F GND --\> INA219 GND

ESP-12F D1 --\> INA219 SCL

ESP-12F D2 --\> INA219 SDA

**ESP-12F is powered by separated USB power source**

The voltage and current values at this point is shown below:

The load voltage increases and the difference which is approx **2.1V**. This delta voltage matches the voltage values from solar panel when measured by **multimeter** at this point. Thus, I would assume load voltage = current voltage generated by solar panel. But, current is unchanged and LED on breadboard if OFF the moment I connect INA219 Vin. Thus, I assume I have done wrong connections.

It will be great if you can point out my mistakes and make suggestions!

Thank you!

# Answer
You connected the V- and V+ probes of the INA module direct to the V- and V+ of the solar panel. That means you connect V+ with V- from solar panel over a 0.1 Ohm resistor. That is like a short. The Solar panel gets overloaded and the voltage breaks down. Lucky you, the solar panel can not provide more current. If it could, then the shunt resistor would be grilled. RIP ;-). Try put the v+ and V- in series with the LED and LED\_Resistor. e.g.

```
Solar+ --> IN4001 --> INA+ |no connection| INA- --> LED --> R(LED) --> Solar-

```

That would make more sense. It'll show you how much current is drawn by the LED.

If you want to know how much current the panel can deliver, you would have to build a circuit with a potentiometer and measure the Voltage between V+ and V- of the Panel. You can also use the INA to mesasure the current through the potentiometer. Begin with a high resistancy, then turn the poti towards lower resistance and check when the voltage breaks down. The INA shows you the current. But be aware that, the max current depent on the amount of light the panel is exposed to and on the age of the panel itselves. So the values will change as these conditions change.
> 4 votes

---
Tags: esp8266, nodemcu
---


title: How to upload code to atmega32u4?

text:
# Question
Title: How to upload code to atmega32u4?
I recently created a pcb with the atmega32u4 to use it as a development board. The controller is connected to a micro usb port. Should I install the arduino bootloader instead of the deafult one? Or keep the default boot loader and find another way of flashing hex files? But bottom line what is the process to flash a hex file to the atmega32u4 via usb?

# Answer
Installing the Arduino bootloader would make it easier to upload you sketch from the Arduino IDE.

Installing the Arduino bootloader via DFU is probably the easiest method. Alternatively use ISP, but you'd need a programmer for that, or use a separate Arduino board with the ArduinoAsISP sketch running on it.
> 0 votes

---
Tags: programming, atmel
---


title: How to pause a loop

text:
# Question
Title: How to pause a loop
any ideas on how could i code this loop so when i press a button everything stops (Vernier stops reading temperature), and then when i press the button again it (Vernier reader) stars working.

```
   #include "VernierLib.h"
    VernierLib Vernier;
    #define led 13
    #define button 12
    int switchState = 0;
    float sensorReading;
    void setup() {
      Serial.begin(9600);
      Serial.println(Vernier.sensorName());
      Vernier.autoID();
      pinMode(12, INPUT);
    }
    void loop() {
      static float base_temp = 0;
      static float t = 0;
      t = Serial.parseFloat();
      if (t != 0) {
        base_temp = t;
      }
      sensorReading = Vernier.readSensor();
      Serial.print(sensorReading);
      Serial.print(" ");
      Serial.println(Vernier.sensorUnits());
      Serial.print("Željena temperatura: ");
      Serial.println(base_temp);
      if (base_temp > sensorReading) {
        digitalWrite(led, HIGH);
      } else {
        digitalWrite(led, LOW);
      }
      delay(1500);
    }

```

# Answer
Assume you did `#define BUTTON 12` as I suggested.

Somewhere inside your loop you could code:

```
if (digitalRead(BUTTON) {        // First button press
  while (digitalRead(BUTTON));   // Wait till button release
  while (!digitalRead(BUTTON));  // Wait till second button press
  while (digitalRead(BUTTON));   // Wait till button release
}

```

This "hangs" from the first button press to the second button release. The code assumes your button takes pin 12 HIGH when pressed and LOW otherwise. This is a bit difficult to realize in hardware (well, not really; but you will beed an external Pull-Down resistor). The easier way will be to connect pin 12 to GND when button is pressed, and use the internal PullUp-resistor: `pinMode(BUTTON, INPUT_PULLUP);`. Then the logic of the `while` condition has to be reverted:

```
if (!digitalRead(BUTTON) {        // First button press
  while (!digitalRead(BUTTON));   // Wait till button release
  while (digitalRead(BUTTON));    // Wait till second button press
  while (!digitalRead(BUTTON));   // Wait till button release
}

```
> 2 votes

# Answer
For reading the button I suggest using the Bounce2 library. Then you can wire your button to a fitting digital pin, the other side to ground. Use

```
button.attach( BUTTON_PIN ,  INPUT_PULLUP );

```

To use the internal pullup of the Arduino. Define a global state variable, that holds, if your code should run or not.

```
bool code_running = true;

```

Then in your main code (additional to calling the update function of the library) use

```
if(button.fell()){
    code_running = !code_running;
}

```

to toggle the state variable on button presses. Then, still in `void loop()`, use an if statement with the state variable to execute your code:

```
if(code_running){
    // put your code here
}

```

Note, that your code should not block for long periods for this to work correctly. You should always write your code in a non-blocking way, meaning, that no function call or loop will take longer than a few ms to execute. Otherwise your button action will not be responsive enough.
> 1 votes

---
Tags: arduino-uno
---


title: L298N motor driver problems

text:
# Question
Title: L298N motor driver problems
(edited)

So sorry my bad. To make it clear:

From the picture that I posted, I need to press the PBA (as Button1) so that both motors can run in forward (CW-clockwise) and backward (CCW-counterclockwise) and a stop.

While on the other hand, PBB (as button2) is for another condition both motors can run in left, right, and stop.

*Problems*:

1. When I run my code, it appears glitching from my LCD display.
2. I able to achieve for PBB side but for PBA side, both motors don't move at all.
3. I had use potentiometer to adjust my speed. The potentiometer are doing fine.
4. I use debounce for both my buttons and I am not sure whether the debounce effect my `void setmode(int Mode, int MotorMode1){}`

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

boolean lastButton=LOW;
boolean currentButton = LOW;

boolean last1Button = LOW;
boolean current1Button = LOW;

boolean debounce(boolean last){
    boolean current = digitalRead(PBA);
    if (last != current) {
      delay(5);
      current = digitalRead(PBA);
      return current;
    }
  }

  boolean debounce1(boolean last1) {
    boolean current1 = digitalRead(PBB);
    if (last1 != current1) {
      delay(5);
      current1 = digitalRead(PBB);
      return current1;
    }
  }

  int Mode = 0;
  int motorMode1 = 0;

  void loop() {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SPEED:");
    lcd.setCursor(0, 1);

    // potentiometer LCD
    float inputValue = analogRead (pot);
    inputValue = map(inputValue, 0, 1023, 0, 100);
    lcd.setCursor(7, 0);
    lcd.print (inputValue);
    lcd.setCursor(12, 0);
    lcd.print ("%");

    //read values from potentiometer
    MotorSpeed = analogRead(SpeedControl);
    MotorSpeed = map(MotorSpeed, 0 , 1023 , 0 , 255);
    // adjust to prevent at low speed
    if (MotorSpeed < 8)MotorSpeed = 0;
    //set the motor speed
    //analogWrite (enA, MotorSpeed);
    //analogWrite (enB, MotorSpeed);
    // MotorLCD
    lcd.setCursor(0, 1);
    lcd.print("MOVE:");

    currentButton = debounce(lastButton);
    if (currentButton == HIGH && lastButton == LOW) {
      Mode++;
    }
    lastButton = currentButton;
    if (Mode == 3){
      Mode = 0;
    }

    current1Button = debounce1(last1Button);
    if (last1Button == HIGH && current1Button == LOW) {
      motorMode1++;

    }
    last1Button = current1Button;
    if (motorMode1 == 3){
      motorMode1 = 0;
    }

  setMode( Mode, motorMode1);

 }

  void setMode(int Mode, int motorMode1) {
    analogWrite (enA, MotorSpeed);
    analogWrite (enB, MotorSpeed);

    if (Mode == 1 ) {
      lcd.setCursor(5, 8);
      lcd.print("Forward");

      //MOTOR_A CLOCKWISE MAX SPEED
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);

      //MOTOR_B CLOCKWISE MAX SPEED
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
    }
    if (Mode == 2) {
      lcd.setCursor(5, 8);
      lcd.print("Reverse");

      //MOTOR_A COUNTERCLOCKWISE MAX SPEED
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);

      //MOTOR_B COUNTERCLOCKWISE MAX SPEED
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);

    }

   if (motorMode1 == 1) {

      lcd.setCursor(5, 8);
      lcd.print("Right");
      //MOTOR_A CLOCKWISE MAX SPEED
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      //MOTOR_B COUNTERCLOCKWISE MAX SPEED
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);

    }
    if (motorMode1 == 2) {
      lcd.setCursor(5, 8);
      lcd.print("Left");
      //MOTOR_A COUNTERCLOCKWISE MAX SPEED
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      //MOTOR_B CLOCKWISE MAX SPEED
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);

    }
     if (Mode == 0 || motorMode1 == 0) {
      lcd.setCursor(5, 8);
      lcd.print("Stop");
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
    }
  }

```

# Answer
I hope I understood you correctly. The best way would be to tell you how you can use states to get the problem solved. But that would cost me too much time.

I decided to edit your program. I have no hardware to try it. So it is just an example to show you the idea. Perhaps it works as it is.

Please check the comments. If you are really interested in understanding to problem and the solution and things are unclear, you (or others) can ask with comments below. And of cause, if you find an error, I would be happy to know about it and correct it. ;-)

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// These are the different movement states
#define STATE_STOP 0
#define STATE_LEFT 1
#define STATE_RIGHT 2
#define STATE_FORWARD 3
#define STATE_BACKWARD 4

// always use expressive names

// The pin assignments
//////////////////////////////////////////////

// Analog
int pinPotiSpeed = A0;

// Motor A
int pinEnA = 9;
int pinInA1 = 8;
int pinInA2 = 7;

// Motor B
int pinEnB = 3;
int pinInB1 = 5;
int pinInB2 = 4;

// Buttons
const int pinBtnDir = 10;
const int pinBtnTurn = 11 ;

int stateMotors = STATE_STOP;
boolean flagBtnDirPressed = LOW;
boolean flagBtnTurnPressed = LOW;

int stateMotorsSpeed = 0;
int speedPercent = map( stateMotorsSpeed, 0, 255, 0, 100 );

LiquidCrystal_I2C lcd(0x27, 16, 2);

// I have not the time to think a lot about this debouncing, but
// I have a bad feeling. If the Arduino does not react on button presses
// or the mode change to quick please let me know. I'll have a look on it, if
// necessary. ;-)
boolean readButtonAndDebounce(int btnPin, boolean lastState)
{
    boolean actualState = digitalRead(btnPin);
    if (lastState != actualState)
    {
      delay(15);
      actualState = digitalRead(btnPin);
      return actualState;
    }

    // this return was missing in the original program
    return actualState;
}

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

    pinMode(pinEnA, OUTPUT);
    pinMode(pinInA1, OUTPUT);
    pinMode(pinInA2, OUTPUT);

    pinMode(pinEnB, OUTPUT);
    pinMode(pinInB1, OUTPUT);
    pinMode(pinInB2, OUTPUT);

    pinMode(pinBtnDir, INPUT);
    pinMode(pinBtnTurn, INPUT);

    digitalWrite(pinInA1,LOW);
    digitalWrite(pinInA2,LOW);

    digitalWrite(pinInB1,LOW);
    digitalWrite(pinInB2,LOW);

    lcd.init();
    lcd.backlight();

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SPEED:");
    lcd.setCursor(0, 1);

    lcd.setCursor(7, 0);
    // convert 0-255 to 0%-100%
    lcd.print ("0 %");

    lcd.setCursor(0, 1);
    lcd.print("MOVE: Stop");
}

void loop()
{
    stateMotorsSpeed = map( analogRead( pinPotiSpeed ), 0, 1023, 0, 255 );
    if ( stateMotorsSpeed < 8 ) stateMotorsSpeed = 0;
    speedPercent = map( stateMotorsSpeed, 0, 255, 0, 100 );

    boolean flagBtnDirPressedOld = flagBtnDirPressed;
    flagBtnDirPressed = readButtonAndDebounce( pinBtnDir, flagBtnDirPressed );

    boolean flagBtnTurnPressedOld = flagBtnTurnPressed;
    flagBtnTurnPressed = readButtonAndDebounce( pinBtnTurn, flagBtnTurnPressed );

    // this is a bit tricky, because I don't know if i understood the problem correctly.
    // My problem is, what happens if both button are pressed, I decided to give
    // the Direction button the precedence
    if ( flagBtnDirPressed && ! flagBtnDirPressedOld )
    {
      switch( stateMotors )
      {
        case STATE_STOP:
          stateMotors = STATE_FORWARD;
          break;

        case STATE_FORWARD:
          stateMotors = STATE_BACKWARD;
          break;

        case STATE_BACKWARD:
          stateMotors = STATE_STOP;
          break;

        default:
          // this happens if a state from the other button is active
          // The table does not include a rule what to do in this case.
          // Perhaps you could count button click modulo 3 for each button
          // and then you can switch to the correct state
          stateMotors = STATE_STOP;
      }

    }
    else if ( flagBtnTurnPressed && ! flagBtnTurnPressedOld )
    {
      // this is only entered if press state of the direction button has not changed
      switch( stateMotors )
      {
        case STATE_STOP:
          stateMotors = STATE_RIGHT;
          break;

        case STATE_RIGHT:
          stateMotors = STATE_LEFT;
          break;

        case STATE_LEFT:
          stateMotors = STATE_STOP;
          break;

        default:
          // this happens if a state from the other button is active
          stateMotors = STATE_STOP;
      }
    }

    controlMotorAndUpdateLcd();
}

void setMotorSignals( boolean sigA1 , boolean sigA2, boolean sigB1, boolean sigB2 )
{
      //MOTOR_A
      digitalWrite(pinInA1, sigA1);
      digitalWrite(pinInA2, sigA2);

      //MOTOR_B
      digitalWrite(pinInB1, sigB1);
      digitalWrite(pinInB2, sigB2);
}

void controlMotorAndUpdateLcd()
{
    lcd.clear();
    lcd.setCursor( 0, 0 );
    lcd.print( "SPEED:" );
    lcd.setCursor( 0, 1 );

    // potentiometer LCD
    lcd.setCursor( 7, 0 );
    lcd.print ( speedPercent );
    lcd.setCursor( 12, 0 );
    lcd.print ("%");

    analogWrite ( pinEnA, stateMotorsSpeed );
    analogWrite ( pinEnB, stateMotorsSpeed );

    // MotorLCD
    lcd.setCursor(0, 1);
    lcd.print("MOVE:");

    lcd.setCursor(5, 8);
    switch( stateMotors )
    {
      case STATE_STOP:
        lcd.print("Stop");
        setMotorSignals( LOW, LOW, LOW, LOW);
        break;

      case STATE_FORWARD:
        lcd.print("Forward");
        setMotorSignals( HIGH, LOW, HIGH, LOW);
        break;

      case STATE_BACKWARD:
        lcd.print("Reverse");
        setMotorSignals( LOW, HIGH, LOW, HIGH);
        break;

       case STATE_LEFT:
        lcd.print("Left");
        setMotorSignals( HIGH, LOW, LOW, HIGH);
        break;

      case STATE_RIGHT:
        lcd.print("Right");
        setMotorSignals( LOW, HIGH, HIGH, LOW);
        break;
    }
}

```
> 1 votes

---
Tags: arduino-uno
---


title: Can arduino nano drive two circuit

text:
# Question
Title: Can arduino nano drive two circuit
I am building a robot snake with a bunch of servos and ov7670. As I see, ov7670 operate with 3.3v and servos needs 5v. I will use Lipo battery for servos for this I need to connect ground pin of arduino and input of battery. But For ov7670, I already connect the ground pin of arduino. Can I connect ground with a jumper to another breadboard to connect with lipo battery and servos or I need two arduino nanos?

# Answer
> 2 votes
You can use a common ground in fact it's the normal thing to do with external circuits such as relays, servos etc

---
Tags: arduino-nano, motor, servo, battery, lipo
---


title: Program ESP01 and keep it after reboot

text:
# Question
Title: Program ESP01 and keep it after reboot
I am bit of a noob when it comes to ESP programming. I have an ESP01 and a USB programmer for it, but every time I unplug it, it resets, which makes me wonder how can I make it battery-powered since every reboot resets the program.

# Answer
> 1 votes
The ESP-01 ... and all ESP8622 ... have two modes for operation.

1. Flash mode / Boot load mode - on bootup (at the time an electrical current is first applied, or after the reset pin is grounded), if the GPIO0 (GPIO Zero) pin {On the ESP-01 this is the 7th pin} is connected to ground, the chip goes into non-run, receive program mode. This is where you load the compiled program.
2. Normal - on bootup (as above), but GPIO0 is ***NOT*** ground, then the ESP-01 goes into run mode.

---
Tags: esp8266
---


# Question
Title: Routing Arduino Mega output to either one of two serial ports
I have an Arduino Mega controller that normally communicates via Bluetooth (HC08 Bluetooth module) to an Android device. In case there is a problem on the Android side I wish to have a fallback ability to communicate via the USB serial port. The choice of serial port is determined by a hardware switch that the Arduino can read. Currently I have:

```
HardwareSerial & Terminal = Serial;
HardwareSerial & BTPort = Serial1;

```

Is there a way to route an output to either BTPort or to terminal, dependent on the state of the switch? Ideally I would like to do something like this:

```
HardwareSerial & OutputPort
if(switch_is_on)
  OutputPort = Terminal;
else
  OutputPort = BTPort;

```

Obviously the above code does not work. I have no idea of how to proceed.

# Answer
> 1 votes
I can think of three distinct ways (and one that is similar to another) of doing what you want.

But first a note on *polymorphism*. The `HardwareSerial` class is itself a child of the `Stream` class. It's this `Stream` class that provides all the read/write functionality (it, itself, is a child of the `Print` class which provides all the `print(...)` functions).

If all you want to do is print then you should be working with the `Print` class. if you want to do both reading and writing then the `Stream` class is what you want. You should only use `HardwareSerial` if you *need* to use the Serial-specific functions like `.begin(baud)`.

So with that in mind you could:

# 1. Assign a pointer

```
Print *printer;

void setup() {
    Serial.begin(115200);
    Serial1.begin(115200);
    printer = &Serial;
}

void loop() {
    printer = &Serial;
    printer->println(millis());
    delay(100);
    printer = &Serial1;
    printer->println(millis());
    delay(100);
}

```

This is by far the most efficient method from a purely machine perspective.

Note the use of `->` instead of `.` when calling a function on a pointer.

# 2a. Use a wrapper function

```
uint8_t stream = 0;

void printit(const char *text) {
    switch (stream) {
        case 0:
            Serial.print(text);
            break;
        case 1:
            Serial1.print(text);
            break;
    }
}

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

void loop() {
    stream = 0;
    printit("Hello on stream 0\r\n");
    stream = 1;
    printit("Hello on stream 1\r\n");
}

```

This is less efficient and limits what you can print unless you write lots of overloaded functions.

# 2b. Use a macro

This is like 2a but uses a macro instead of a function:

```
#define printit(T) if (stream == 0) Serial.print(T) else Serial1.print(T)

```

This keeps the standard overloading of the print function but has lots of IF statements littered through your code. A fraction more efficient than 2a since it's all inline. Harder for a human to understand though.

# 3. Create a wrapper class

This is the rolls-royce method. Everything becomes encapsulated in your own object. Pointers are used to keep it efficient.

```
class Printer : public Print {
    private:
        Print *stream;
        Print *stream0;
        Print *stream1;
    public:
        Printer(Print &s0, Print &s1) : stream0(&s0), stream1(&s1) {
            stream = &s0;
        }
        size_t write(uint8_t c) {
            return stream->write(c);
        }
        void setStream(uint8_t sno) {
            switch (sno) {
                case 0: stream = stream0; break;
                case 1: stream = stream1; break;
            }
        }
};

Printer printer(Serial, Serial1);

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

void loop() {
    printer.setStream(0);
    printer.println(millis());
    delay(100);
    printer.setStream(1);
    printer.prinln(millis());
    delay(100);
}

```

With this method the new class could be put into a library and used across your projects.

You also get all the functions you'd normally get with the `Serial` object when printing (for reading change `Print` to `Stream` and implement all the *pure virtual* functions you need for that class).

And a footnote for all those that say "Why use pointers? Why not references?" I say: I hate references. Pointers are far more obvious what they are. References you can't tell apart from distinct variables. With a pointer you know it's a pointer. References are the spawn of the devil.

---
Tags: serial, arduino-mega
---


# Question
Title: BLDC geared motor with encoder - How to wire the encoder? (6 wires)
I am quite a newbie to Arduino and currently stuck with an encoder.

I have a BLDC geared motor with encoder, all I want to do is to get values from the encoder.

There are 6 wires: out A, out B, out Z, +V, 0V, FG. How should I wire the six of them correctly?

Encoder specification says 5 VDC is OK to power it, and I want to make a circuit to power an encoder using an Arduino Mega board.

# Answer
This should be in the documentation of the motor or encoder, and that is the first place to look.

If you don't have any documentation, here is my best guess:

ABZ suggests it is an *incremental encoder* with channel A and B for *quadrature encoding* (giving direction and speed), with Z as the *index pulse* for getting absolute position once every rotation. FG is most probably Frame Ground, or maybe be the Fault signal.

How you wire it all depends on what you want to do with it, but knowing what each signal is should make it easy enough.
> 1 votes

---
Tags: arduino-mega, rotary-encoder
---


# Question
Title: How to upload code without closing puTTY
My question is quite simple: can you, somehow, upload Arduino code without closing puTTY's serial console? I hate having to close the program to open it again for reading the incoming information.

# Answer
You can't. Putty has no way of disconnecting without closing the program (as far as I can tell).

You could try "Tera Term" which apparently (though I don't use Windows so have no experience with it) has a disconnect option (which you would have to use before uploading).

Alternatively, as @Juraj has mentioned, you could use a separate USB to TTL UART adaptor to provide a second debug serial port (either with SoftwareSerial or mirroring the TX pin of the Arduino directly - don't connect RX in this case) which doesn't interfere with software upload.
> 2 votes

# Answer
There is an open source project that will do what you want.

http://com0com.sourceforge.net/

The com0com will create virtual com ports for the programs to connect to.

The hub4com will allow you to route data between the physical port and multiple virtual com ports.

http://com0com.sourceforge.net/hub4com/ReadMe.txt
> 6 votes

---
Tags: serial, c, uart, avrdude
---


title: Which Arduino-Board do I need?

text:
# Question
Title: Which Arduino-Board do I need?
I want to use a single Arduino board and link it to both the ANALOG CO2 GAS SENSOR (MG-811 SENSOR) and ANALOG PH SENSOR - METER KIT. I was wondering if the Uno Rev 3 had enough pins or do I have to go with the Mega.

# Answer
Nano board has a bunch of analog and digital pins. It does good and cheap. But for convenience UNO board is preferable for its large size easy handling and easy pin and wiring management.
> 1 votes

# Answer
Uno has enough pins. You'll probably need an analog pin for each measured quantity, and you might want a few digital pins to turn them on or off or make mode changes, if any. The next question is: what your project meant to do, and does the Uno have enough memory to accomplish it? You will probably go quite a way with an Uno before your project exceeds its capabilities, unless you have some unusually stringent requirements.
> 0 votes

---
Tags: arduino-uno, arduino-mega, sensors
---


title: MFRC522 not scanning card

text:
# Question
Title: MFRC522 not scanning card
So I have an Arduino Uno and an MFRC-522 reader, using a breadboard I've wired it up according to the example sketch which is the mfrc522 DumpInfo sketch.

```
/*Typical pin layout used:
 *
 *             MFRC522      Arduino
 *             Reader/PCD   Uno/101
 * Signal      Pin          Pin
 * -------------------------------
 * RST/Reset   RST          9
 * SPI SS      SDA(SS)      10
 * SPI MOSI    MOSI         11 / ICSP-4
 * SPI MISO    MISO         12 / ICSP-1
 * SPI SCK     SCK          13 / ICSP-3
 */

```

I've checked the wiring hundreds of times. The console shows Firmware Version: 0x92 = v2.0 Scan PICC to see UID, SAK, type, and data blocks...

but getting a card near the chip, will not scan or dump any info no other information appears on the serial monitor.

I've tried with mifare classic 1k cards a Nexus 6 and a Samsung Galaxy S7

Edit: Everything

```
    /*
    * ------------------------------------------------------------------------------------------------------------------
    * Example sketch/program showing how to read data from a PICC to serial.
    * --------------------------------------------------------------------------------------------------------------------
    * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
    *
    * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
    * Reader on the Arduino SPI interface.
    *
    * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
    * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
    * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
    * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
    * when removing the PICC from reading distance too early.
    *
    * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
 * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
 * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
 * keep the PICCs at reading distance until complete.
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init();     // Init MFRC522
    mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    // Dump debug info about the card; PICC_HaltA() is automatically called
    mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

```

datasheet Nxp website /documents/data\_sheet/MFRC522.pdf

# Answer
your breadboard can be buggy. In addition, are you connected VCC to 3V or 5V?
As I remember, you need to connect it to 3V.
> 1 votes

# Answer
```
#include <SPI.h>
#include <MFRC522.h>

void setup() {
  Serial.begin(9600);
  SPI.begin();
  RFID.PCD_Init();      // MFRC522
}
#define SS_PIN 10
#define RST_PIN 9

MFRC522 RFID(SS_PIN, RST_PIN);

void loop() {
  if (!RFID.PICC_IsNewCardPresent() || !RFID.PICC_ReadCardSerial())
    return;

  String buffer;
  for (byte byte = 0 ; byte < RFID.uid.size ; byte++)
    buffer += String(RFID.uid.uidByte[byte] < 0x10 ? " 0" : " ") + String(RFID.uid.uidByte[byte], HEX);
  Serial.println("NUID: " + buffer);

  RFID.PICC_HaltA();
  RFID.PCD_StopCrypto1();
}

```
> 1 votes

# Answer
I had a similar problem. I used I2C to check if the board can see the reader. If I2C Bus doesn't detect your reader, then one of your soldering must be faulty... check with a meter and carefully re-solder the erring pin.
> 1 votes

# Answer
I have several of this board with this condition. As I checked ,they all return the same thing as you send in SPI . I think all of them have hardware problem. Common thing for all of them is In past I supplied them with switching supply and I think this is why they got broken(this chip is very sensitive with supply voltage and **YOU MUST NOT CONNECT THEM TO MORE THAN 3.3V EVEN FOR VERY SHORT TIME**) . I highly recommend use of Linear regulator for them
> 1 votes

# Answer
Same problem as above. Three card readers. Two worked. One didn't. All three readers had two pins bridged on the reader chip. The bridged pins were close to the pin 1 corner. I left the bridge alone as all three readers had the same bridge and one of the pins did not have a trace to it. The faulty card reader also had two pins bridged with solder in a different location. Both pins had separate traces. I removed the solder bridge and the faulty card reader was no longer faulty.
> 1 votes

# Answer
I figured out that one get these kind of problems (reader get´s firmware version but can not read tags) are related to power consumption. I tried to power the reader with Heltec Lora 32 Dev board and it schowed exactly this behaviour. Now, connected to another 3,3V source everything works as it should :)
> 1 votes

# Answer
Maybe you need a function **TO PRINT THE READINGS!!!**

This is the loop and a function to print it:

```
void loop() {
  if ( ! rfid.PICC_IsNewCardPresent())
    return;
  if ( ! rfid.PICC_ReadCardSerial())
    return;

    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }

    Serial.println(F("The NUID tag is:"));
    Serial.print(F("In hex: "));
    printHex(rfid.uid.uidByte, rfid.uid.size);

  rfid.PICC_HaltA();
  rfid.PCD_StopCrypto1();
}

void printHex(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }

}

```
> 0 votes

---
Tags: arduino-uno, rfid
---


# Question
Title: What is the over-volt, over-current or over-power limit on a pin to an Arduino Mega 2560
I have an input voltage going to an Arduino pin that could be up to 5.25 V. I have many options on solving the problem but the simplest would be to include an inline resistor that limits the power that the over-voltage can deliver to the board.

I have done some experiments with the board using a pin that is set to `INPUT`, `INPUT_PULLUP`, `OUTPUT` set to low and `OUTPUT` set to high. I sent a voltage through a 33 kOhm resistor to the pin in those configurations, and swept 0-6V across the resistor. The pin voltage when in `OUTPUT` mode was very rigid, holding its output perfectly against the resistor.

When in either `INPUT` mode, the overvoltages seemed to happily pass through the resistor, driving at most 65 uA and 0.15 mW into the pin while it was raised to the 5.5 V value. it seems to me then that the Arduino pins are quite resilient to overvoltage, but this might be an incorrect assessment.

# Answer
> 0 votes
The maximum voltage on any IO pin is VCC+0.5V or 5.5V when powered from 5V.

The maximum "injected" current is not specified in the datasheet, but typically 1mA is a reasonable value to assume.

So 5.25V at 65uA is, while not ideal, at least tolerable.

# Answer
> 0 votes
The ATMega2560 Datasheet is here:

Microchip ATMeta2560 Datasheet

The important section for questions like this is: **ABSOLUTE MAXIMUM RATINGS**

For this chip we are provided:

Note the Voltage on any Pin... specification that I have highlighted. This says that under NO circumstances should you allow a pin to go below -0.5V or above (Vcc + 0.5V) or you risk damaging the chip. So if you are running at 5.0V that means you can safely apply a voltage of +5.5V to the pin.

Your 0-6V signal is over the limit for this device and you will fall into the other section that I highlighted, the "NOTICE".

---
Tags: voltage-protection
---


# Question
Title: I have made a Nano send 4 pot values to an Uno please help with code
Happy New Year!

So I have made a Nano send 4 pot values to an Arduino Uno over serial but I have a problem: I don't know how to separate these values. Here's the code:

Master:

```
    int Pot = A0;
    int Pot2 = A1;
    int Pot3 = A2;
    int Pot4 = A3;

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

    void loop() {
      int Value = analogRead(Pot);
      int Value2 = analogRead(Pot2);
      int Value3 = analogRead(Pot3);
      int Value4 = analogRead(Pot4);
      Serial.write(Value); //Write the serial data
      Serial.write(Value2); //Write the serial data
      Serial.write(Value3); //Write the serial data
      Serial.write(Value4); //Write the serial data
      delay(150);
    }

```

Slave:

```
    int incomingByte; // for incoming serial data

    void setup() {
      Serial.begin(115200); // opens serial port, sets data rate to 9600 bps
    }

    void loop() {
      // send data only when you receive data:
      if (Serial.available() > 0) {
        // read the incoming byte:
        incomingByte = Serial.read();

        // say what you got:
        Serial.print("I received: ");
        Serial.println(incomingByte, DEC);
      }
    }

```

And a bit from the serial logs:

```
    I received: 255
    I received: 247
    I received: 11
    I received: 0

```

It updates and sends these four values for the four pots, it can read them but they are together, and it sometimes also kind of lags if I can say it like that; it sometimes takes longer to update but then it goes to normal again.

Thanks!

# Answer
> 1 votes
This is actually a huge topic, one that I could write volumes on. However I will try and be concise. But it is such a common question it's time to finally write a definitive answer.

Sending data between devices, be that computers, Arduinos, or anything else like that, is very much like speaking to someone.

It is very common to do something like you have done and just "send" the data. However that is, as you have rightly noticed, very much akin to sending someone a message all in capitals with no spaces or punctuation. Like this:

> WHATAPIECEOFWORKISMANHOWNOBLEINREASONHOWINFINITEINFACULTYINFORMANDMOVINGHOWEXPRESSANDADMIRABLEINACTIONHOWLIKEANANGELINAPPREHENSIONHOWLIKEAGODTHEBEAUTYOFTHEWORLDTHEPARAGONOFANIMALSANDYETTOMEWHATISTHISQUINTESSENCEOFDUSTMANDELIGHTSNOTMENONORWOMANEITHERTHOUGHBYYOURSMILINGYOUSEEMTOSAYSO

Only through effort and the application of known predefined standards (i.e., English vocabulary) is it possible to make out what the message says.

So in language we introduce "meta" information - that is, information in a message that tells you not about the content of the message, but about the message itself. The simplest is to introduce spaces to indicate where words start and end. So that message now becomes:

> WHAT A PIECE OF WORK IS MAN HOW NOBLE IN REASON HOW INFINITE IN FACULTY IN FORM AND MOVING HOW EXPRESS AND ADMIRABLE IN ACTION HOW LIKE AN ANGEL IN APPREHENSION HOW LIKE A GOD THE BEAUTY OF THE WORLD THE PARAGON OF ANIMALS AND YET TO ME WHAT IS THIS QUINTESSENCE OF DUST MAN DELIGHTS NOT ME NO NOR WOMAN EITHER THOUGH BY YOUR SMILING YOU SEEM TO SAY SO

There, that's much more readable. But still lacking. So we add more "meta" characters that provide even more information about the formation of the message: punctuation. Now we can have:

> What a piece of work is a man! How noble in reason, how infinite in faculty! In form and moving how express and admirable! In action how like an Angel! in apprehension how like a god! The beauty of the world! The paragon of animals! And yet to me, what is this quintessence of dust? Man delights not me; no, nor Woman neither; though by your smiling you seem to say so.

And now the message is completely plain. What we have done here is introduce characters that aren't part of the message but form the structure of the message. These characters are distinct from the message by being of a different type of character. Not letters, but symbols instead. It's possible to add any symbol you could imagine and attach a meaning to it to convey any information about the message you like. There is no limit.

But that's where computer communication differs.

When sending data over serial you have a limited range of values you can send. You have one byte for sending information, which means that you can only send one of 256 possible "symbols".

When you're sending, as you are, binary data you use all 256 symbols for your data. There are no symbols left for any "punctuation" in your message. It becomes impossible to go even from the first to the second examples above, let alone the third.

So what can be done?

Well, there's two approaches:

1. Re-encode your data to use less "symbols" leaving some available for meta information
2. Nominate some of the symbols used for data to be also used for meta information and create some way of distinguishing them from the actual data

The first method is probably the simplest - change the data encoding to use a smaller range of symbols. The most obvious way is to use ASCII encoding - use just 10 symbols to represent numerical data, but use a lot more of them. I'm sure you know the symbols: "0123456789". You then have such standard symbols as "New Line" (or `\n`) to mark when your message is finished, and commas to separate different parts of your message.

It's easy to encode and transmit, but harder to receive. Sending is as simple as:

```
Serial.print(Value);
Serial.print(F(","));
Serial.print(Value2);
Serial.print(F(","));
Serial.print(Value3);
Serial.print(F(","));
Serial.println(Value4);

```

Receiving that data and making sense of it is far more involved. You have to read everything up to a comma (or to the end of the line and split it on a comma) and then convert the ASCII text back into numbers. It could be done on the fly on a character-by-character bases (read a character, if it's a number then multiply your current value by 10 and add the new number to it, if it's a comma then move on to to the next number, or if it's the end-of-line then reset to the first number again) or as a whole chunk of data (read the whole lot into a char array until you reach `\n` then split it with `strtok()` on the commas, and convert each chunk with `atoi()`).

That method though is not efficient. It takes a lot of bytes to represent just a small number (for instance the number 100 takes 3 bytes whereas the value 100 will fit into a single byte as a raw value), and processing it afterwards is slow and cumbersome.

Method 2 from the list above is far more efficient, but takes a little more in-depth knowledge and thought.

Step one is to design a strict format for your message. You need some way of saying "This is the start of the message" and "This is the end of the message" and everything in between is considered the data for the message. Since you are working with fixed sized variables you don't need anything within that data to separate the values.

You have 4 integer values. That's 8 bytes in total (each integer takes 2 bytes for 16 bits). You could pack those together in to a `struct` for easier handling:

```
struct data {
    int value1;
    int value2;
    int value3;
    int value4;
};

struct data values;

```

That is good if you have lots of different kinds of data, but since yours are all the same a simple array might be better:

```
int values[4];

```

Now the ASCII character set has a set of control characters that are intended to be used for building these kind of messages. For example character 2 is "STX" or "Start Of Text". Character 4 is "EOT" or "End Of Transmission". So you could choose to start your message with character 2, then send your 8 bytes, and follow it with character 4. Then you just look for a 2, read 8 bytes, and check it's followed by a 4. That would work, right?

Well, no. Not quite. What if you're sending the value 2 or 4 as part of your data? How would it distinguish those from the start/end characters? You can't.

It's now time to introduce a new concept: Data Link Escape. This is where you nominate another special character. This one says "The next character is data. Treat it as such". DLE is character 16 in ASCII, so you might like to use that. 27 is sometimes used too, or 255. You can use whatever you like, but I like 16 (DLE).

The idea here is that if you are sending a byte that could be either a control character or a data character (i.e., 2 or 4) then you *first* send the DLE character *if and only if that character should be interpreted as data*. So if you are sending a start byte you send just 2. If you're sending the value of 2 in your data you send 16 then 2.

But what, you ask, if you are sending the value 16 in your data? Simple: you just send it twice. The first time is the DLE character which says the next byte is data. The next is interpreted as data regardless because it's following the DLE character.

Sounds complex, yes? Well, not really. Let's visualise it. Take our original text message. Let's nominate A as the start of message and B as the end of message. We'll even add C as a space character. D will be our DLE character. Our message would now look like (I won't do it all, too tedious...):

> AWHDATCDACPIEDCECOFCWORKCISCMDANB

To you as a human it looks garbled, but that's because you're trying to apply standard English rules to it. But if we take it one character at a time and apply our new rules to it it's different:

* A - start of message
* W - letter W
* H - letter H
* D - Next character is a letter
* A - letter A
* T - letter T
* C - Space

... etc ...

We do just the same with your binary data. Let's say we're sending the values 23, 2, 16 and 1928 as integers. In little-endian (I'll go into that later on) that's represented as the values

```
23,0,2,0,16,0,136,7

```

so with our start and end characters, and adding our DLE character 16 we end up with

```
2,23,0,16,2,0,16,16,0,136,7,4

```

You might like to write a little function to send data in that format:

```

int values[4];

// Some symbols for easy reference
#define STX 2
#define EOT 4
#define DLE 16

void sendPacket(const uint8_t *data, int len) {
    Serial.write(STX);
    for (int i = 0; i < len; i++) {
        // Escape the special characters
        if ((data[i] == STX) || (data[i] == EOT) || (data[i] == DLE)) {
            Serial.write(DLE);
        }
        Serial.write(data[i]);
    }
    Serial.write(EOT);
}

// then use it:

sendPacket((uint8_t *)values, sizeof(values));

```

Now reception can be done one byte at a time and fed into your array as raw data. Something like this:

```

int values[4];

// Some symbols for easy reference
#define STX 2
#define EOT 4
#define DLE 16

bool rxData(uint8_t *data, int len) {
    static int pos = 0; // Where in the data are we now?
    static bool isDLE = false; // Are we in DLE mode?
    static bool messageStarted = false; // Are we receiving yet?

    if (Serial.available()) {
        int b = Serial.read(); // Read one byte

        if (!messageStarted) { // We're not receiving yet - should we start?
            if (b == STX) { // STX received, start receiving.
                messageStarted = true;
            }
            // Anything else is ignored.
            return false; // Message not complete yet
        }

        // If we're here we must be part way through receiving.

        // If we received a DLE last time then we always treat it as data
        if (isDLE) {
            data[pos++] = b;
            isDLE = false; // No longer in DLE mode
            if (pos > len) { // Too many bytes in the message, something bad happened
                // ABORT
                pos = 0;
                messageStarted = false;
            }
            return false; // Message not complete yet
        }

        // If we have an STX and we're not in DLE mode then we must be
        // out of sync. Reset the counter and flags and start a fresh message
        if (b == STX) {
            pos = 0;
            isDLE = false;
            return false; // Message not complete yet
        }

        // Are we at the end of the message?
        if (b == EOT) {
            if (pos == len) { // Did we receive the right number of bytes?
                messageStarted = false;
                return true; // Message complete
            }
            // Something bad must have happened. Not the right amount of
            // bytes received for a valid message. ABORT.
            messageStarted = false;
            pos = 0;
            isDLE = false;
            return false; // Message not complete yet
        }

        // Check for a DLE character
        if (b == DLE) {
            isDLE = true;
            return false; // Message not complete yet
        }

        // Anything else is a data byte.
        data[pos++] = b;
        if (pos > len) { // Too many bytes in the message, something bad happened
            // ABORT
            pos = 0;
            messageStarted = false;
        }
    }
    return false; // Message not complete yet
}

// Then use it:

if (rxData((uint8_t *)values, sizeof(values)) {
    Serial.print("You got: ");
    Serial.print(values[0]);
    Serial.print(", ");
    Serial.print(values[1]);
    Serial.print(", ");
    Serial.print(values[2]);
    Serial.print(", ");
    Serial.println(values[3]);
}

```

Now I haven't tested any of this code, so take it with a pinch of salt.

Now a little word on *endianness*. An integer is 16 bits in size. That takes two bytes to represent (2 x 8 = 16). The "endianness" of a system is the order in which those two bytes are stored in memory. In a little-endian system, like the Arduino, the value 1928 is stored as the bytes 136,7. But on a big-endian system it's stored as 7,136. The "biggest" (i.e., most significant byte) value comes first. When sending binary data like this it's vital to ensure that both ends of the link agree on the order of the bytes. And then there's word size to consider. 8-bit systems use a 16-bit word for integers. 32-bit systems use a 32-bit word. So sending an `int` from an Arduino to a Pi, for example, will cause confusion - the Arduino sends 2 bytes (for 16 bits) and the Pi expects 4 bytes (for 32 bits).

To combat the latter it is good to use the fixed width variable types that specify exactly how many bits are used. Instead of `int` use `uint16_t` (for **U**nsigned **INT**eger **16** bits). That way you're unambiguous about what size it is.

To combat the former problem (if needed) there are a standard set of functions that alter values from native to "network" endianness. Network endianness is a standard used for IP communication and is the same as big-endian. If you're only ever going to communicate between little-endian Arduinos then there's no real need for this. But if that is not going to be a certainty then using `htons()` for "Host to Network Short" and `ntohs()` for "Network to Host Short" ("short" is a 16 bit word, like `int16_t`) could be of benefit. It's best to use them when storing or retrieving values in your `values[]` array:

```
values[0] = htons(analogRead(0));

```

and:

```
Serial.print(ntohs(values[0]);

```

You may need to include the header `machine/endian.h` in your code depending on which system you're using.

I could go into so much more depth about things like variable length packets, checksums, sliding window reception and such, but for now this covers the basic concepts. Maybe I'll write a book.

# Answer
> 3 votes
If your goal is to "talk" to a computer vs. a human, then a format that can be parsed easily is better than one that is easy to read.

For example, you have:

```
I received: 255
I received: 247
I received: 11
I received: 0

```

While this could be parsed by your Uno, it will be a lot simpler if you send the data something like:

```
255|247|11|0

```

Now you can use a "C" string parsing function like strtok() to parse on the "|" character. Of course there are many other ways to do this as well but this is one possible solution to your question.

# Answer
> 0 votes
So like this? And also what kind of serial speeds do I use? @Majenko This is the sender:

```
    int pot1 = A0;
    int pot2 = A1;
    int pot3 = A2;
    int pot4 = A3;

    // Some symbols for easy reference
    #define STX 2
    #define EOT 4
    #define DLE 16

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

    void sendPacket(const uint8_t *data, int len) {
      Serial.write(STX);
      for (int i = 0; i < len; i++) {
        // Escape the special characters
        if ((data[i] == STX) || (data[i] == EOT) || (data[i] == DLE)) {
          Serial.write(DLE);
        }
        Serial.write(data[i]);
      }
      Serial.write(EOT);
    }

    void loop() {

      int values[4] = {analogRead(pot1), analogRead(pot2), analogRead(pot3), analogRead(pot4)};
      sendPacket((uint8_t *)values, sizeof(values));

    }

```

And this is the receiver:

```
int values[4];

// Some symbols for easy reference
#define STX 2
#define EOT 4
#define DLE 16

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

bool rxData(uint8_t *data, int len) {
  static int pos = 0; // Where in the data are we now?
  static bool isDLE = false; // Are we in DLE mode?
  static bool messageStarted = false; // Are we receiving yet?

  if (Serial.available()) {
    int b = Serial.read(); // Read one byte

    if (!messageStarted) { // We're not receiving yet - should we start?
      if (b == STX) { // STX received, start receiving.
        messageStarted = true;
      }
      // Anything else is ignored.
      return false; // Message not complete yet
    }

    // If we're here we must be part way through receiving.

    // If we received a DLE last time then we always treat it as data
    if (isDLE) {
      data[pos++] = b;
      isDLE = false; // No longer in DLE mode
      if (pos > len) { // Too many bytes in the message, something bad happened
        // ABORT
        pos = 0;
        messageStarted = false;
      }
      return false; // Message not complete yet
    }

    // If we have an STX and we're not in DLE mode then we must be
    // out of sync. Reset the counter and flags and start a fresh message
    if (b == STX) {
      pos = 0;
      isDLE = false;
      return false; // Message not complete yet
    }

    // Are we at the end of the message?
    if (b == EOT) {
      if (pos == len) { // Did we receive the right number of bytes?
        messageStarted = false;
        return true; // Message complete
      }
      // Something bad must have happened. Not the right amount of
      // bytes received for a valid message. ABORT.
      messageStarted = false;
      pos = 0;
      isDLE = false;
      return false; // Message not complete yet
    }

    // Check for a DLE character
    if (b == DLE) {
      isDLE = true;
      return false; // Message not complete yet
    }

    // Anything else is a data byte.
    data[pos++] = b;
    if (pos > len) { // Too many bytes in the message, something bad happened
      // ABORT
      pos = 0;
      messageStarted = false;
    }
  }
  return false; // Message not complete yet
}

void loop() {
  // put your main code here, to run repeatedly:
  if (rxData((uint8_t *)values, sizeof(values))) {
  Serial.print("You got: ");
    Serial.print(values[0]);
    Serial.print(", ");
    Serial.print(values[1]);
    Serial.print(", ");
    Serial.print(values[2]);
    Serial.print(", ");
    Serial.println(values[3]);
  }
}

```

---
Tags: arduino-uno, serial, arduino-nano, code-optimization, faq
---


# Question
Title: L293D motorshield with batteries doesn't power Arduino
Recently I came across a video about a guy building a remote Bluetooth-controlled Arduino car and I was quite amazed. So I decided I wanted to build it too. I have no Arduino or electronics experience at all other than being an IT professional.

So I bought the parts he used in the video (he advised a knockoff Arduino in the description).

After putting it all together the motors work through Bluetooth (yay!). But the issue is that the batteries connected to the motorshield don't give power to the Arduino at all (because the lights don't turn on).

When plugged in the laptop with the USB cable the Arduino gets powered and the motorshield light turns on just a bit, but not enough to make the motors and Bluetooth work.

So in short:

USB powered: Arduino works, motorshield light barely turns on, motors don't work, Bluetooth lights go on, but is not emitting a signal.

2x 18650 battery powered: motorshield light shines bright, Arduino doesn't work, Bluetooth lights don't flicker.

Both: everything works.

So for some reason, the batteries connected to the motorshield don't power the Arduino.

Video used: https://youtu.be/Q36NbjPMV5k

Circuit diagram:

Knockoff arduino:

L293D motor shield (I'm aware that the ground of the power isn't plugged in)

Parts used:

* Geekcreit UNO r3 ATmega16U2 AVR
* L293D motor shield
* Geekcreit HC-05 bluetooth
* 4 TT motor
* 2x 18650 3,7-4.2v 2200mah batteries

I really don't know what I did wrong, since I followed the video and did exactly what the person did. Maybe the batteries aren't powerful enough?

# Answer
The problem was that the 2 pins on which the jumper sits, the jumper or the board was broken (idk exactly). I might've caused that myself by turning on the batteries + powering it through usb at the same time.

I bought a new L293D board then made sure I didn't connect usb power to the arduino while the L293D was sitting on top of it. I uploaded the code, then disconnected the usb, put the L293D on top, powered it all and it works like a charm!
> 1 votes

# Answer
Nice project. The batteries are connected to the motor power which is correct but the motor shield does not output voltage to the 5V system. Try connecting the batteries to the Vin on the board and all should work.
> 0 votes

---
Tags: arduino-motor-shield, l293d
---


title: Can RX pin(s) be used as TX instead?

text:
# Question
Title: Can RX pin(s) be used as TX instead?
1. Title question. I do not need any receive communication pins, only transmission.

Actually, I need as many transmission pins as possible on any Arduino besides a Mega2560 (to re/write the EEPROM of slave devices). A Mega2560 has 23 TX/RX pin pairs.

Maybe I'm misunderstanding serial communication. And maybe some sort of multiplexing deal can work like One-Wire temperature sensors...such as `softwareSerials[x].write()`...

---

```
SoftwareSerial serialOne(2, 3); // Software Serial ONE
SoftwareSerial serialTwo(8, 9); // Software Serial TWO
                     // RX, TX

```
2. Is there a way to make all the pins using SoftwareSerial TX? Or do half need to be RX?

---

"Just take a better microcontroller, and that is all." - user1829200

3. What off-the-shelf microcontroller is geared for serial communication?

# Answer
> 1 votes
One way to communicate Arduino to Arduino device is UART (and Software Serial for additional pins). For the ESP32, it seems this allows 28 TX pins using Majenko's method (in their answer). In other words, slave 28 devices.

After further research, isn't I2C the clear route to go?

* With more slave devices the less times per second to talk to them all
* The application needs to have all the slave devices execute commands synchronously:
    + At least, the slave devices need to start functioning at the same time.

---

* How many slave Uno's/Nano's can be connected to an ESP32?

> Each device on an i2c network has a 7-bit address, so a single network theoretically supports up to 128 slave devices. In practice though, the limit is much lower. i2c slave chips often support only 8 different bus addresses, no more than 8 of that chip can be attached to the same i2c network.

https://mindbleach.com/words/2012/10/23/i2c-and-device-limits

Unclear answer:

# Answer
> 0 votes
You should be (though I haven't tested it) be able to set the RX pin to an unused pin number, such as 255. Then the RX pin will do nothing.

```
#include <SoftwareSerial.h>

SoftwareSerial s0(255, 2);
SoftwareSerial s1(255, 3);
SoftwareSerial s2(255, 4);
SoftwareSerial s3(255, 5);
SoftwareSerial s4(255, 6);
// ... etc ...

```

The "can't have more than one instance" thing is to do with reception. You can't have more than one SoftwareSerial instance *receiving* at once - but you don't care about that, since reception is not being used.

---
Tags: serial, softwareserial, communication
---


title: Arduino Pro Mini PWM issue

text:
# Question
Title: Arduino Pro Mini PWM issue
I want to create a small LED strip driver/controller with 2 channels (Cold/Warm white) using Arduino Pro Mini (5V/16MHz). I have connected the parts per the following diagram  I have pins 5 and 6 setup as output, control them via analogWrite, and it all works great on Arduino UNO.

The problem comes with Arduino mini pro. When one channel is set to 255 and the other is 0, the LED strip does light only in one color, which is OK and when I swap the PWM channel's values, the other light color starts to shine. So far so good. When I set both to 0, the strip keeps on shining at about 30% (I don't have a scope, so I can't tell what the pwm signal is doing). Varying the channels' pwm in the range 0-255 does affect the light somehow but it never goes down to a complete off.

Looking at the arduino uno and pro mini I can't see anything obvious that should make them act differently from the hardware perspective so I'm guessing there's a problem in the libraries or perhaps my arduino pro mini (a clone) is somehow messed up.

Has anyone observed this kind of behavior in Arduino pro mini and has a solution for it?

**Edit**: Added some measurements per @Abel's request. I measured both DC and AC with and without the LED strip connected.

Connecting the LED strip really does mess things up, but WHY? UNO can handle it, but the pro mini can't! I thought mini was basically just shrunk down arduino uno (both have the same SMD version of MEGA328P), but apparently there are some differences.

# Answer
> 1 votes
Thanks to comments I received from several people here I quadruple checked the wiring and eventualy found the problem. My recent Arduino Uno tests were done on a breadboard, but I had the Pro Mini prototype soldered on the prototyping board which has the holes connected in columns on the copper side. I made the cuts in all the necessary places ... but one! That one omission caused a short between pin 6 and the drain from the other channel's mosfet. The problem with these boards is that the parts are on one side and while flipping the board to the copper side, it is too easy to get lost in all the columns and miss something. The morales of this story are: "Never be too certain about your wiring/soldering" and "Arduino is pretty resistent to my attempts to fry it :)".

# Answer
> 0 votes
Nice clean design! Let's determine for sure what voltage it is outputting to the MOSFETs. Write a very simple sketch that cycles a pin every few seconds and measure the voltage. You should get ground and VCC. If it is less than 4.5 volts (guard band included) your FETs will give you problems as they will not be properly enhanced. Here is why: The IRF520 is a Power Mosfet with 9.2A collector current and 100V breakdown voltage. The mosfet has a low gate threshold voltage of 4V and hence commonly used with microcontrollers like Arduino for switching high current loads. You may have to get a different MOSFET with a lower gate threshold. Note there is some variation in the devices so they will not all but the same but will meet the specification. The 10K pull down resistors is a great addition and guarantees your state during reset until it is set up.

# Answer
> 0 votes
Get a good digital O'scope. They are incredibly cheap these days, and pay for themselves pretty rapidly in reduced frustration and time spinning one's wheels. I recently got a Hanmatek DOS1102 dual-channel 110MHz, and I haven't used my old analog Tek2236 since

---
Tags: pwm, arduino-mini
---


# Question
Title: SoftwareSerial read until available is empty only works with delay
I originally was only going to make my program work on an ESP until I needed it on an Arduino UNO (because I suspect my ESP is broken). I had to add SoftwareSerial support but because I didn't originally intend to, the strings I send from my app have no terminators on them. I thought this would be fine because I could do something like:

```
void loop()
{
    while (ble.available() > 0)
    {
        data += (char)ble.read();
    }

    if (ble.available() <= 0 && data.length() > 0)
    {
        ble.println(data);
        //do stuff
        data = "";
    }
}

```

All that is doing is creating a string out of the recieved characters. It then checks if there is nothing left to read, and stuff has already been read (ie `data` has a length), then print the data. What I expect the output to be is (if the input string in `03:255,255,255`):

```
03:255,255,255

```

What I actually get is:

```
0
3
:
2
5
5
,
//and so on

```

That is becuase, for some reason, even though `ble.available()` should return a number not 0 at the if statement, it returns 0 and therefore the statement will always become true. The only way I've fixed this is by adding in a little delay at the end of the loop. Whether that be:

```
delay(10)

```

or even this, in the while loop:

```
Serial.println(ble.available()) //This introduces enough delay somehow

```

Without having to modify my app, can I pull this off without using a delay? With delays it seems hacky especially because for all I know, for older or newer devices this delay could be too high or too low.

# Answer
> 4 votes
Serial does not transmit data as one bunch, but byte by byte. There can easily be some little delays introduced, especially, when transmitted via a packaged protocol like bluetooth, long enough, for the Arduino to not see any new data in its buffer. Also the transmission needs some time, depending on the baudrate. When you read faster from the buffer, than you receive, you will encounter an empty buffer after every byte.

Now with that information look at your code:

```
void loop()
{
    while (ble.available() > 0)
    {
        data += (char)ble.read();
    }

    if (ble.available() <= 0 && data.length() > 0)
    {
        ble.println(data);
        //do stuff
        data = "";
    }
}

```

Let's assume, the Arduino receives one byte, then a little pause happens, then the next data is received. The code will go into the while loop and read the received byte from the serial buffer. To stay in the while loop, the next byte has to be received in the execution time of the code inside of the while loop. That is incredible short. So after one byte there is nothing more inside the buffer, thus the while loop exits, because `ble.available()` returns zero. Then the if statement is executed, also rather fast. Most likely, `ble.available()` will still return zero. But you already put a character into the buffer, so the if statement is executed.

The delay solves your problem because then you read way slower than you receive. The data is mainly received while the delay runs. Then the rest of your code can read, what was already received and put into the buffer.

\**What to do instead of `delay()`: You need to make sure, that you always read a full message. There are different ways, depending on your requirements. If your messages always have the same length, you could wait, until the specified number of characters was received, and only then read them. But that will fail, if you for some reason (for example a reset of the Arduino) receive a partial message, which would cause a misalignment. You could clear the receive buffer, when you read a full message, that might help, if your data transmissions don't happen to often.

You could try to parse the incoming data according to the message format (which needs to stay constant for this purpose), like:

```
Read a number.
If it has a colon following it, it is a new message.
Then read number
    read comma
    read number
    read comma
    read number
Repeat.

```

For this purpose it would be fitting to read every byte, that gets received, and write then into your own circular buffer. You can then continuously add newly received characters at the end, while removing the already parsed messages from the start of the buffer.

---

You see, these ways have caveats and might be convoluted. The easiest way would be to add a delimiter/terminator to your messages, though from your question it sounds, as if this is not possible for you currently.

Note:

* None of the above is specific to `SoftwareSerial`. It's the same for hardware `Serial`.
* I suspect the code worked your ESP, because you had some other code there, which introduced a big enough delay (just like your `delay()` call)

---
Tags: arduino-uno, bluetooth, softwareserial
---


title: How to sense snow and ice?

text:
# Question
Title: How to sense snow and ice?
We are building an outdoor snow melting system for the pavement. It would be nice if it could turn on itself only when it is needed: if there is snow, ice in the surface or the pavement is wet and the temperature is below the freezing point. Is there a good way to detect if the surface of something is snowy, icy or wet?

# Answer
> 7 votes
If the pavement is black, you could detect snow by infrared reflectivity. You might detect wet by resistivity. That leaves ice. Reflectivity might work there, too, at a different threshold. You'd need to experiment.

Another possibility might be a short-range sonar. If the measured distance changes, something is there. Ice would probably read as nearer. You'd probably need to average a number of measurements to increase the measurement resolution; you care about very thin ice coatings. Snow might well read as no return - but again, experiment.

A combination of the reflectivity and sonar might be the most reliable.

# Answer
> 3 votes
I may experiment with a simple photocell used to turn lights on or off, and a light source for night time. Mount the photocell so that its lens is upwards towards the sky, at night you'd need a light source shining on the photocell, I'm thinking a very low wattage led light to reduce power consumption, or even another photocell or astronomical time clock to turn the light source on or off, depending on how complex you'd want to make it. When the photocell can no longer detect light you know it is covered. You'd have to experiment with the opaqueness of the snow, and how much coverage would block out the light. Seems like a cheap, easy, pretty much "out of the box" solution for snow anyway.

# Answer
> 0 votes
cheap video camera with snow detection software. See this article for a start

---
Tags: sensors, automatization
---