# Question
Title: TIMEOUT error when connecting ESP8266 to Arduino Uno
I am trying to set up my Arduino Uno to receive information from the internet, but I am having a very hard time finding proper guides online. I am using an Arduino Uno and ESP8266-01. I am trying to use the "WebClientRepeating" example from this library: https://github.com/bportaluri/WiFiEsp

Here is the code I am running (updated the SSID and password):

```
/*
 WiFiEsp example: WebClientRepeating

 This sketch connects to a web server and makes an HTTP request
 using an Arduino ESP8266 module.
 It repeats the HTTP call each 10 seconds.

 For more details see: http://yaab-arduino.blogspot.com/p/wifiesp.html
*/

#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6,7); // RX, TX
#endif

char ssid[] = "MY-SSID";            // your network SSID (name)
char pass[] = "MY-PASSWORD";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "arduino.cc";

unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10000L; // delay between updates, in milliseconds

// Initialize the Ethernet client object
WiFiEspClient client;

void setup()
{
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");

  printWifiStatus();
}

void loop()
{
  // if there's incoming data from the net connection send it out the serial port
  // this is for debugging purposes only
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if 10 seconds have passed since your last connection,
  // then connect again and send data
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server
void httpRequest()
{
  Serial.println();

  // close any connection before send a new request
  // this will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");

    // send the HTTP PUT request
    client.println(F("GET /asciilogo.txt HTTP/1.1"));
    client.println(F("Host: arduino.cc"));
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection
    Serial.println("Connection failed");
  }
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```

My wiring is as follows:

* ESP8266 RX - Uno Pin 7
* ESP8266 TX - Uno Pin 6
* ESP8266 VCC - 3.3V power source (not from Uno)
* ESP8266 GND - Uno GND
* ESP8266 CH\_PD - 3.3V power source (not from Uno)

I also connected the GND of the 3.3V power source to the other GNDs.

When I go to run the WebClientRepeating example, my Serial output says:

```
11:05:04.764 -> [WiFiEsp] Initializing ESP module
11:05:05.760 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:07.785 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:09.758 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:11.780 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:13.803 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:14.794 -> [WiFiEsp] Cannot initialize ESP module
11:05:20.794 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:20.794 -> [WiFiEsp] No tag found
11:05:20.830 -> WiFi shield not present

```

The tutorial specifies that it uses a "ESP WiFi shield" but I am using a ESP8266 card only - could that be part of the problem? If that is a problem, are there any simple guides out there for how to connect the Arduino Uno to the internet to read information? I am frustrated with the lack of good documentation, and would really appreciate some help.

# Answer
It means that your ESP8266 is not detected

Because of you connect RX and TX (6 and 7) to secondary pin. Use your standart RX TX pin to solve the problem
> 2 votes

---
Tags: arduino-uno, esp8266, wifi
---


# Question
Title: How can I use multiple 7-segment displays in Tinkercad
I need to connect five 7-segment displays using Tinkercad.

We know that Tinkercad doesn't have an Arduino Mega to use its pins.

How can I do this without the Arduino Mega?

# Answer
> 0 votes
It sounds like you will need to multiplex them.

Assuming common cathode LEDs:

Set up a transistor for each digit that activates the ground for that digit. (Lighting all the segments of a digit will probably exceed the max current sink of one of your digital pins.) You may be able to drive a single segment directly from an output pin, assuming it's current draw is ≤20 mA. If the segments draw \> 20 mA then you will likely need transistors for the segment drivers as well. (The max output of a pin on most Arduinos is actually 40 mA, and if the average current when multiplexed across 5 digits is \< 20 mA, you might get away with drawing up to 40 mA per segment. I'd ask somebody with more electronics experience than me to confirm this.)

Write your code to switch one digit's ground on at a time, after turning on the desired anode (segment) pins. Cycle through the digits rapidly and they will all appear to be on at the same time.

The pseudo-code:

```
setup {
   digit index = 0
   turn all pins (segment anodes and digit cathodes) to open state
}

loop {
   set up segments pins for digit[index]
   Turn on cathode for that digit
   short delay to allow segments of current digit to glow
   turn off cathode (ground) of current digit
   digit index = (digit index + 1) % num_digits
}

```

The above would require a digital pin for each segment, and a pin for the ground of each digit. (7 + 5 = 12 digital pins total.) Without multiplexing, you'd need 7x5 = 35 digital pins, and would still have to make sure you didn't exceed the total current output limits of the Arduino. (35 segments x 20 mA/segment would be 700 mA total.) Most Arduinos have a total current output of no more than 200 mA across all pins, so you could not light up all the segments of more than 2 digits at once, assuming 20 mA/segment.)

Note that it might be easier to ignore all of the above and get a serial LED display driver like a MAX7219. You just need 2 digital lines to drive that, and it will control 8 8-segment digits (7 segments plus a decimal point at each position)

---
Tags: 7-segment
---


title: Antenna for ESP32-pico-d4

text:
# Question
Title: Antenna for ESP32-pico-d4
I am currently playing a bit around with the esp32-pico-4d, it does not have an onboard antenna, so an external antenna is needed, tho I don't know a lot about it so a little help would be appreciated.

I found this:

https://www.espressif.com/sites/default/files/documentation/esp32-pico-d4\_datasheet\_en.pdf

here one says that he literally just connected the antenna to ground and LNA\_IN would that work?

and which antennas would you recommend? (as small as possible is only gonna be used for BLE and)

(datasheet: https://www.espressif.com/sites/default/files/documentation/esp32-pico-d4\_datasheet\_en.pdf)

# Answer
In my experience, an LNA connection typically implies that an antenna with a Low Noise Amplifier is required to meet the specifications - typically for signal strength. That's not to say it absolutely won't work without it, but rather it's *typically* used.

You'll need to select an antenna first, do some calculations and determine if you have enough signal to make your ESP32's receiver "happy". If your antenna doesn't deliver enough power, you'll have to add an LNA.

Wrt antennas, many boards are made today with the antennas etched from the copper. Some are quite good, and last I checked there were Gerber files available that could be used to replicate them on your PCB (assuming you use a board that meets the specs - dielectric constant is important). Another, maybe easier approach is to buy one of the miniature ceramic antennas - for example Johanson Technology makes them, and they're available from other mfrs through distributors - Mouser, for example. You may be able to wangle free samples - perhaps even some applications engineering support if they believe that will help them sell product!

Another source for antenna recommendations would be the Bluetooth Consortium website. They maintain a list of "prequalified" vendors \- including some who make antennas. There may be other resources that would be useful. And don't overlook the usual open source repositories for help... there may be some out there who are hacking the same chip.

Anyway - got carried away - hope this helps.
> 1 votes

# Answer
> here one says that he literally just connected the antenna to ground and LNA\_IN would that work?

Yes. LNA\_IN is the input to the Low Noise Amplifier - the input stage of the receiver / output stage of the transmitter.

> and which antennas would you recommend? (as small as possible is only gonna be used for BLE and)

You want one tuned for 2.4GHz. The simplest is a quarter wave dipole at 3.125cm in length. Better would be a proper 2.4GHz antenna of the kind you get on a WiFi router or some USB WiFi dongles.
> 0 votes

---
Tags: esp32, electronics, rf, ble
---


# Question
Title: Writing and Reading data from RTC module EEPROM_Arduino
i have took below code from https://lastminuteengineers.com/ds1307-rtc-arduino-tutorial/. i am not understand what these codes are doing. please help me to understand.

```
Wire.write((int)(eeaddress >> 8)); // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB

```

Thanks

# Answer
These two lines write a 16 bit (2 8-bit) value, which is signed -32768..32767 or unsigned 0..65535.

Assume a value in bits: 10101010 11001100

Statement 1:

```
Wire.write((int)(eeaddress >> 8)); // MSB

```

The first statement shifts the value 8 bits (positions) to the right; this is called the MSB (Most Significant Byte, the left 8 bits). Bits on the right are clipped / fall off. Thus

```
10101010 11001100

```

will become

```
00000000 10101010

```

When casted to an 8 bit value you get:

```
10101010

```

Statement 2:

```
Wire.write((int)(eeaddress & 0xFF)); // LSB

```

The second statement will get the LSB (Least Significant Byte). This used the AND operator, meaning a bit is only 1 if both values are 1. 0xFF is the 'mask'

```
Original value: 10101010 11001100
Mask:           00000000 11111111
                ----------------- AND (&) operator
Result:         00000000 11001100

```

As you can see only the right 8 bits are kept. When casting this to an 8 bit value:

```
11001100

```
> 1 votes

---
Tags: arduino-uno, rtc
---


title: Sine wave using arduino uno

text:
# Question
Title: Sine wave using arduino uno
I am an adruino hobbyist, i want to make sine wave using arduino uno, for that i using timer0 as interrupt, OCR0A set to 17 for 3.6khz interrupt(16000000/(100hz\*36 interval)/256-1), If i am using only one pwm pin i am getting correct frequency but when i enable two pwm pin i am getting only half if the frequency, kindly advise what is wrong and how to correct it. ................................. This code i am getting correct frequency at PWM pin 9.

//

```
ISR(TIMER0_COMPA_vect)
{
OCR1A=(256+((((sin(num*3.14/180))*256))))/2;
//OCR1B=(256+((((sin(num*3.14/180))*256))))/2;
     num=num+10;
    if(num >= 360)
{
       num = 0;
    }
}

```

// ............................ This code i am getting only half of the previous frequency at PWM pin 9,10

//

```
ISR(TIMER0_COMPA_vect)
{
OCR1A=(256+((((sin(num*3.14/180))*256))))/2;
OCR1B=(256+((((sin(num*3.14/180))*256))))/2;
     num=num+10;
    if(num >= 360)
{
       num = 0;
    }
}

```

//

# Answer
You are doing complex calculations inside an Interrupt Service Routine. This is not a good idea. Computing sines takes a large amount of time as this consists of multiple, complex floating point operations. Interrupt Service Routines should be short and as simple as possible.

This is probably the reason you can't have two PWM signals active at the same time at the same frequency. The ISRs simply take too long.

The solution would be to pre-calculate the desired waveforms or greatly simplify the waveform calculations (preferably without floating point). If you decide to pre-calculate, take care to stay within the limited amount of memory you have available on your Arduino. You can minimize the memory used by calculating and storing just 1/4 of a complete waveform and constructing the remaining 3/4 from these values.

This leaves the conversion of your PWM output to a real sine wave. How are you planning to do that?
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Send data before raising edge of a Clock
I'm trying to control a LED strip that has a custom protocol (developed above of I2C).

But in my tests i was successful figuring out how it works :

You set Clk to zero , you send a bit in the data line , then you set Clk to high. Based on the pixels number , i should send 16bits for each color (Red Green Blue).

I was able to generate a Clock signal at 8MHz with this code :

```
const byte Clock = 9;
const byte Data = 10;

void setup ()
{
 pinMode (Clock, OUTPUT);
 pinMode (Data, OUTPUT);
 digitalWrite(Data, HIGH);
 TCCR1A = bit (COM1A0);
 TCCR1B = bit (WGM12) | bit (CS10);
 OCR1A =  0;
 }

 void loop ()
 {
 ...
 }

```

**My questions :** How could i send data at that specific time when the clock is at zero ?

Note that using digitalWrite() function was not working due to the frequency limitation of that function.

Thanks for any helpful information.

# Answer
After a night of continuous tests i figure out how to control correctly the LED strip using the following :

1- To apply any RGB value (a pixel) you have to send a compete frame of data to all the pixels. In my strip i have 12 pixels ,so to turn for example the first pixel into red , i have to send 11 zero pixels then the red pixel.

2- The delay and timing as mentioned above by @Majenko was the key, you just set the data and pulse the clk , that easy.

3- the protocol used isn't SPI or I2C , it's a custom protocol based on a custom driver developed by a private company (not a driver for general use or market , it was dev for a big wall lighting project).

```
#define setPin(b) ( (b)<8 ? PORTD |=(1<<(b)) : PORTB |=(1<<(b-8)) )
#define clrPin(b) ( (b)<8 ? PORTD &=~(1<<(b)) : PORTB &=~(1<<(b-8)) )
#define Data 7
#define Clk 9

void setup() {
pinMode(Data,OUTPUT);
pinMode(Clk, OUTPUT);
Serial.begin(9600);
}

void loop() {
int i, j, k, q, r, lim_j, lim_i;
int red, green, blue;
for(k=0; k<12; k++)
{
r= k%3;
lim_j = 2 - r;
q = k/3;
lim_i = 3 - q;
Serial.print(lim_i); Serial.println(lim_j);
clrPin(Clk);
delayMicroseconds(5);
setPin(Clk);
delayMicroseconds(5);

for(i=0; i<4; i++)
{
  for(j=0; j<3; j++)
  {
    if(i==lim_i && j==lim_j)
      one_pixel(1200, 0, 0);
    else
      one_pixel(0, 0, 0);
  }
}
clrPin(Clk);
delay(1000);
}
}

int one_pixel(int red, int green, int blue)
{
rapid_serialize(red);
delayMicroseconds(5);
rapid_serialize(green);
delayMicroseconds(5);
rapid_serialize(blue);
delayMicroseconds(5);
clrPin(Clk);
}

inline void rapid_serialize (uint16_t color) //just a copy for now , not a pointer
{
uint16_t bit_shift = 32768;
while (bit_shift)
{
 clrPin(Clk);
 bit_shift = bit_shift>>1;
  if ((bit_shift & color) == 0)
      clrPin(Data);
  else
      setPin(Data);
 delayMicroseconds(5);
 setPin(Clk);
 delayMicroseconds(5);
  }
 }

```
> 0 votes

# Answer
It sounds like you have some misconceptions.

In order to work with clocked signals like in SPI, you set your data line(s) to the desired value, and then raise the clock signal from low to high. The receiving device detects the low to high transition and reads the state of the data lines.

If you did it in the other order (switch the clock signal from low to high, then set the data pin(s).) then the receiver would detect the clock rising edge and try to read the data value before it was set correctly.

With a clock line like in your setup, the communication doesn't rely on fixed timing. The clock line tells the receiver when the data is available, and you can use whatever clock timing you want (up to the max speed supported by the hardware.)
> 0 votes

---
Tags: arduino-uno, timers, data
---


# Question
Title: Come out of loop and execute Setup again
I want to end loop at a specific time and start setup again. Is this possible? (I can explain reason in case you require).

# Answer
You could just call `setup()` yourself:

```
void loop() {
    if (some_condition) {
        setup();  // reinitialize everything
        return;
    }
    // etc.
}

```

But, as Majenko puts it, if you nee to do that it looks like there is something wrong with your methodology.

That being said, it would be less suspicious if you only need to reinitialize some specific part of your program. In this case you can make a separate function for these initializations, and call it both from `setup()` and, when needed, from `loop()`:

```
void init_foo() {
    // ...
}

void setup() {
    init_foo();
    // other initializations...
}

void loop() {
    if (some_condition) {
        init_foo();  // reinitialize foo
        return;
    }
    // etc.
}

```
> 6 votes

# Answer
Not directly, no. You can reboot the Arduino though so everything starts from scratch (either through the watchdog timer or wiring a GPIO pin to RESET and pulling it LOW), but if you find you need to do this sort of thing then you should rethink your methodology so that you don't need to do this sort of thing.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Problem on color mixing lamp on Proteus Arduino starter kit
I set the circuit and couldn't illuminate, where is the problem?

Fritzing: https://fritzing.org/media/fritzing-repo/projects/c/color-mixing-lamp/images/Arduino%20Lamp%20Project.png

# Answer
just fixed by using TORCH LDR instead of normal LDR. FULLY WORKS.
> 1 votes

---
Tags: pcb-design
---


# Question
Title: Is it possible to preform VIO from two cameras/IMUs on a dual-core ESP32?
Like the title says, I want to take in the synchronised data from two NXP breakout boards and two Ueye 1220LE cameras, and use VIO to fuse their data and get positions for both setups.

A lot of people have suggested running things like SLAM, which is similar to VIO, on something stronger than an Arduino, some specifically suggested using a version of a Raspberry Pi.

Now, I know that Raspberry Pis are stronger than an ESP32, but ESP32s are stronger than Arduinos, and since Pis are more expensive than an ESP32s and I need WiFi capabilities, before I buy a Pi, I was wondering if it would be possible to perform this on my dual-core ESP32.

And if the Pi isn't overkill and I needed all the processing power I could get, what version should I use? The Zero? The 3.0? The 4.0? Do let me know.

# Answer
I haven't worked with the ESP-32, but it seems to me you're quibbling over pennies. Pis are cheap and very powerful. They run Linux, so there are tons of open source libraries available for them. You could install OpenCV, for example, and do computer vision quite readily.

I'd recommend at least a PI 3.

If you used an ESP-32 based system, would you run it as an Android device? The Arduino "OS" (And that the term OS is quite a stretch) is really just a setup function and a run loop. You should use a device with a real OS, including a file system, etc.
> -1 votes

---
Tags: esp8266, wifi, raspberrypi, imu, camera
---


title: Standalone 328P Arduino

text:
# Question
Title: Standalone 328P Arduino
I am creating a standalone Arduino using Atmega328P. The circuit is below.

However, I'm seeing

```
avrdude: Device signature = 0x000000 error

```

whenever I try to burn the Arduino Uno bootloader. I'm assuming that the chip isn't responding to the SPI lines?

I know I'm doing something wrong but I can't see it.

My connections are

```
SCLK --> Arduino Pin 13
MISO --> Arduino Pin 12
MOSI --> Arduino Pin 11
Reset --> Arduino Pin 10

VIN --> 5V
GND --> GND

```

I'm using a true Arduino UNO as the ISP. I've uploaded the ArduinoISP code into it, choose Arduino as ISP as Programmer and Arduino Uno on boards. The programming connections are just wired from Arduino UNO pins to some vias I've purposely added on the layout.

As mentioned in the comments, I'm adding an image of the layout here.

I've tried this very circuit on an atmega328P soldered in a TQFP adapter and with the other components soldered on the adapter as well (looks like a jungle of wires) and somehow I was able to burn the bootloader.

Hoping someone can point out what's wrong.

# Answer
It seems that you are using a lm317 voltage regulator to power your atmega328p MCU but I think you forgot the part that lm317 needs feedback of 1.25v with voltage divider network to set its variable output voltage in the schematic you have connected adj pin of lm317 directly to GND. S0 check your output vtg from your regulator and another issue voltage regulator only works great when difference between regulating voltage is lower then the supply voltage.
> 2 votes

# Answer
From the schematic it appears you are using a LM317 voltage regulator from USB V\_IN. The voltage drop is too large and your issues may be due to brown out, i.e. insufficient voltage: See this SE post. You can solve it by using a lower dropout regulator (5 V to 3.3 V) or just use the standard USB 5 V, bypass V\_IN to V\_CC.
> 0 votes

---
Tags: atmega328, bootloader
---


# Question
Title: Boolean Logic With Chars For Motor Input Selection
Context of the code:

I am trying to control 2 DC motors through an H-gate, this means there are 4 inputs in total: For DC motor 1: Input 1 (VCC) and Input 2 (GND). For DC motor 2: Input 3(VCC) and Input 2 (GND).

Summary of the code:

The global variables are motinpN which are the pins connected to the different inputs.

An array, which is where the different PWM for the motor speeds are stored.

Char x, which is the variable used for the boolean logic.

Then comes the actual loop which consists of 4 similar functions, the "input selector" function and then the statements that turn the integers stored in the inpSpeedS\[\] arrays into motor speeds.

The issue:

The code won't enter the first loop, i.e it won't advance past

Serial.println("X equals:"); Serial.print(x);"

I would like to know then, what I am doing wrong in order for this not to work?

```
   int Speed = 0;
const int motinp1 = 2;
const int motinp2 = 3;
const int motinp3 = 4;
const int motinp4 = 5;

char  x = '0';

int inpSpeedS[4]; // An array to determine the speed of each individual input

void setup()
{
  Serial.begin(9600);
  pinMode(motinp1, OUTPUT);
}

void loop() {
  Serial.println("X equals:");
  Serial.print(x);

  if (Serial.available () && (x == '0')) {
    Serial.print("Which input?");
    x = Serial.read();
    Serial.println(x);
  }
  if (Serial.available () && (x == 'a'))
  {
    Serial.println("Input 1 selected");
    inpSpeedS[0] = Serial.parseInt();
    Serial.print("Input 1: ");
    Serial.println(inpSpeedS[0]);
   x = '0'; //reset x, goes back to input selection
  } if (Serial.available () && (x == 'b'))
  {
    Serial.println("Input 2 selected");
    inpSpeedS[1] = Serial.parseInt();
    Serial.print("Input 2: ");
    Serial.println(inpSpeedS[1]);
   x = '0';
  }
  if (Serial.available () && (x == 'c'))
  {
    Serial.println("Input 3 selected");
    inpSpeedS[2] = Serial.parseInt();
    Serial.println("Input 3: ");
    Serial.print(inpSpeedS[2]);
   x = '0';
  }
  if (Serial.available () && (x == 'd'))
  {
    Serial.println("Input 4 selected");
    inpSpeedS[3] = Serial.parseInt();
    Serial.print("Input 4: ");
    Serial.println(inpSpeedS[3]);
   x = '0';
  }
  analogWrite(motinp1, inpSpeedS[0]);
  analogWrite(motinp2, inpSpeedS[1]);
  analogWrite(motinp3, inpSpeedS[2]);
  analogWrite(motinp4, inpSpeedS[3]);
}

```

EDIT - I have turned the char 0 from a string literal null to an ASCII code for 0, and same for the other chars. It is still stuck outside of the function loops.

# Answer
> 1 votes
It's screaming on you:

```
sketch_jun13a.ino:7:11: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

 char  x = "0";

           ^~~

sketch_jun13a.ino: In function 'void loop()':

sketch_jun13a.ino:21:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "0")) {

                                    ^~~

sketch_jun13a.ino:21:36: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]

sketch_jun13a.ino:26:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "a"))

                                    ^~~

sketch_jun13a.ino:33:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0"; //reset x, goes back to input selection

         ^~~

sketch_jun13a.ino:34:38: warning: comparison with string literal results in unspecified behavior [-Waddress]

   } if (Serial.available () && (x == "b"))

                                      ^~~

sketch_jun13a.ino:41:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

sketch_jun13a.ino:43:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "c"))

                                    ^~~

sketch_jun13a.ino:50:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

sketch_jun13a.ino:52:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "d"))

                                    ^~~

sketch_jun13a.ino:52:36: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]

sketch_jun13a.ino:58:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

```

Basically this is char variable with assigned character literal: `char x = '0';`

And this is C string: `char str[] = "0";` or its equivalent: `char str[] = {'0', '\0'};`. Where `'\0'` is so called `NUL` Terminal character.

Everything about C strings you need to know

EDIT:

Simple demo for the "parser" - it's not perfect but should be enough:

```
char  x = '0';

int inpSpeedS[4]; // An array to determine the speed of each individual input

void setup() {
  Serial.begin(9600);
  Serial.println("Select channel [a..d] and speed [0..255]: ");
}

void loop() {

  if (Serial.available() > 1) { // wait for more characters in buffer
    switch (Serial.read()) {
      case 'a': inpSpeedS[0] = Serial.parseInt(); break;
      case 'b': inpSpeedS[1] = Serial.parseInt(); break;
      case 'c': inpSpeedS[2] = Serial.parseInt(); break;
      case 'd': inpSpeedS[3] = Serial.parseInt(); break;
      default : return; // skip invalid characters like line endings
    }

    Serial.print("Speeds: ");
    for (auto spd : inpSpeedS) {
      Serial.print(' ');
      Serial.print(spd);
    }
    Serial.println();
    Serial.println("Select channel [a..d] and speed [0..255]: ");

    /*
      analogWrite(motinp1, inpSpeedS[0]);
      analogWrite(motinp2, inpSpeedS[1]);
      analogWrite(motinp3, inpSpeedS[2]);
      analogWrite(motinp4, inpSpeedS[3]);
    */

  }
}

```

And the result:

```
-> Select channel [a..d] and speed [0..255]:
<- a547
-> Speeds:  547 0 0 0
-> Select channel [a..d] and speed [0..255]:

```

---
Tags: programming, motor, software
---


title: Relative position using Accelerometer

text:
# Question
Title: Relative position using Accelerometer
I have a simple scenario please:

Two Arduino Nano 33 IoT devices started moving randomly from the same exact origin(Point = \[X0, Y0, Z0\]);

Can I use the coordinates queried from each device Accelerometer to get the Euclidean Distance between them?

In other words, Is the relative coordinate/position retrieved from the Accelerometer reliable?

Because I read that getting the relative position every time requires double integrations which leads to big accumulated error over time. Though I might be totally wrong.

Your help is very much appreciated.

# Answer
What you heard (about double integration and accumulating errors) is correct. Mathematically, you can do this, by integrating each device's acceleration to get its current speed, and integrating the speed to get it's current position, then taking the vector difference in the their positions to get the distance between them.

*If* you had highly accurate accelerometers in a very noise-free environment (both mechanical and electrical noise), you could do it for a (short) while before the inevitable tiny errors (which are also being integrated!) begin to dominate the data and make the results useless. But as a practical matter - especially for us experimenters using inexpensive equipment and subject to a lot of mechanical and electrical noises on the experimental platform, plus environmental electrical noise - this will happen even more quickly.
> 1 votes

---
Tags: arduino-nano, accelerometer, imu
---


title: Using interrrupts with RC522

text:
# Question
Title: Using interrrupts with RC522
I have a project using the RC522 RFID module with my Arduino Uno board and miguelbalboa's rfid library. The example code and every other code I find on the internet work pooling the device in order to know if there is a new card present, but I intend to work with a interrupt-driven approach. I have the proper knowledge to do the hardware/arduino part, but I'm having trouble generating an interrupt in the IRQ pin when the card is present. Have anyone succeded on this?

Edit: Connection: RST -\> 8

SS-\> 9

MOSI -\> 11

MISO -\> 12

SCK -\> 13

IRQ -\> 2

Code:

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

#define RST_PIN     8
#define SS_PIN      9

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_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
  mfrc522.PCD_WriteRegister(MFRC522::ComIEnReg, 0x7F); //Enable all interrupts
  mfrc522.PCD_WriteRegister(MFRC522::DivIEnReg, 0x14);
  Serial.println(F("Ready..."));
  attachInterrupt(0, isr, RISING);
}

void loop()
{
}

void isr()
{
  Serial.println(F("Interrupt"));
  mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
}

```

Result: I only get the "Ready..." on the Serial Monitor, no matter if there is a card present or not.

# Answer
From your code:

```
void isr()
{
  Serial.println(F("Interrupt"));
  mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
}

```

Do not do serial prints inside an ISR! They will eventually hang it. What you need to do is have a volatile variable (eg. a bool), set that in the ISR, and then check that in `loop`. If it changes, display it. Eg.

```
volatile bool cardPresent;

void loop()
{
  if (cardPresent)
    {
    Serial.println(F("Interrupt"));
    mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
    cardPresent = false;
    }

}

void isr()
{
  cardPresent = true;
}

```

---

The other thing I would do is put a scope or logic analyzer on the IRQ pin and see if it is actually changing. It *should* trigger the interrupt if it does.
> 4 votes

# Answer
I'm quite late to this party, but I was looking for a way to have the MFRC522 generate an interrupt when it detects a compatible RFID card/key fob/sticker/etc., and this is one of the hits I got from my search. I write this now for the pilgrim who follows the same breadcrumbs I have in the hopes that it will save them at least a little time.

I tried something similar to what was suggested, found that I got interrupts quite often and continuously, and looked into the situation a bit more.

The MFRC522 does not generate interrupts for card detection. The microcontroller (or microprocessor) must command it to transmit and then query it to see if there was any response. This means that the MCU cannot go into a sleep mode and get awaken by the MFRC522 when there's a card to read. The MFRC522 does have a timer that can generate an interrupt, but the maximum period of this timer is not huge, and the timer does not control the transceiver, it's there for the convenience of the application on the MCU.

Writing 0x7F to the "ComIEnReg" means the following:

* Bit 7: IRqInv=0 - Interrupts are active high
* Bit 6: TxIEn=1 - Transmitter interrupt is enabled
* Bit 5: RxIEn=1 - Receive interrupt is enabled
* Bit 4: IdleIEn=1 - Idle interrupt is enabled
* Bit 3: HiAlertIEn=1 - "High Alert" interrupt is enabled
* Bit 2: LoAlertIEn=1 - "Low Alert" interrupt is enabled
* Bit 1: ErrIEn=1 - Error interrupt is enabled
* Bit 0: TimerIEn=1 - Timer interrupt is enabled

The bits in the register "ComIrqReg" have the following meaning:

* Bit 7: Set1 - when written as 1, a bit value of 1 in bits 6-0 of the byte written set the corresponding register bit; when written as 0, bits 6-0 clear the corresponding register bit
* Bit 6: TxIRq - Set when the last bit of Tx data has been sent
* Bit 5: RxIRq - Set when the receiver detects the end of a valid data stream
* Bit 4: IdleIRq - Set when the CommandReg changes the command field to the idle command
* Bit 3: HiAlertIRq - Set when the Status1 register HiAlert bit is set
* Bit 2: LoAlertIRq - Set when the Status1 register LoAlert bit is set
* Bit 1: ErrIRq - Set when any bit in ErrorReg gets set
* Bit 0: TimerIRq - Set when the TCounterValReg decrements to zero

Writing 0x14 to the "DivIEnReg" has the following meaning:

* Bit 7: IRQPushPull=0 - IRQ is an open-drain output pin
* Bit 6: reserved=0 - no known effect
* Bit 5: reserved=0 - effect unknown
* Bit 4: MfinActEn=1 - Allow the MFIN active interrupt request to trigger IRQ
* Bit 3: reserved=0 - boundedly undefined
* Bit 2: CRCIEn=1 - Permit the "DivIrqReg" bit CRCIRq to trigger IRQ
* Bit 1: reserved=0 - do not set to 1 on pain of nothing
* Bit 0: reserved=0 - has no purpose other than to confuse

The register "DivIrqReg" corresponds to "DivIrqEn", and has the following bit definitions:

* Bit 7: Set2 - when written as 1, a bit value of 1 in bits 6-0 of the byte written set the corresponding register bit; when written as 0, bits 6-0 clear the corresponding register bit
* Bit 6: reserved - don't ask
* Bit 5: reserved - don't tell
* Bit 4: MfinActIRq - MFIN is active
* Bit 3: reserved - just leave it at zero and back away slowly
* Bit 2: CRCIRq - when 1, the CalcCRC command is active and all data is processed
* Bit 1: reserved - nothing to see here
* Bit 0: reserved - are you feeling lucky, punk?

*The above register bit definitions were cribbed from the MFRC522 datasheet from NXP, titled "MFRC522 Standard performance MIFARE and NTAG frontend", Rev 3.9, 27-April-2016.*

The library for the MFRC522 does have an interrupt example that uses a lighter weight means of polling the transceiver. see https://github.com/miguelbalboa/rfid/tree/master/examples/MinimalInterrupt, but it does not provide a means of waking your host from a low-power sleep mode when someone waves their magic ring over the hidden panel by the secret door, meaning that your secret lair will need to be wired to power the reader even if it is otherwise wireless; either that, or your henchmen will be forever changing batteries.
> 4 votes

# Answer
first of all, I apologize for the English, I can understand it but i use google translator to express myself in.

I don't use arduino, It's a interesting platform (for the ide, which is apparently object oriented programming POO), but extremely limited by the hardware

Well, entering the subject, I am also developing an implementation for the MRFC522, and the datasheet does not give examples of how do it, but indicates how enable interrupts (although I have not tried ,yet)

but if I'm not wrong, the following registers are involved:

ComIEnReg--\> Control register bits to enable and disable the passing of interrupt requests.

DivIEnReg--\> control bits to enable and disable the passing of interrupt requests.

ComIrqReg--\> register Interrupt request bits. (I think it's read only)

DivIrqReg--\> register bit descriptions (I think it's read only)

I think it's just properly setting the first two should be able to generate the interrupt on the pin irq. i don't know if the following is correct.

set ComIEnReg to --\> (in binary) 0b01111111 //enables all al interrupts

set DivIEnReg to --\> 0b10000100 //I don't understand complete about MFIN (bit4) and set it to 0 but i set CRCIEn to 1 (bit 2) and bit7 to 1 "pin IRQ is a standard CMOS output pin"

// the different posible configuration to DivIEnReg

* yours--\> 0b00010100 --\>0x14
* try 1 --\> 0b00000100 --\>0x04
* try 2 --\> 0b10010100 --\>0X94
* try 3 --\> 0b10000100 --\>0X84

if you manage to the module to do the interruption, it would be kind enough to comment on how you did
> 0 votes

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


# Question
Title: Feeding microcontroller and linear actuators (motors) with the same power supply
I have already made a diagram using a motor controller. I want to use only one power supply to feed arduino and motors. I want to use MDD10 dual motor driver.

The details of the actuators each one is:

Input voltage: 12VDC, Max Load: 750N(168.607lbs), Stroke Length: 16 inch, Travel Speed: 12mm/s, Duty Cyle: 25%, Current: 5A.

The power supply is 12V, 10A.

Could you please check if it is ok, or which would be the best solution?

Some of my concerns are:

Be sure if the feed of 12 volts for the motors, and 5 volts for Arduino are correct and can live together as shown.

Be sure if the wiring for the Arduino, driver and motors is correct since it looks kind of simple.  I want to know if this is the natural approach by doing it with a voltage regulator to feed the Arduino and with 12V 10A power supply to feed the motors, or if there are other, better options to make the circuit feed only using one power supply (12V, 10A).

MDD10 Datasheet Link: https://www.robotshop.com/media/files/content/c/cyt/pdf/cytron-10a-7-30v-dual-channel-dc-motor-driver-shield-datasheet.pdf

Thanks in advance

**UPDATE**

I have increased power supply to 13A, also changed the linear voltage regulator (7805) to a switching voltage regulator (OKI-78SR-5), what do you think about this approach?  Or I should try with the 12V DC Vin of Arduino(I understand that it works with a linear voltage regulator)? Being this option, it could be maybe with a voltage pre-regulation stage(for example from 12V to 9V) or maybe connecting directly to the jack.  Thanks, Best Regards.

# Answer
> 1 votes
First of all I would look to see if the two motors will actually run at the same time. If not then the 10A power supply, is fine. If they do run together, for how long? (you mention 25% duty cycle), power supplies usually have a over capability for a short period of time, and batteries will supply more current but at a slightly reduced voltage, so if going slightly slower isn't an issue then this would be fine. Then there is the question of do they really use all 5Amps, I very much suspect not, unless you are fully loading the actuator(750N), they prob run at 2-3 amps at most. Secondly Circuit protection, fuses or thermal shutdown links for the motors is required, better still instant overcurrent protection for them set at 1.2x nominal current. Do some worst case tests and measure the current, set the protection to 1.2 x this. Remember if there is an issue the supply voltage will start to drop, its now that the micro will suffer if the voltage dips too much and you have no protection/sensing.

So suspect the power supply is more than ok.

# Answer
> 0 votes
Your approach looks reasonable, but you don't have enough power. The motors will draw 10A, which is the full output of your power supply/battery. That doesn't leave any left over for your Arduino system.

You should have a high enough capacity power supply/battery for your total peak power requirement plus a little margin (say 10%-20%) The Arduino and all the other electronics on it might draw another 1/2 amp, so 10.5 total. Add 20% margin to that and you get 10.5 * 1.2, or about 12.6 A.

(When you drive a power supply up to its upper limit its output voltage can start to sag. By having a buffer it doesn't have to work as hard.)

One advantage you have in your circuit is that you're feeding unregulated 12V to your motors, and then feeding 12 into your Arduino's voltage regulator. That way even if the 12V supply droops to 10V under maximum load, the voltage regulator will still be able to maintain a clean 5V supply to your MCU.

Also note that you could feed 12V into the Arduino's V in and use its built-in voltage regulator. As long as don't draw a lot of current out of its 5V line the built-in regulator could manage the 5V voltage regulation itself. If you need ≥500 mA, though, you might want to use an external buck converter (or a high capacity linear regulator with a good heat sink.)

---
Tags: power, motor, voltage-level, current
---


# Question
Title: Mac OS X Catalina Serial Monitor Problem
I have some problems on MacBook Pro running with Catalina. I bought new nodemcu LoLin board. Its clone. It has ch340 adapter to communicate. And writing on bottom side wemos.cc and use ch340g driver.

I succesfully installed drivers and I can see my lolin boards on port list

I upload a code that doing only print hello to serial port. I tried with 9600 and 115200 baud rates. My serial monitor show garbage data. I am using platform io with VSCode to upload code and upload time is too much.When I am uploading code I got this warning :

"Detected crystal freq 156.04MHz is quite different to normalized freq 40MHz. Unsupported crystal in use?"

I am using cheap thundeIrbolt usb converter too. But I connect with this converter to Windows pc, everything looks fine. I can see hello world on serial monitor. But on my Mac, I can see garbage only. I tried some serial monitors, Arduino IDE and platform io ide but still same.

Are there any solution about this problem?

EDIT :

I fixed issue last night. Catalina has ch340 drivers already and I setup oem driver from GitHub. Apples driver and oem drivers conflicting. If you use Mojave and higher os, you dont need any driver for ch340. So if you installed ch340 oem driver you should delete it.

I am adding the post: Platformio post

# Answer
> 1 votes
I fixed issue last night. Catalina has ch340 drivers already and I setup oem driver from GitHub. Apples driver and oem drivers conflicting. If you use Mojave and higher os, you dont need any driver for ch340. So if you installed ch340 oem driver you should delete it. I am adding the post: Platformio post

---
Tags: esp8266, mac-os
---


# Question
Title: Error passing a `time_t` and `struct tm`, ESP32
I need to create a converter from epoch time stored in a `time_t` variable, to a `struct tm` variable, in order to check / create a certain task every hour or a day. This function should get also a past `time_t` for other uses.

Converting function, inside a library, works OK ( last two lines are for verification purposes, meaning conversion was done as expected ):

```
void myIOT32::convEpoch(time_t in_time, struct tm *convTime)
{
  convTime = gmtime(&in_time);
  char time_char[40];
  sprintf(time_char, "%04d-%02d-%02d %02d:%02d:%02d", convTime->tm_year + 1900, convTime->tm_mon+1, convTime->tm_mday,
            convTime->tm_hour, convTime->tm_min, convTime->tm_sec);

  Serial.print(" from funct: ");
  Serial.println(time_char);

```

Now, when calling it from my code and try to use time `tm` var, it causes the code to crash. In code below, I just try to print it to console:

```
void sendnewNotif()
{
  struct tm *newtime;
  time_t t=182423032;
  iot.convEpoch(t, newtime); // <--- Using the conversion
  char timeStamp[50];
  // Serial.print(newtime->tm_year);

}

```

What may be the problem ?

Guy

# Answer
```
void myIOT32::convEpoch(time_t in_time, struct tm *convTime)
{
  convTime = gmtime(&in_time);

```

Here you are overwriting the parameter `convTime`. There is no point in passing such a parameter if you are not going to use the value provided.

```
void sendnewNotif()
{
  struct tm *newtime;
  time_t t=182423032;
  iot.convEpoch(t, newtime); // <--- Using the conversion

```

`newtime` is initially uninitialized. The call to `iot.convEpoch()` doesn't change that (the parameter is passed by value, not by reference).

```
  Serial.print(newtime->tm_year);

```

This is dereferencing an uninitialized pointer, which is undefined behavior and can crash the program.

The simplest solution I see is to have `myIOT32::convEpoch()` return the pointer it got from `gmtime()`. Note that this points to static storage, which makes the method not reentrant.

Example (not tested):

```
struct tm *myIOT32::convEpoch(time_t in_time)
{
  struct tm *convTime = gmtime(&in_time);
  // ...
  return convTime;
}

void sendnewNotif()
{
  time_t t = 182423032;
  struct tm *newtime = iot.convEpoch(t);
  Serial.print(newtime->tm_year);
}

```
> 1 votes

---
Tags: esp32, time
---


# Question
Title: Need help with EEPROM not storing array values on ESP8266 after restart
I am struggling through a program. I am trying to store my uploaded string into an array then write that array to EEPROM. I run the program, upload the new array and store it in the EEPROM. all values display correctly until I reset or power off the device. I am sure I am overwriting or something obvious, but i am breaking down and asking for help.

The read and write EEPROM subroutines are at the bottom of the code. I call the EEPROM\_Write() in server.on after parsing the http get.

*EDIT: per feedback, removed all but the function, with the EEPROM.commit(); suggestion included... still not working*

```
void EEPROM_Write(){
Serial.begin(115200);
EEPROM.begin(280);
  // store values in EEPROM
  for (int i = 0; i < pwmarray1Size; i++)
  {
    Serial.println(pwmarray1[i]);
    EEPROM.put( EEPROMStartAdress + (i * sizeof pwmarray1[0]), pwmarray1[i]);
  }
  Serial.println();
  EEPROM.commit();
 // EEPROM.end();
}

```

# Answer
> 1 votes
The ESP has no real EEPROM. Instead the `EEPROM` class for ESPs uses the flash memory. There is a difference in the implementations of this class between Arduinos and ESPs:

On an ESP every data, that you write, will first be placed in a buffer in RAM. You need to call `EEPROM.commit()` to actually write that data to the underlying flash memory.

So you need to add

```
EEPROM.commit();

```

to the end of your `EEPROM_Write()` function, or the data will stay in RAM and thus be lost on power cycle or reset.

---

I think your problem (besides the commit) lies not in your `EEPROM_Write()` function, but in the `EEPROM_Read()` function. If it doesn't work correctly, you are just not able to see, if the data gets written correctly. In your code (which can be seen in the edit history), you have this function:

```
void EEPROM_Read(){
   //load array pwmarray1 with stored values in EPROM
  for (int x = 0; x < pwmarray1Size; x++){
    EEPROM.get(EEPROMStartAdress + (x * sizeof pwmarray1[0]), pwmarray1[x]);
        Serial.print("loading program from EPROM: ");
    Serial.println(pwmarray1[x]);
    }
}

```

While in `EEPROM_Write()` you are calling `EEPROM.begin(280)` every time, you don't `EEPROM.end()` it there and you are also not begin the EEPROM in the `EEPROM_Read()` function. I'm not sure about the underlying implementation, but it started to work for me, when I began and ended the `EEPROM` object in both functions.

I've written a test code, that I composed party of your code and that for me correctly saves and reads an array via the `EEPROM` object into the flash memory. It keeps the data over resets and power cycles just correctly. You can control it via Serial Monitor. Just type `c` (for clearing the array to zero), `r` (for reading the array from EEPROM/flash) or `i` (for incrementing all array elements and save them to EEPROM/flash).

```
#include <EEPROM.h>

#define EEPROM_SIZE 280

int array[60] = {0};
const unsigned arraySize = sizeof array / sizeof array[0];

#define EEPROMStartAdress 0

void setup(){
  Serial.begin(115200);
  Serial.println("///////////////////////////////////////");
  delay(2000);
}

void loop(){
  if(Serial.available()){
    char c = Serial.read();
    switch(c){
      case 'c':
        for(uint8_t i=0;i<arraySize;i++) array[i] = 0;
        EEPROM_Write();
        Serial.println("EEPROM RESET");
        break;
      case 'r':
        EEPROM_Read();
        break;
      case 'i':
        for(uint8_t i=0;i<arraySize;i++) array[i] += 1;
        EEPROM_Write();
        break;
    }
  }
}

void EEPROM_Write(){
  EEPROM.begin(EEPROM_SIZE);
  // store values in EEPROM
  for (int i = 0; i < arraySize; i++)
  {
    EEPROM.put( EEPROMStartAdress + (i * sizeof array[0]), array[i]);
  }
  EEPROM.commit();
  EEPROM.end();
}

void EEPROM_Read(){
  EEPROM.begin(EEPROM_SIZE);
  for (int x = 0; x < arraySize; x++){
    EEPROM.get(EEPROMStartAdress + (x * sizeof array[0]), array[x]);
    Serial.print(" ");
    Serial.print(array[x]);
    }
  Serial.println();
  EEPROM.end();
}

```

Removing `begin()` and `end()` from `EEPROM_Read()` and also `end()` from `EEPROM_Write()` gives me the same results, that you described as your problem.

---
Tags: esp8266, array, eeprom
---


title: SIM800L and DTH22

text:
# Question
Title: SIM800L and DTH22
I am very new to arduino. I am build a model that will require SIM800L and DTH22. I want to know if I can power both from my arduino. DTH22 has a wide range of input voltage but I doubt of SIM800L. It says 3.4V-4.4V but one arduino forum said that it requires 2Amps of current. But many people simply connect it to arduino 3.3V. Can anyone with experience tell me about this? (I am asking as I fried the microcontroller in my previous project.) Should I get externel power supply or go forward with arduino?

# Answer
**Do not connect any GSM module to an Arduino board 3.3v**

This SimCom GSM modules like sim800L or sim800C can take burst current of 2Amp in low network area to provide proper network and another thing is that below 3.4v and above 4.4v it will shut down automatically and you will get an Undervoltage & overvoltage warning AT response on UART before shutdown.

Another thing is that the 3.3v voltage regulator on the Arduino board can only handle up to 1Amp max and above 500ma consumption its temperature will rise and near 1A even more.

So the conclusion don't provide supply to sim800l from Arduino.
> 2 votes

---
Tags: arduino-uno
---


title: Atmega32A fuses

text:
# Question
Title: Atmega32A fuses
I have Atmega32A and 16 MHz quartz, with 22pF capacitors. Tell me, please, how to set the fuses correctly so that the MK works from external quartz.

Will MK work when setting 0xFF LOW and 0xD8 HIGH? These are the fuses of the Arduino Leonardo

As a result, I want to get a working microcontroller with work from external quartz and that I could rewrite the program.

I use eXtreme Burner - AVR and usbasp

# Answer
> 0 votes
This Atmel fuse confuses me a lot so I have figure out an easy way of finding fuses for such controllers basically two methods that I have used once are:

**Method 1:(explaining specific for this controller ( ATmega1284, ATmega644, ATmega324, ATmega164, ATmega32, ATmega16, ATmega8535 ))**

Add this to your Arduino board manager it is from MCU dude they have different varients also for other controllers check here.

Now select your controller and your clock frequency and all parameters as you like after that use USBASP or Arduino as isp for burning bootloader inside your controller, in this case, we will burn the bootloader into Atmega32A.

After the successful burning bootloader, you will need an AVRdudess software by using this software you have to just read the fuse of our MCU so we will get the fuse setting done by MCUdude from Arduino and after that, you can directly set those fuse setting and it will work fine.

**Method2:**

just use online calculators such as here for finding fuse settings.

---
Tags: fuses, atmega
---


title: Arduino Micro 5V Vin and 3v3 pins

text:
# Question
Title: Arduino Micro 5V Vin and 3v3 pins
I am very confused with the pins on the arduino micro. What are the 3v3, 5v, and Vin pins used for? Are they for power input, or power output, or both?

# Answer
> 6 votes
Vin is a power INPUT. It is connected to the input of the voltage regulator, which enables you to power the Arduino with voltages between 6V and 12V, while the Arduino itself is running on 5V.

The 5V pin can be both an power INPUT and OUTPUT. It is connected to the general 5V power rail inside the Arduino and thus to the power inputs of the microcontroller. This rail/pin needs to be provided with 5V power to let the Arduino work. Where this power comes from (from the voltage regulator, from USB or from your own external 5V power supply connected to the 5V pin) is irrelevant for the Arduino. The 5V pin can even be used to provide power to other components in your circuit (though with certain limitations, see below).

The 3V3 (meaning 3.3V) pin is a power OUTPUT. It is connected to the output of another voltage regulator, which brings the 5V from the 5V rail down to 3.3V. It can be used to power external parts, that need 3.3V to work.

---

Up to this point I only wrote about voltage. But depending on your circuit you also need to consider the current. The different electrical parts on the Arduino can only handle a specific power (measured in Watts). Thus with a given voltage you can only draw up to a specific amount of current through them, before you destroy them.

As an example, let's assume you provide the Arduino with 9V through Vin and you want to drive a middle sized motor. Motors in general can draw a lot of current. When you now drive the motor from the 5V pin of the Arduino, the motors current will flow through the Arduinos voltage regulator. Thus the regulator will go into emergency shutdown and cut the power (applies for a genuine Arduino) or it will get destroyed (applies for most cheap Arduino clones). To prevent that, you need to connect the motor directly with the power supply (or through an extra voltage regulator, suitable for the needed current), so that the current for it is no longer flowing through the Arduino.

This explanation is only to prevent you from destroying your board. That is always very annoying, when it happens.

# Answer
> 1 votes
VIN is power input. IN means INput.

Generally 5V and 3.3V are used for power output, but the 5V one can also be used for power input if you want to power the board from 5V.

But since they are just power they have no "direction" as such, only a voltage level.

---
Tags: arduino-micro
---


# Question
Title: How to supply more than 500mA while powered by USB
I'm about to build myself a new BrewPi and I have some Arduino power/USB questions.

Something smiliar to a combination of these projects:

https://i.stack.imgur.com/gZHZt.jpg

https://www.homebrewtalk.com/threads/how-to-brewpi-lcd-add-on.510036/

The device will have a Raspberry Pi Zero W, an Arduino UNO (clone?), a LCD screen with backlight, and some relays and probes. The Pi must be connected to the Arduino via USB. The Arduino will drive the screen and some relays/probes. For simplicity's sake, I would like to power everything from the same regulated 5V power supply, and for ease of wiring I would prefer to power the Pi only and have it power the Arduino via USB, with the Arduino then supplying power to the rest.

My preference: 5V ----\> Pi Zero --(USB)--\> Arduino --(5V)--\> Screen/etc.

However, according to this datasheet the max draw of the screen might exceed 1000mA: https://www.vishay.com/docs/37314/lcd020n004l.pdf

This obviously exceeds the 500mA limit from the Arduino's 5V pin while being powered via USB. However, a Pi Zero has few safety features and does not limit outgoing current from it's USB port: https://www.reddit.com/r/raspberry\_pi/comments/3zyhuq/pi\_zero\_usb\_power\_outputmilliamps/

Given this, is it feasible to short/bypass the Arduino's polyfuse and then draw more than 500ma from the 5V pin of the Arduino without too many problems?

If not, can I 'add' the power supply's 5V to the Arduino's 5V (either from the Pi's 5V pin, or direct from the power supply) at the same time as maintaining the USB connection (which uses the same 5V source)? I'm stretching the limit of my circuit understanding here. If not how should I power the other components?

Would it instead be better to have a 12V supply and power the Arduino directly, then attempt to power everything else from its 5V pin (remembering that there is still a USB connection from the Pi back to the Arduino). What I'd really like to avoid in this situation is having to provide a second 12V-\>5V conversion.

Any help or advice would be greatly appreciated.

# Answer
> 1 votes
Do not bypass the fuse. Drive your external components directly from the external 5V power supply. Do not pass everything through the Arduino.

You say you have a regulated 5V power supply. Assuming it provides enough current you should use it to drive your external components directly.

You might need to add a filter capacitor near the feed for the Pi/Arduino, to filter out fluctuations in the 5V supply as your high current components switch on and off. You should be able to google "Power supply filter capacitor" to learn more.

---
Tags: arduino-uno, power, usb, raspberrypi
---


# Question
Title: Pulling the enable pin on Adafruit PowerBoost to low (It's connected to VBatt!)
I am working on an Tonuino (tonuino.voss.earth), and I am using a PowerBoost-module from Adafruit (https://www.adafruit.com/product/1944) for it. The powerboost-module needs the enable pin driven to LOW(GND) to turn the output 5V off. Currently I have a rocker switch which allows me to permananently connect EN to GND.

I would like to implement a auto-off functionality for this combination, i.e. the arduino can drive the enable pin LOW and in this manner kill its own power. In addition to the auto-off, I want the user to be able to turn on the device via a button press. I come from a software background and my last connection to electronics is from a time long, long ago, which is why I am struggeling.

This shows my initial thoughts:

1. The user presses the button to start the Tonuino. The switch disconnects EN from GND, EN goes to UBATT(HIGH) and 5V to the arduino is enabled. By enabling the arduino, a GPIO is set to high and thus EN is maintained high
2. To turn off, the arduino sets the GPIO to LOW, thus setting EN to LOW, 5V are disabled and so forth...

My problem: 5V from the Arduino GPIO will always be at 5V and thus higher than the reference voltage of EN (UBATT 3V - 3.7V). I really am afraid that this will damage my lipo. For me this means, I ideally should switch UBATT for EN (safely) and am failing to come up with a solution.

Any pointers are greatly welcome

# Answer
Your biggest problem is that the module defaults to on. There is a 340kΩ resistor pulling the EN pin up to VBAT all the time, so to turn it off you have to actively override that pullup.

Ideally you would modify the module by removing that resistor (R13) and adding your own resistor between the ENABLE and GND pins. You can the override that with both a button and a P-channel FET in parallel to turn the module on.

For example:

simulate this circuit – Schematic created using CircuitLab

Now normally R1 pulls ENABLE to ground turning the module off. You press SW1 and it pulls ENABLE up to VBAT and turns it on. 5V then gets supplied to the Arduino, at which point you need to set the GPIO to output and pull it HIGH.

This causes the gate of M2 to be pulled above its threshold voltage (make sure it has a threshold voltage between 0V and 3V) and it starts to conduct pulling the gate of M1 below its threshold voltage (must be between 0V and -2V) bypassing switch SW1 keeping the system enabled.

You can now let go of SW1 and it will all stay powered on until you either set the GPIO LOW or set it to an INPUT.

Note that resetting the Arduino (for programming, for example) would cause the boost module to shut down and require re-powering with SW1 (or through the GPIO if you have the Arduino powered through USB for programming of course).

However if you don't want to or can't modify the module then things get a little nastier.

To make it default to OFF R1 in the above schematic will have to be low enough value that the voltage presented at the ENABLE pin is below 20% of the battery voltage. R1 and the existing 340kΩ pullup resistor form a voltage divider, so you need to calculate the size of resistor that will allow it to be below 20% VBAT.

Since a voltage divider just gives you a proportion of the input voltage whose ratio is the ratio of the "top" resistance in the divider to the total resistance we don't care what the voltage is, only the ratio. And we don't really care about the exact value, only that the result is *below* 20%. So we can pick a good common value.

However we don't want a value that is too low, because the voltage divider will be draining power from the battery all the time, so the higher the resistances the less the power drain will be.

For example if we pick the common value 47kΩ we see that:

```
    R2           47000
 ------- = --------------- = 0.11 (11%)
 R1 + R2    340000 + 47000

```

Which is below the 0.2 (20%) that we want, which is good. Calculating the current at a typical battery voltage of 3.7V we get

```
     V          3.7
I = --- = -------------- = 0.000010 (10µA)
     R    340000 + 47000

```

10µA is not much, on the scale of things, but it's good to know about it when you're working from a battery since it will form part of your power budget calculations.
> 2 votes

---
Tags: arduino-nano
---


# Question
Title: How do you make a Class variable array bigger?
I am making an infrared macro-keyboard, I want to store Unicode for the Keyboard class in an array inside a class I made called `Keybind`and to allow the user to program as many outputs as they want, I want the storage to be mutable. I currently use the String class and decode within the program but it's cpu intensive and not very practical.
I want to use an array or list, but I haven't found any way to expand the size of an array inside a class. Casting a temporary array didn't work:

```
  int intArray[] = {0,1,2,3,4,5};
  int* temp[7];

  for(int x = 0; x<sizeof(intArray)/sizeof(intArray[0]); x++){
    temp[x] = intArray[x];
  }
  temp[6] = 6;
  intArray = temp;

```

IDE spits out "`incompatible types in assignment of 'int* [7]' to 'int [6]'`"

# Answer
> 0 votes
> I want to \[...\] allow the user to program as many outputs as they want

This may be problematic. The microcontroller has a limited amount of RAM: it will not be able to store arbitrarily long macros. You should consider a way of telling the user “sorry, no more memory”. Or you can be optimistic and assume the user will never try to record macros long enough to exhaust the memory... and let the firmware crash if this assumption turns out to be invalid.

> I currently use the String class and decode within the program but it's cpu intensive and not very practical.

CPU intensive? You mean the allocation? Reading the contents of a String object is not CPU intensive. And what do you find impractical in the String class? At it's core, it's just a dynamically sized container for character data, which seems to be exactly what you are looking for.

> I haven't found any way to expand the size of an array inside a class.

A class is a data structure of *fixed size*. There is no way you can expand its contents. If you need something of variable size, you will have to use dynamic allocation. You will then only store a *pointer* to the allocated memory in your class. This is exactly what `String` does. The only other option is to store an array of fixed size within the class, and make that size large enough so that you never need more.

---
Tags: string, array
---


title: Arduino expected ':' before '{' token

text:
# Question
Title: Arduino expected ':' before '{' token
I wanted to compile a project yesterday which always worked until now. Probably since an adjustment of the libraries (update) I have not been able to do this anymore. I ask for help.

ERRORMESSAGE: exit status 1 expected ':' before '{' token

Line from Error

```
#define MSG_PRINT(...) { MSG_PRINTER.print(__VA_ARGS__); }

```

# Answer
> 2 votes
`MSG_PRINT` is a macro. It gets replaced in your code verbatim *before* compilation.

The error message will give you more information. Specifically it will tell you *where* the error is. For example:

```
/tmp/untitled1/untitled1.ino: In function 'void loop()':
/tmp/untitled1/untitled1.ino:1:24: error: expected ':' before '{' token
/tmp/untitled1/untitled1.ino:12:13: note: in expansion of macro 'MSG_PRINT'

```

Here I have defined `MSG_PRINT` at line 1, which is where it "says" the error is. However that's only where the macro is. The actual error is at line 12, where the error says the macro is being expanded. That's the *last* line in the error message.

The little bit of code I used to trigger that error is actually a `switch` command where I deliberately omitted the `:` at the end of a case statement:

```
    switch (v) {
        case 3 // <---- missing colon here
            MSG_PRINT("foo");
            break;
    }

```

If we replace `MSG_PRINT` as the preprocessor would we end up with:

```
    switch (v) {
        case 3
            { Serial.println("foo"); }
            break;
    }

```

(I defined `MSG_PRINT` to just call `Serial.println`...) and now we can better see the context of the error.

With the expansion now in place it is obvious that there is indeed a `:` missing before a `{`, even though that `{` isn't immediately visible in your code.

Learning to interpret these sometimes cryptic error messages is key to working with C and C++.

---
Tags: arduino-ide
---


title: DHT.h Library not being imported

text:
# Question
Title: DHT.h Library not being imported
I am trying to read the humidity and temperature using a DHT11 temperature sensor for an Arduino UNO using the `DHT.h` library. I have my code below:

```
#include <DHT.h>
#define dataPin 4
dht DHT;

void setup() {
  Serial.begin(9600)

}

void loop() {
  int readData = DHT.read11(dataPin);
  float t = DHT.temperature;
  float h = DHT.humidity;
  Serial.println("Temperature: ")
  Serial.print(t)
  Serial.print(" ºC")
  Serial.println("Humidity: ")
  Serial.print(h)
  Serial.print(" % ")
  delay(2000)
}

```

When compiling the program, it gives me an error:

```
fatal error: DHT.h: No such file or directory

```

I have also tried with lower case letters, but it will not work. Is there any reason why? Do I have to install it? I have tried to search for the library in the Arduino app **Sketch - Include Library - Manage Libraries**, but the library is not there.

# Answer
> 1 votes
1. Download https://github.com/RobTillaart/Arduino/archive/master.zip
2. Copy the `Arduino-master/libraries/DHTstable` subfolder of the downloaded file to the `libraries` subfolder of your sketchbook folder. You can find the location of your sketchbook folder at **File \> Preferences \> Sketchbook location** in the Arduino IDE.
3. Change the first line of your sketch from:

```
#include <DHT.h>

```

to:

```
#include <dht.h>

```

Now when you try to compile the sketch you will still encounter many errors. However, these are caused by a paucity of semicolons, not by the DHT library, and thus off-topic for this question.

# Answer
> 0 votes
I have had problems using some `DHT` library versions. I suggest that you try using a different version of `dht.h`

This version works for me (there are newer versions, but I recommend starting with this oldie but goldie):

dht.h (606B 6/12/2012)

```
//
//    FILE: dht.h
// VERSION: 0.1.00
// PURPOSE: DHT Temperature & Humidity Sensor library for Arduino
//
//     URL: http://arduino.cc/playground/Main/DHTLib
//
// HISTORY:
// see dht.cpp file
//

#ifndef dht_h
#define dht_h

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

#define DHT_LIB_VERSION "0.1.00"

class dht
{
public:
    int read11(uint8_t pin);
    int read22(uint8_t pin);
    double humidity;
    double temperature;

private:
    uint8_t bits[5];  // buffer to receive data
    int read(uint8_t pin);
};
#endif
//
// END OF FILE
//

```

# Answer
> 0 votes
try to download this library in this link and insert it to your ide, it works for me.

https://github.com/adafruit/DHT-sensor-library

---
Tags: c++, arduino-uno, electronics
---


# Question
Title: Int64_t aka long long acts as int32_t and overflows at 2^31
I have an `int64_t` variable. When I add another `int64_t` variable

and convert it to a double to print it on the serial monitor, it acts as if it was a `int32_t` variable. This is the program:

```
int64_t a = 1 << 31;
double b = static_cast<double>(a);
Serial.println(b);

```

The output on the serial monitor is `-2147483648.00`.

What is going on?

# Answer
> 3 votes
`1 << 31` is interpreted by the compiler as `(int)1 << (int)32`. See the implicit types of integer literals. The rules of usual arithmetic conversions state that no implicit conversion is performed in this case. The result is then computed as an `int`, and it overflows. Note that this is undefined behavior. The assignment `int64_t a = ...` converts the (already overflowed) result to the wider type, without changing its value.

You probably want to write something like:

```
int64_t a = 1LL << 31;

```

---
Tags: c++, data-type, print
---


# Question
Title: Trying to switch a 5v fan with a LiPo and can't figure our what's wrong at full duty cycle
I have a simple project where I want to turn a 5v fan on/off and both the MCU and fan will powered by a LiPo battery.

I'm powering the ESP and fan directly from the battery in the attached circuit. For now I've decided not to boost the power to 5v for the fan because the fan runs fine at lower voltage. Also using a BJT transistor as a low side switch.

This all seems to work fine except at full duty cycle the voltage to the fan seems to completely collapse. At just below full (like if a do analogWrite(pin 1000) it's humming along fine but when I go to 1023 the voltage drops from around 4 to closer to 2 and the fan stops. Even at lower duty cycles like 50% the fan operates nice and slow.

I put a multimeter on the leads to the fan and observe the voltage drop at full duty.

I'm very new to all this and have done a lot of reading but I haven't been able to solve this. Also this is my first fritzing drawing so I hope it makes sense.

Edit: I made some changes to the circuit and it's working as expected. I have also updated the circuit diagram below.

# Answer
> 1 votes
According to specs I found online, the NodeMCU wants 7-12V on Vin. Most LiPo cells put out around 4 volts, which isn't enough. The battery voltage may drop and the MCU's voltage regulator probably fails to keep putting out 3.3V when the fan's average power draw exceeds some threshold.

It might also be that the fan itself is slowing when the duty cycle approaches 100% and the battery voltage drops.

Doesn't the NodeMCU run on 3.3V, not 5V? If you feed 5V into the 3V pin and that's supposed to have 3.3V, it will likely damage or destroy the board.

---
Tags: motor, switch
---


# Question
Title: How to power Arduino pro mini and DFPlayer mini togather with 3.7 V LiPo battery?
I made a small box containing Arduino Pro Mini , DFPlayer Mini player and a 3.7V LiPo battery. Is it possible to power two devices with 3.7 V Battery? What is the best way to save power for longer time performance?

# Answer
> 1 votes
Use a buck/boost voltage regulator. Those are high efficiency switching regulators, and can either increase or decrease the input voltage. Feed the output of the regulator directly into the Arudino's 5V (or 3.3V) line, bypassing the on-board voltage regulator.

What input voltages do the 2 devices need? Both 5V? If so, you can use a single voltage regulator to power both devices. If one needs 3.3V and the other needs 5V you may have to have 2 different voltage regulators.

By using a switching regulator you can bypass the fairly inefficient linear regulator in your Arduino supply 3.3V or 5V to it directly (depending on the type of board you have.)

## Edit:

Ok, I looked it up and a DFPlayer Mini player appears to be a shield designed to plug directly into an Arduino. It looks like it can be powered from 3.2 to 5V, so you should be able to use it with either a 3.3V or 5V Arduino Pro Mini. Once you've decided if you're going to use a 3.3V or 5V Arduino, pick a buck/boost voltage regulator with the desired output voltage (or get an adjustable one and set it appropriately.)

---
Tags: power, arduino-pro-mini, battery
---


title: Using SD card shield on Arduino Due

text:
# Question
Title: Using SD card shield on Arduino Due
I have a Seeed Studio SD card shield (V3) that I am trying to use on my Arduino Due. I am having trouble using the SD examples that come with the Arduino IDE.

They worked fine on my Arduino Uno by setting `chipSelect` to `SS`. Below is the code I used for the Arduino Uno. It is the same as the `CardInfo.ino` in the examples section under SD (except for the `chipSelect`).

CardInfo.ino /\* SD card test

```
 This example shows how use the utility libraries on which the'
 SD library is based in order to get info about your SD card.
 Very useful for testing a card when you're not sure whether its working or not.

 The circuit:
  * SD card attached to SPI bus as follows:
 ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
 ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
 ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
 ** CS - depends on your SD card shield or module.
        Pin 4 used here for consistency with other Arduino examples

 created  28 Mar 2011
 by Limor Fried
 modified 9 Apr 2012
 by Tom Igoe
*/

// include the SD library:
#include <SPI.h>
#include <SD.h>

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = SS; //CHANGE HERE!!!!!!!!

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.print("\nInitializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  // or the SD library functions will not work.
  pinMode(10, OUTPUT);     // change this to 53 on a mega

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card is inserted?");
    Serial.println("* Is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    return;
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.print("\nCard type: ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("\nVolume type is FAT");
  Serial.println(volume.fatType(), DEC);
  Serial.println();

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);

  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);

  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
}

void loop(void) {

}

```

Here is a picture of my setup:

### tl;dr

How do I make this shield work on my Due?

# Answer
> 1 votes
Looking at the pin configuration, the SPI pins are not in the same location as the UNO. Remove the Shield from Due and use cables to connect to the SPI pins

---
Tags: serial, shields, arduino-due, sd-card, spi
---


# Question
Title: Teensy 2.0 MIDI: Number of notes in a chord limited to 6?
I am using the Teensy 2.0 with USBMidi in a project that allows musicians to use retro computers as "instruments" (https://github.com/fredlcore/midijoy). So far, all these computers had no more than four voices, so the problem I am encoutering now has not arisen so far.

When I now want to play a chord with more than six notes simultaneously, only the first six notes are received and played. However, if I release two from, let's say, eight notes, the remaining two notes are subsequently being played if these keys are still kept pressed.

Here is a script reduced to the bare minimum, when you press eight keys on the MIDI device one after another, you'll see that it stops after the sixth key, and when you then subsequently keep all keys pressed and release one after the other, you'll see that the "remaining" keys/notes will be received then:

```
void setup() {
  Serial.begin(38400);
  usbMIDI.setHandleNoteOn(doNote);
  usbMIDI.setHandleNoteOff(doNoteOff);
}

void loop() {
  usbMIDI.read();
}

void doNote(byte channel, byte pitch, byte velocity) {
  Serial.println(channel);
  Serial.println(pitch);
}

void doNoteOff(byte channel, byte pitch, byte velocity) {
  Serial.println(channel);
  Serial.println(pitch);
}

```

You have to configure the Teensy as a MIDI device so that the USBMidi libraries will be found.

Is there a hardware limit in the Teensy 2.0 that will prevent it from processing more than six notes at a time? Or is this a constraint within the library?

# Answer
@Majenko pointed me to the root cause of the problem: I was sending MIDI notes via Ableton's feature of using the computer's keyboard. It seems that the OS (or the keyboard) cannot send/receive more than six simultaneous keystrokes.
> 0 votes

---
Tags: usb, library, teensy, midi
---


# Question
Title: How can I make my custom board use the programmer selected in "Tools->Programmer" when the Upload button is pushed?
I've created a custom board that can be programmed using any one of several programmers defined in `programmers.txt`. I would like the user to be able to choose which programmer to use via the "Tools-\>Programmer" menu options.

I tried using `{protocol}` and `{upload.protocol}` in `platform.txt` to pass the programmer to the upload tool, but neither seem to be defined when the `Upload` button is used to initiate the upload (they are defined if `Upload using programmer` is selected from the menu).

# Answer
Make sure you do not have a `protocol` listed in the `boards.txt` file. If the uploader sees protocol is `null` then it will fall back to using the same code that "Upload using programmer" does.

Relevant code in `SerialUploader.java`:

```
    if (usingProgrammer || prefs.get("upload.protocol") == null) {
      return uploadUsingProgrammer(buildPath, className);
    }

```
> 0 votes

---
Tags: uploading
---


# Question
Title: upload.tool not used in custom boards.txt?
I've created a custom board in `boards.txt` and changed the `upload.tool` to a nonsense value, and yet when I do an upload the IDE still calls `avrdude`.

For example, In boards.txt I've changed the line...

```
tile.upload.tool=avrdude

```

...to...

```
tile.upload.tool=nogood

```

...and added these lines to platform.txt...

```
# NOGOOD programmer

tools.nogood.cmd="dir"
tools.nogood.program.pattern="dir"
tools.nogood.upload.pattern="dir"

```

...and reloaded the IDE and hit upload.. and it still runs AVRDUDE.

(Note that my board ID is `tile`)

I've verified that I am editing the correct boards.txt by changing the `cores` key to `nogood` and this does generate an error.

Is `boardid.upload.tool` not the right place to change the recipe called when upload is hit?

How/where does the `boardid.upload.tool=toolname` key in boards.txt get mapped to the `tools.toolname.upload.pattern` key in platforms.txt?

I am using Arduino IDE version 1.8.3.

The custom boards.txt is in the directory `Arduino\hardware\Move38\avr`.

This full custom platform package is here...

https://github.com/bigjosh/Move38-Arduino-Platform

Thanks!

# Answer
If you leave the `protocol` unset in the `boards.txt`, then the current version of the Ardunio IDE (1.8.12) will then use the `program` recipe rather than the `upload` recipe in `platform.txt`. The `program` recipe can use the `{protocol}` key to get the programmer selected in the IDE menus.

Relevant source in Arduino IDE `SerialUploader.java`...

```
if (usingProgrammer || prefs.get("upload.protocol") == null) {
  return uploadUsingProgrammer(buildPath, className);
}

```
> 0 votes

# Answer
From https://github.com/bigjosh/Move38-Arduino-Platform#programmers:

> Since there is no bootloader in a tile, all code must be programmed rather than downloaded.

When you do an "Upload Using Programmer", the tool is specified in the `{programmerID}.program.tool` property in programmers.txt. The `{boardID}.upload.tool` value is only used for a standard upload.

Since programmers.txt is not in your hardware package, this makes it very inconvenient to customize. What's worse is that the platform.txt associated with the selected programmer is used, rather than the one in your hardware package, for "Upload Using Programmer". For this reason, some popular hardware packages include their own copies of all standard programmers. The downside of this is it really clutters up the **Tools \> Programmer** menu if you have multiple of these packages installed.
> 4 votes

# Answer
Custom tools for the Arduino build process are documented in the Boards Manager Package Index spec here...

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package\_index.json-format-specification#tools-definitions

So it would seem that it i not possible to use custom tools with a manually installed board since there is no package index file.
> 2 votes

---
Tags: arduino-ide
---


title: Serial.print() not fully printing

text:
# Question
Title: Serial.print() not fully printing
println() function is being used to send AT commands to GSM module.

```
sim800l.println("AT+CLTS=1");
  delay(3000);
  sim800l.println("AT+COPS=2");
  delay(3000);
  sim800l.println("AT+COPS=0,0");
  delay(3000);

```

But problem is the output -

```
AT+CLTS=1

OK
AT+COP

```

The command AT+COP did not print fully? Why?
Minimal Reproducable Example -

```
#include <SoftwareSerial.h>    //Library required for serial communication
char MYDATA[18];
SoftwareSerial sim800l(3, 2); // RX,TX for Arduino and for the module it's TXD RXD, they should be inverted
void setup() {
  Serial.begin(9600); //Start the serial interface on 9600
  sim800l.begin(9600);
  delay(100);
  // AT command to set sim800l to SMS mode
  sim800l.println("AT+CMGF=1");
  //Serialcom();
  delay(100);
  // Set module to send SMS data to serial out upon receipt
  sim800l.println("AT+CNMI=2,2,0,0,0");
  delay(100);
  sim800l.println("AT+CLTS=1");
  delay(3000);
  sim800l.println("AT+COPS=2");
  delay(3000);
  sim800l.println("AT+COPS=0,0");
  delay(3000);
   sim800l.println("AT+CCLK?");
  Serial.find("+CCLK: \"");
  Serial.readBytesUntil('\+', MYDATA, 17);

}

void loop() {
 Serial.print(MYDATA);
}

```

# Answer
> 0 votes
You're overflowing the serial receive buffer. There's only a limited amount of space (64 bytes normally, maybe less in SoftwareSerial) for receiving data before you must read it or lose data. Since you are just blindly throwing commands at the SIM800 and not doing anything with its responses until right at the end all that incoming data fills the receive buffer to overflowing.

Your methodology is flawed (not your fault, the examples on the internet are all rubbish and teach you the wrong way of doing things). What you should be doing is issuing a command then receiving the response back and parsing it to see if the command was successful or not, and retrieve any information that the response may include that you would want to know.

---
Tags: arduino-uno
---


# Question
Title: 3-instruction remote machine coding Arduino Atmel chip over a serial line from a tethered (host) PC
I'm trying to write a program for AVR Atmel 328 chip on Arduino Nano board that will allow me to send machine code instructions to the chip over a serial line, run/execute them on the chip, and interrogate the results by reading chip memory and sending the contents back over the serial line. This is the genesis of the idea: 3-instruction Forth by Frank Sergeant.

The remote-store and remote-fetch instructions appear to be working fine, but **I've not been able to get the remote-call instruction (`XCALL()` function) to work.** The approach I've taken is to coerce a 16-bit address into a subroutine by casting it as a function pointer.

Below is the code that is running on the Arduino Nano (compiled in the Arduino IDE and uploaded using the USB cable via the bootloader)

Any insight would be greatly appreciated! (I can add diassembled code, my remote instructions etc, if that helps).

Thanks in advance!

```
// Remote serial development platform for machine coding ArduinoNano/ATmel328, AKE, Jun 9, 2020

// global variables
unsigned char byt;                  // command token from host
unsigned char mem[255];             // memory window under programmatic control
unsigned char dat;                  // data byte from host
unsigned char adr_lo;               // address from host, low byte first
unsigned char adr_hi;
unsigned short adr;                 // combined 16-bit address
typedef void (*GeneralFunction)();  // template to call memory address (as a subroutine)

void setup() {
  Serial.begin(9600);              // Turn UART serial protocol ON for comms with host PC
  Serial.write(0xFF);              // magic number to verify transmission
  Serial.write(0xFE);
  Serial.write((int) mem);         // Informs you of the writeable address space available (LSB, MSB) for tethered memory access
  Serial.write((int) mem>>8);
}

char get_byte(void) {
    while (!(Serial.available()>0)) { delay(50); }
    return Serial.read();
}
short get_adr(void) {
    adr_lo=get_byte();
    adr_hi=get_byte();
    return ( (short)adr_hi<<8 )   |   (short)adr_lo;
}
void xstore() {             // Instruction 1 = xstore(data,adr_lo,adr_hi).  Store byte from host at indicated address in target.
    dat=get_byte();
    adr=get_adr();
    *(char *)adr=dat;
}
void xfetch() {             //  Instruction 2 = xfetch(adr_lo,adr_hi).  Read byte from target memory and return to host.
        adr=get_adr();
        dat=*(char *)adr;
        Serial.write(dat);
}
void xcall() {              //  Instruction 3 = xcall(adr_lo,adr_hi).  Execute subroutine in target memory from indicated address.
                            //  WARNING!  User must have stored RET instruction to send control back to serial monitor.
        adr=get_adr();
        GeneralFunction fGf=adr;
        fGf;
}

void loop() {
    byt = get_byte();               // user specified instruction token (1,2,3)
    if(byt == 0x01 )      { xstore(); }
    else if (byt == 0x02) { xfetch(); }
    else if (byt == 0x3 ) { xcall(); } // else ignore any other serial inputs
}

```

# Answer
> 2 votes
The AVR CPU cannot execute instructions from RAM. It's not a question of what the compiler can do or should be able to do, the physical chip itself cannot do it. There is simply no physical pathway between the RAM and the instruction decoder in the CPU.

Instructions can *only* be executed directly from Flash memory. That is how the chip works. You can only execute code that you send over serial if you first erase a page (or more) of Flash memory then burn the incoming code into that page. You can then call the start of that page's address and your code will execute.

But there is another caveat there: only code running in the bootloader flash area is allowed to modify the flash memory. That means your code can't do it, only the bootloader. That doesn't mean that the bootloader has to be running, but the code that you execute has to reside there.

There is an alternative version of the Optiboot bootloader that can provide flash writing facilities to a user program, but I have no experience using it so can't assist with that.

---
Tags: serial, avr, remote-control, memory, atmel
---


# Question
Title: Exit from for function after detecting obstacles
```
#include <HCSR04.h>

int red = 13;
int green = 12;
int blue = 11;
int trigger = 9;
int echo = 8;
int halt;

void setup(){
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(trigger, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);
}

void redLed(){
  rgb(255,0,0);
  delay(200);
}

void rgb(int r, int g, int b){
  analogWrite(red, r);
  analogWrite(green, g);
  analogWrite(blue, b);
}

void fadeBlu(){

    for (int i=0; i<=255; i+=5){
    rgb(0,0,i);
    delay(40);

    Serial.print("halt in IF is ");
    Serial.println(halt);
    }

    for(int i=255; i>=0; i-=5) {
      rgb(0,0,i);
      delay(40);

      Serial.print("halt ELSE is ");
      Serial.println(halt);
    }
}

void human() {

  UltraSonicDistanceSensor distanceSensor(trigger, echo);
  double distance = distanceSensor.measureDistanceCm();
  halt = 0;

  // cover sensor
  if (distance<=30) {
    halt=0;
    redLed();
  }
  // no cover
    halt=-1;
    fadeBlu();
}

void loop(){
  human();
}

```

I'm looking for a way to exit from "for" loop of fadeBlue() function if the hand is detected in front of sensor. I would like that in any case of fading and if there is hand in front of sensor the led became red. In my code the led doesn't stay red if I had hand in front of the sensor and also the value of "halt" doesn't change. I put some serial.println to make debugging.

# Answer
First, try to avoid duplication of code, so make a sub function (I slightly changed the print statement, but I assume it's only for debugging):

```
void fadeBlu()
{
    fadeBlueCycle(0, 255, 5);
    fadeBlueCycle(255, 0, -5);
}

void fadeBlueCycle(uint8_t start, uint8_t end, int8_t step)
{
    for (int i = start; i != end; i += step)
    {
        rgb(0, 0, i);
        delay(40);

        Serial.print("halt in step ");
        Serial.print(step);
        Serial.println(halt);
    }
}

```

Now to break from the `for`, you can use `break`, or simply `return`. It's not a good practice to have multiple `return` statements in one function, thus put it at the end, and use a `break`. Also, some people don't like a `break` and prefer using a \`while. This would look like:

```
void fadeBlueCycle(uint8_t start, uint8_t end, int8_t step)
{
    uint8_t i = start;
    bool condition = true;

    while ((i != end) && condition) // or !condition, depending on what you prefer
    {
        rgb(0, 0, i);
        delay(40);

        Serial.print("halt in step ");
        Serial.print(step);
        Serial.println(halt);

        condition = `some condition`;
        i += step;
    }
}

```
> 0 votes

---
Tags: loop
---


title: Using RX TX pin

text:
# Question
Title: Using RX TX pin
Can i use pin RX TX on Arduino Uno as reguler pin ? . For input and output pin , because two digital pin on my board doesn’t work . Thank’s

# Answer
> 1 votes
Yes, you can use those pins like regular digital pins on the Uno. They are numbered 0 and 1. That is... provided you do not try to use `Serial`.

---
Tags: arduino-uno, serial, programming, arduino-ide
---


# Question
Title: Flash firmware with hex file over serial with Python (no avrdude, Arduino IDE)
I'm trying to make a Python function in the TCLab package to flash firmware to an Arduino Leonardo (32u4). I can compile the TCLab ino (firmware) and deploy with the Arduino IDE or with the Python avryp package. The Python avr\_helpers package looks like a possible solution but is only supported with the older Python 2.7. Forum posts such as this one, how can I upload a hex file to an arduino uno?, and others suggest `avrdude` to upload a hex file. However, I need a Python solution that can be used on any platform (MacOS, Windows, Linux, etc) without a requirement to install packages (avrdude, Arduino IDE, etc).

I have the hex file from a successful Arduino build. Here is an unsuccessful attempt to load the hex file with serial communication:

```
import serial
import time
import os

# open and close COM8 to activate bootloader
ser = serial.Serial('COM8',baudrate=1200)
print(ser.isOpen()); ser.close()
time.sleep(2)

# load hex file on COM9
filesize = os.path.getsize('tclab_v2.ino.hex')
fid = open('tclab_v2.ino.hex','rb')
offset = 0; MTU = 20
ser2 = serial.Serial('COM9',115200)
while (offset < filesize):
    fid.seek(offset, 0)
    ser2.write(fid.read(MTU))
    offset = offset + MTU
ser2.close()

```

The script is able to activate the bootloader on another port and connect. If I transfer all at once with `ser2.write(fid.read())`, it semi-bricks the Arduino and I recover it by hitting the reset button just before the Arduino IDE installs the firmware. I use a Maximum Transfer Unit (MTU) of 20 but I couldn't verify if there is one for the Leonardo. I can write a Python function to identify the ports and have used `COM8` and `COM9` here just to simply the test. Although the TCLab firmware is preloaded for Python, sometimes users change the firmware to use MATLAB, Octave, or Java and then want to switch back to Python. I'd like to make that as easy as possible without adding more steps or more instructions to the troubleshooting FAQ. Can I update the firmware like the MATLAB Arduino Support Package that detects a new device and transfers the firmware automatically with user confirmation?

# Answer
This isn't the exact answer but it helps.

Uploading without avrdude is complicated and generally slow. The best solution to not using the IDE is to open and close a port then use the avrdude command that the ide usually uses.

```
from serial import Serial
from time import sleep
from subprocess import run

while input('Press enter to upload ') == '':
    Serial('COM5',baudrate=1200).close()
    sleep(1)
    run(["C:\\Progra~2\\Arduino\\hardware\\tools\\avr/bin/avrdude", "-CC:\\Progra~2\\Arduino\\hardware\\tools\\avr/etc/avrdude.conf", "-v", "-patmega32u4", "-cavr109", "-PCOM6", "-b57600", "-D", "-Uflash:w:C:\\Users\\USER\\Desktop\\Python\\tclab_v2/tclab_v2.ino.hex:i"])

```
> 1 votes

---
Tags: serial, bootloader, python, atmega32u4
---