# Question
Title: Serial monitor listing unreadable characters
My Serial Monitor is displaying unreadable characters. If anybody can give me some insight on why this would be happening please let me know.

Thank You.

# Answer
Change `Serial.write` to `Serial.print` (or `Serial.println`).

`write` writes in binary, which gives you unprintable characters.
> 6 votes

# Answer
Make sure the selected baud (like 115200, 57600) in Serial Monitor matched the one specified in code like Serial.begin(115200)
> 3 votes

# Answer
I had the same problem, baud rate was the same in the code as it was in the serial monitor. I tried changing the baud rate in the code to 19200 and the same in the serial terminal and that fixed the problem. Hope this helps, not sure why it wasn't working with the 9600 baud value. Also found that clicking on the wrong baud rate in the terminal and back on the right one fixed the issue with it displaying gibberish.
> 1 votes

---
Tags: arduino-uno, serial
---


# Question
Title: if statement does not work with fraction, but works with decimal equivalent
I'm trying to trouble shoot a problem with my code and narrowed it down to my if statement not working with a fraction.

The below code does not work and returns 0

```
for(float i=0; i <= 1; i += .0001){
 t += .0001;
 if(t >= 1/440){ //Fraction
   t = 0;
 }
 Serial.println(t*100);
 delay(100);
}

```

But when I replace the 1/440 with its decimal equivalent (.0022727) it works fine and counts from 0 to 2.2

```
for(float i=0; i <= 1; i += .0001){
 t += .0001;
 if(t >= 0.0022727){ //Decimal
   t = 0;
 }
 Serial.println(t*100);
 delay(100);
}

```

If there is a simple way to use a fractional value instead of a decimal value it would make my application much similar. Thanks.

# Answer
`1/440` will be treated as an integer expression, returning zero.

To make it work, make one or both operands a floating-point type. In your case:

```
 if(t >= (float)1 / 440){ //Fraction
   t = 0;
 }

```

Or:

```
 if(t >= 1.0/440){ //Fraction
   t = 0;
 }

```
> 2 votes

---
Tags: programming, c++, sketch, loop
---


# Question
Title: Wemos D1 won't work with MH-Z19B (CO2 sensor)
I would like to connect a CO2 sensor to the Wemos D1. I would like it to work via UART (RX, TX) and not the PWM pin. I've encountered numerous libraries on Github, but I can't seem to get it working. I've connected the following things:

I've tried a lot of snippets from all over the internet, and a lot of libraries on Github, but I can't seem to get it working. For the sake of this question, I am going to use this advanced library.

This is my code:

```
#include <Arduino.h>
#include "MHZ19.h"                                         // include main library
#include <SoftwareSerial.h>                                // Remove if using HardwareSerial or non-uno library compatable device

#define RX_PIN D1                                          // Rx pin which the MHZ19 Tx pin is attached to
#define TX_PIN D2                                          // Tx pin which the MHZ19 Rx pin is attached to
#define BAUDRATE 9600                                      // Native to the sensor (do not change)

MHZ19 myMHZ19;                                             // Constructor for MH-Z19 class
SoftwareSerial mySerial(RX_PIN, TX_PIN);                   // Uno example
//HardwareSerial mySerial(1);                              // ESP32 Example

unsigned long getDataTimer = 0;                             // Variable to store timer interval

void setup()
{
    Serial.begin(9600);                                     // For ESP32 baudarte is 115200 etc.
    mySerial.begin(BAUDRATE);                               // Uno example: Begin Stream with MHZ19 baudrate
    //mySerial.begin(BAUDRATE, SERIAL_8N1, RX_PIN, TX_PIN); // ESP32 Example
    myMHZ19.begin(mySerial);                                // *Important, Pass your Stream reference
    myMHZ19.autoCalibration();                              // Turn auto calibration ON (disable with autoCalibration(false))
}

void loop(){
    if (millis() - getDataTimer >= 2000)                    // Check if interval has elapsed (non-blocking delay() equivilant)
    {
        int CO2;                                            // Buffer for CO2

        /* note: getCO2() default is command "CO2 Unlimited". This returns the correct CO2 reading even
        if below background CO2 levels or above range (useful to validate sensor). You can use the
        usual documented command with getCO2(false) */

        CO2 = myMHZ19.getCO2();                             // Request CO2 (as ppm)
        Serial.print("CO2 (ppm): ");
        Serial.println(CO2);

        int8_t Temp;                                         // Buffer for temperature
        Temp = myMHZ19.getTemperature();                     // Request Temperature (as Celsius)
        Serial.print("Temperature (C): ");
        Serial.println(Temp);

        getDataTimer = millis();                            // Update interval
    }
}

```

I am constantly getting this:

```
19:39:59.750 -> !Error: Timed out waiting for response
19:39:59.784 -> !ERROR: Failed to verify connection(1) to sensor. Failed to stablise
19:39:59.853 -> !ERROR: Initial communication errorCode recieved
19:40:00.272 -> !Error: Timed out waiting for response
19:40:00.758 -> !Error: Timed out waiting for response
19:40:00.792 -> CO2 (ppm): 0
19:40:01.280 -> !Error: Timed out waiting for response
19:40:01.315 -> Temperature (C): -17

```

Am I connecting something wrong or what am I doing wrong?

**EDIT:** Version using only the serial instead of library that also doesn't work:

```
#include <SoftwareSerial.h>
SoftwareSerial co2Serial(3, 1);
unsigned long startTime = millis();

void setup() {
  Serial.begin(9600);
  co2Serial.begin(9600);
  pinMode(9, INPUT);
}

void loop() {
  Serial.println("------------------------------");
  Serial.print("Time from start: ");
  Serial.print((millis() - startTime) / 1000);
  Serial.println(" s");
  int ppm_uart = readCO2UART();
  delay(5000);
}

int readCO2UART(){
  byte cmd[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
  byte response[9]; // for answer

  Serial.println("Sending CO2 request...");
  co2Serial.write(cmd, 9); //request PPM CO2

  // clear the buffer
  memset(response, 0, 9);
  int i = 0;
  while (co2Serial.available() == 0) {
    Serial.print("Waiting for response ");
    Serial.print(i);
    Serial.println(" s");
    delay(1000);
    i++;
  }

  if (co2Serial.available() > 0) {
      co2Serial.readBytes(response, 9);
  }

  // print out the response in hexa
  for (int i = 0; i < 9; i++) {
    Serial.print(String(response[i], HEX));
    Serial.print("   ");
  }
  Serial.println("");

  // checksum
  byte check = getCheckSum(response);
  if (response[8] != check) {
    Serial.println("Checksum not OK!");
    Serial.print("Received: ");
    Serial.println(response[8]);
    Serial.print("Should be: ");
    Serial.println(check);
  }

  // ppm
  int ppm_uart = 256 * (int)response[2] + response[3];
  Serial.print("PPM UART: ");
  Serial.println(ppm_uart);

  // temp
  byte temp = response[4] - 40;
  Serial.print("Temperature? ");
  Serial.println(temp);

  // status
  byte status = response[5];
  Serial.print("Status? ");
  Serial.println(status);
  if (status == 0x40) {
    Serial.println("Status OK");
  }

  return ppm_uart;
}

byte getCheckSum(byte *packet) {
  byte i;
  unsigned char checksum = 0;
  for (i = 1; i < 8; i++) {
    checksum += packet[i];
  }
  checksum = 0xff - checksum;
  checksum += 1;
  return checksum;
}

```

# Answer
> 1 votes
I know it is rather late to respond. What worked for me working with a *WEMOS D1 mini* and the *MH-Z19C* was reassigning the Software Pins used *SoftwareSerial co2Serial(D1, D2);* In that case the second sketch posted works atleast for me.

The problem might be that the ESP8266 uses the hardware serial lines for connection to the USB-to-Serial bridge (usually a CH340 or CP2102 in most designs) which means you might encounter problems if you want to use the same serial line for more than one device.

---
Tags: arduino-uno, esp8266, nodemcu
---


# Question
Title: Atmega 328pu on breadboard. What to choose in order to upload code with ftdi converter
When I program atmega328 PU on breadboard,vwhat programmer do I have to use and what arduino board type I have to choose? I am trying this with ftdi converter I have already done the connections and it's okay but there's an error when I'm trying to upload the code either with instant upload either with the programmer. Everything can help is acceptable and thanks in advance for your support.

# Answer
> 0 votes
There are quite a few questions here about breadboard computers. Try searching this site for "breadboard". I also have a page about making a breadboard Arduino which might help.

Normally I would set the Arduino type to Uno if the breadboard computer has a 16 MHz oscillator or crystal on it. If you are running at 8 MHz (possibly with the internal oscillator) I would set it to Lilypad.

If the chip doesn't have a bootloader on it then you need to install that first. I have a page about installing a bootloader which might help.

To install the bootloader you need to use an SPI interface as described on the above page. That requires running 6 wires from an existing (working) Arduino to your breadboard.

> it's okay but there's an error when I'm trying to upload the code

It's OK? But there's an error? What error message?

# Answer
> 0 votes
I have a number of atmega328-PU-on-breadboards. I build them with a 16MHz crystal and load the Uno Optiboot loader if they don't already have a bootloader installed. I program them with an FTDI USB to TTL Serial 5V Adapter Cable 6 Pin 0.1 inch Pitch Female Socket Header UART IC FT232RL Chip (or the 3.3v version of the same cable, if I built for 3.3v). By using a 16 MHz crystal and a standard bootloader, I can select 'Uno' as the board type in the IDE and everything works.
On the board, I build a 6-pin header to accept the cable's 6-pin female header I use connect it for for uploading and/or viewing debug output on the board's serial port, but otherwise remove it and power the board through a more compact micro-USB connector. You could always make a more permanent connection between your board and the USB-FTDI cable if you find that more suitable.

Update:

> what programmer do you choose ? Also can you share your pinout ?

My programmer is avrdude, run by the IDE. My boards program exactly like an Uno.

Pinout:

.

The CTS output (brown wire) is unused; the RTS output is wired connected to the reset pin through a 0.1uF capacitor, if you want the auto-reset feature. If you are using a different FTDI device, you will, of course, have to use it's particular pinout but it should provide the same signals and behavior.

This is the reset circuit I use on my board (crudely drawn but gets the point across):

---
Tags: atmega328, uploading, ftdi, breadboard, arduino-setup
---


# Question
Title: Arduino Mega Loopback Test with Several TX/RX Ports
I am trying to do a loopback test using an Arduino Mega. What I am looking to do is send a byte over TX and receive said byte back at RX and verify that the byte is unchanged. More or less I just have a jumper wire connecting the TX and RX ports (In reality I have a circuit hooked up to the TX RX ports that effectively acts like a wire, I'm just trying to verify that the circuit traces are sound).

I am also doing the exact same thing over TX2/RX2 and TX3/RX3.

The issue I have run into is that I can't seem to get the data to send out the TX ports. In my attempt I used Serial objects where I would do the following:

```
void setup() {
Serial.begin(9600); //0 and 1
Serial2.begin(9600); //16 and 17
Serial3.begin(9600); //14 and 15
}

void loop() {

//RX TX
int bytesSent = Serial.write(1);
delay(500);
if(Serial.read()!=bytesSent){

  //Do Something

}

delay(500);

//RX2 TX2
bytesSent = Serial2.write(2);
delay(500);
if(Serial2.read()!=bytesSent){

   //Do Something

}

delay(500);

//RX3 TX3
bytesSent = Serial3.write(3);
delay(500);
if(Serial3.read()!=bytesSent){

   //Do Something

}

delay(500);

}

```

I'm aware that the use of "delay(500)" is not optimal nor good coding practice but is left here for now while I'm still trying to understand what's wrong with my transmit and receive.

I believe my misunderstanding comes in with the Serial objects; Am I not using them correctly in this case? I've referenced the Arduino Serial reference guide, so this seems like it would work, but does not.

Further details: I am currently powering my Arduino via USB (which I'm aware can be an issue, but I currently do not have the battery power source). Would switching to the other power source resolve my issue? Just to reiterate I'm not trying to communicate with the PC, I'm just trying to verify that this external circuit (which acts like a wire) is able to carry the signal.

# Answer
> 1 votes
There seems to be a slight misunderstanding here:

```
bytesSent = Serial2.write(2);
// [...]
if (Serial2.read() != bytesSent) // [...]

```

On the serial ports:

* the method `write()` returns the number of bytes that were written, not the value of a written byte
* the method `read()` returns the byte that was read (or −1 if nothing was available), not the number of bytes read.

I suggest you modify your test like this:

```
uint8_t byte_sent = random(256);
Serial2.write(byte_sent);
delay(100);
if (Serial2.read() != byte_sent) // there was an error

```

---
Tags: serial, arduino-mega, usb, hardware, uart
---


title: Transmitting voice via VLC

text:
# Question
Title: Transmitting voice via VLC
The project I'm working on: Short-Range Coded Visible Light Communication System.

Visible Light Communication (VLC) systems use light to transfer data between transmitter and receiver over short-range links. This project intends to build a wireless VLC system capable of transmitting voice between two microcontrollers such as an Arduino or a Raspberry Pi using visible light.

An LED or laser diode is deployed at the transmitter side, and a Light Dependent Resistor (LDR) or photodiode is deployed at the receiving side.

Digital data is transmitted using on-off keying where the LED functions as on-off light. Strings of ones (1) and zeros (0) are transmitted with high frequency such that the LED flicking is undetectable to the human eye.

I'm using an Arduino Uno and this is the code that I used. I'm hearing noise from the speaker, not my voice.

```
Transmitter code:
// Define microphone pin
const int micPin = A0;

// Define LED pin
const int ledPin = 9;

// Define sampling frequency (in Hz)
const int samplingFrequency = 8000;

void setup() {
  // Set microphone pin as input
  pinMode(micPin, INPUT);

  // Set LED pin as output
  pinMode(ledPin, OUTPUT);

  // Begin serial communication at 9600 baud rate
  Serial.begin(9600);
}

void loop() {
  // Read analog voltage from microphone
  int analogValue = analogRead(micPin);

  // Map analog voltage to PWM duty cycle (0-255)
  int dutyCycle = map(analogValue, 0, 1023, 0, 255);

  // Set LED brightness based on duty cycle
  analogWrite(ledPin, dutyCycle);

  // Print duty cycle value to serial monitor
  Serial.println(dutyCycle);

  // Delay to maintain sampling frequency
  delay(1000 / samplingFrequency);
}

```

Receiver code:

```
const int ldrPin = 9;
const int speakerPin = 11;
int voiceSample;

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

void loop() {
  analogWrite(ldrPin, voiceSample);
  delay(10);
  voiceSample++;
  if (voiceSample > 255) {
    voiceSample = 0;
  }
  int voiceInput = analogRead(A0);
  voiceInput = map(voiceInput, 0, 1023, 0, 255);
  analogWrite(speakerPin, voiceInput);
}

```

# Answer
> 0 votes
The `Serial.println(dutyCycle)` in your transmitter is going to seriously slow down communications. It takes 1.04 ms to send a single byte over serial at 9600 baud, and assuming you have 3 digits, plus carriage return and linefeed that will take over 5 ms for each serial print.

However you are trying to sample at 8000 times a second (once per 125 µs) so you simply won't keep up. I suggest removing the serial print.

---

> ```
> delay(1000 / samplingFrequency);
>
> ```

The `delay` function takes a `long` argument, not a float. `1000 / 8000` will evaluate to zero so the sample rate will not in fact be 8000 times a second.

You may want to consider the delayMicroseconds function.

---

Did you write this code or ChatGPT? ChatGPT questions are currently banned on Stack Overflow. I'm not sure about their policy in regards to Arduino Stack Exchange.

---
Tags: arduino-uno, serial, led, speaker
---


# Question
Title: Unexpected Behaviour w/ Arduino Uno Calculation
I have a really simple snippet of code wherein the same calculation outputs different values depending on how I do the calculation. The platform that I am running this code on is an **Arduino Uno** \- with an **Atmel MEGA328P** microcontroller chip. Here's the code:

```
void setup() {

  Serial.begin(9600);
  unsigned long num = 100927;
  Serial.println(1000*60);
  Serial.println(num/(1000*60));
  Serial.println(num/(60000));
}

void loop() {}

```

This code prints the following on the console:

```
-> -5536
-> 0
-> 1

```

I don't understand why `num/(1000*60)` and `num/(60000)` evaluate to different values? Also, `1000*60` evaluates to a garbage value which looks like it somehow set the data type to int and resulted in overflowing the "int" range.

My programming background is heavy in Python. I figure I'm used to python dynamically interpreting variable data types for me which is why the arduino language confuses me a bit here. Any help is appreciated!

# Answer
> 3 votes
This is a pure C++ programming issue, which I cover on my web site.

However, since link-only answers are not allowed here, I reproduce that post below:

---

On the Arduino (Uno) platform, what do you think will be printed here?

```
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  Serial.println (30000 + 30000); // twice 30000
  Serial.println (60 * 60 * 24);  // seconds in a day
  Serial.println (50 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

```

Did you guess:

```
60000
86400
500

```

Nope!

It prints:

```
-5536
20864
0

```

This is because of **integer arithmetic**. If the compiler can, it treats an numeric literal (like 60) as an int type, which means it has the range -32768 to +32767. This may be unexpected for users of modern compilers because nowadays an `int` is usually 32 bits. However on the 8-bit Arduino processors such as the Atmega328P the compiler treats an int as 16 bits wide. The C++ standard permits an int size of **at least** 16 bits, but you are not guaranteed that it will be larger.

And, arithmetic is done using the type of the largest argument, which means the arithmetic in each case is done as 16-bit arithmetic, and thus it overflows once it reaches 32767.

For example, 30000 + 30000 = 60000 which is 0xEA60 in hex. Unfortunately, 0xEA60 is exactly how -5536 is stored in an int type, which is why it prints -5536.

Meanwhile, 60 * 60 * 24 = 86400 which is 0x15180 in hex. As that doesn't fit in 16 bits, it is truncated to 0x5180 which is 20864 in decimal (as printed).

Finally, in integer arithmetic 50/100 is zero, multiply zero by 1000 and you still get zero, which is why the final result is zero.

---

So, can we "help" the compiler by telling it the sort of result we want, like this?

```
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  long a = 30000 + 30000;
  long b = 60 * 60 * 24;
  float c = 50 / 100 * 1000;

  Serial.println (a);
  Serial.println (b);
  Serial.println (c);
  }  // end of setup

void loop () { }

```

That prints:

```
-5536
20864
0.00

```

So no, that hasn't helped.

---

## Solution

First, you can add a suffix to numeric literals (eg. L for long, or UL for unsigned long), and add a decimal place to floats, like this:

```
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  Serial.println (30000L + 30000); // twice 30000
  Serial.println (60L * 60 * 24);  // seconds in a day
  Serial.println (50.0 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

```

Now we get:

```
60000
86400
500.00

```

You only need to help out with the first literal, once the compiler knows we are using longs (or floats) it sticks with them for the expression. *

Or we can "cast" them:

```
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  long a =  (long) 30000 + 30000;
  long b =  (long) 60 * 60 * 24;
  float c = (float) 50 / 100 * 1000;

  Serial.println (a);
  Serial.println (b);
  Serial.println (c);
  }  // end of setup

void loop () { }

```

Results:

```
60000
86400
500.00

```

Casting is useful for variables, because you can't just add "L" to the end of a variable name.

An alternative syntax is to use a constructor like this:

```
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  long a =  long (30000) + 30000;
  long b =  long (60) * 60 * 24;
  float c = float (50) / 100 * 1000;

  Serial.println (a);
  Serial.println (b);
  Serial.println (c);
  }  // end of setup

void loop () { }

```

(Same results).

---

* It's actually somewhat more complex than that as this link explains: Understand integer conversion rules

The compiler "promotes" a value in an expression to match another "higher-ranked" type, under certain circumstances. For example, adding an **int** and a **long** will result in the **int** being promoted to a **long** (regardless of whether it appears first in the expression or not). However if an **int** is being added to another **int**, it will *not* promote them to a **long**, even though the result may not fit into an **int**.

---

## More explanations

I was asked in the comments why `1000 * 60` is not the same as `60000` from the compiler's point of view.

The answer is that a compiler will treat an integer literal as an **int** (if possible) and an **int** on this platform is 16 bits.

Thus 1000 (an **int**) * 60 (another **int**) are multiplied using 16-bit arithmetic, giving a result that overflows.

However the literal, 60000, cannot be stored as an **int** and thus the compiler promotes it to **long** (aka "**long** **int**"). Since it has been promoted to a **long** it is correctly stored, and further operations on 60000 will be done with **long** arithmetic.

I have seen people code 60000 as 60000L however that is unnecessary. The compiler is not silly enough to make 60000 be stored as -5536, as that is clearly not the intent of the programmer.

---
Tags: arduino-uno, calculation
---


# Question
Title: 50% duty cycle PWM signal with calculated frequency
```
#include <PWM.h>
int led = 9;
void setup()
{
  InitTimersSafe();
  Serial.begin(115200);
  Serial.println();
  variable_freq();
  pinMode(A0,INPUT);
}
void variable_freq()
{
   while(true)
 {
   a=analogRead(A0);
   float p = (a/1024)*5;
   int Vi = p/0.143;
   float Vo = 12;
   float Po=100;
   float n=1, ni=0.9, Ntr=1, Vf=0.7, Rf=0.018, rc=0.025, Mvs=0.9;
   float Rl=(Vo*Vo)/Po;
   float fo = 70000;
   float Mv = Vo/Vi;
   float Qo=6;
   float pi = 3.14159;
   float g ;
   g= (1+(2*(Vf/Vo))+((Rf*pi*pi)/4*Rl)+(rc/Rl)*(((pi*pi)/8)-1));
   float Ri=((8*Rl*n*n)/(Ntr*pi*pi))*g;
   float Mvr, MVR, h;
   Mvr=(pi*Ntr)/(2*n*sqrt(2)*g);
   MVR=Mv/(Mvs*Mvr);
   h=(sqrt((pow((ni/MVR), 2))-1))/Qo;
   float f_sw;
   f_sw = ((fo*h)/2) + (sqrt(pow(fo*h,2) + 4*pow(fo,2)))/2;

   SetPinFrequency(led,f_sw);

   float T = 0.5;

   pwmWriteHR(led,T*65536);
 }
}

```

I am working on a project where I have to find a required frequency from a varying DC input voltage. I am using Arduino Nano to produce a PWM signal of this required freqeuncy.

From the code, once the frequency *f\_sw* is calculated, I have used the *setPinFrequency* function to set the frequency of pin D9 to *f\_sw*. I want a PWM signal of duty cycle 50% with f\_sw as the frequency.

Does pwmWriteHR(led,T\*65536) accomplish this? As per this website, pwmWrite()'s 2nd argument is the duty cycle. Given that pwmWriteHR() is just the higher resolution version of pwmWrite(), will this output the signal as per my requirements?

I cannot test this on a board yet, so I simulated it in Proteus, but the frequency of the signal I obtained there does not match, although the duty cycle was 50%.

# Answer
Let's look at what's possible using the Atmega328P (which is on the Nano).

The timers are really just counters, with the input to the counter being the system clock, possibly after being divided down by a prescaler.

Timers 0 and 2 are 8-bit timers which means they can count to 256 before wrapping around. Timer 1 is a 16-bit timer which means it can count to 65536 before wrapping. The inputs to the timers are zero-relative, so the actual counter limits are 255 (0xFF) and 65535 (0xFFFF).

Your desired frequency of 76441 means the period is 1/76441 seconds, namely 13.082 µs.

With no prescaler, the period of the system clock is 1/16000000, namely 0.0625 µs.

Divide 13.082 by 0.0625 and you get 209.312 which means 209 counts are going to roughly get you the frequency you want.

However then we have to divide by 2 because each time the counter counts up we toggle the output, and it takes two toggles to do one period (one up, one down).

So we need to set up a timer of 209/2 which is 104.5. Since we can't count up to half a count we actually count up to 104. The code to do that, without needing any libraries, is:

---

## Example code

```
void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  unsigned long Hz = 76441;

  // it takes two toggles for one "cycle"
  unsigned long ocr = (F_CPU / Hz / 2) - 1;

  // stop timer
  TCCR1A = 0;
  TCCR1B = 0;
  // reset counter
  TCNT1H = 0;
  TCNT1L = 0;

  // what to count up to
  OCR1AH = highByte (ocr);
  OCR1AL = lowByte (ocr);

  TCCR1A = bit (COM1A0);              // toggle output pin
  TCCR1B = bit (WGM12) | bit (CS10);  // start timer, CTC mode
  }  // end of setup

void loop() { }

```

The results on pin 9 were measured as 76.805 kHz which is slightly out, partly because of the fact that the resolution is in increments of 62.5 ns, and partly because the Nano has resonator\* rather than a crystal, so its clock might not be exactly 16 MHz.

* I'm not sure about that.

---

## Duty cycle

In this particular example we have a 50% duty cycle because each time the timer reaches its count it toggles the output. Thus it does it symmetrically. That is, the on portion will be the same length as the off portion.

There are other timer modes which can be used for PWM generation where the duty cycle is not 50%. See the datasheet for more information.

---

## Prescaler

The prescalers (not used in this particular example) are used to extend the length of time that a timer can count for.

Possible prescalers are 1, 8, 32, 64, 128, 256, and 1024. Prescalers of 32 and 128 are only available on timer 2.

So, for example, if you use a prescaler of 8 then each "tick" of the timer will be 8 * 62.5 ns, so it can count for 8 times as long before it overflows. However each count will only have a resolution of 500 ns rather than 62.5 ns, so you can get a less precise time measurement.

Choosing prescalers is a compromise between resolution and the available time period you can time for.

---

See my page about timers for more discussion about the Atmega328P timers.

---

## List of possible frequencies

From my page above I reproduce this list which shows what frequency and period you get for various timer counts, and prescalers.

```
  n  -- Prescale 1   --  -- Prescale 8   --  -- Prescale 64  --  -- Prescale 256 --  -- Prescale 1024--
     Freq (Hz) Per (µs)  Freq (Hz) Per (µs)  Freq (Hz) Per (µs)  Freq (Hz) Per (µs)  Freq (Hz) Per (µs)
  1: 8,000,000*   0.125  1,000,000    1.000    125,000    8.000     31,250   32.000      7,813  128.000
  2: 5,333,333    0.188    666,667    1.500     83,333   12.000     20,833   48.000      5,208  192.000
  3: 4,000,000    0.250    500,000    2.000     62,500   16.000     15,625   64.000      3,906  256.000
  4: 3,200,000    0.313    400,000    2.500     50,000   20.000     12,500   80.000      3,125  320.000
  5: 2,666,667    0.375    333,333    3.000     41,667   24.000     10,417   96.000      2,604  384.000
  6: 2,285,714    0.438    285,714    3.500     35,714   28.000      8,929  112.000      2,232  448.000
  7: 2,000,000    0.500    250,000    4.000     31,250   32.000      7,813  128.000      1,953  512.000
  8: 1,777,778    0.563    222,222    4.500     27,778   36.000      6,944  144.000      1,736  576.000
  9: 1,600,000    0.625    200,000    5.000     25,000   40.000      6,250  160.000      1,563  640.000
 10: 1,454,545    0.688    181,818    5.500     22,727   44.000      5,682  176.000      1,420  704.000
 11: 1,333,333    0.750    166,667    6.000     20,833   48.000      5,208  192.000      1,302  768.000
 12: 1,230,769    0.813    153,846    6.500     19,231   52.000      4,808  208.000      1,202  832.000
 13: 1,142,857    0.875    142,857    7.000     17,857   56.000      4,464  224.000      1,116  896.000
 14: 1,066,667    0.937    133,333    7.500     16,667   60.000      4,167  240.000      1,042  960.000
 15: 1,000,000    1.000    125,000    8.000     15,625   64.000      3,906  256.000        977 1024.000
 16:   941,176    1.063    117,647    8.500     14,706   68.000      3,676  272.000        919 1088.000
 17:   888,889    1.125    111,111    9.000     13,889   72.000      3,472  288.000        868 1152.000
 18:   842,105    1.187    105,263    9.500     13,158   76.000      3,289  304.000        822 1216.000
 19:   800,000    1.250    100,000   10.000     12,500   80.000      3,125  320.000        781 1280.000
 20:   761,905    1.313     95,238   10.500     11,905   84.000      2,976  336.000        744 1344.000
 21:   727,273    1.375     90,909   11.000     11,364   88.000      2,841  352.000        710 1408.000
 22:   695,652    1.438     86,957   11.500     10,870   92.000      2,717  368.000        679 1472.000
 23:   666,667    1.500     83,333   12.000     10,417   96.000      2,604  384.000        651 1536.000
 24:   640,000    1.562     80,000   12.500     10,000  100.000      2,500  400.000        625 1600.000
 25:   615,385    1.625     76,923   13.000      9,615  104.000      2,404  416.000        601 1664.000
 26:   592,593    1.688     74,074   13.500      9,259  108.000      2,315  432.000        579 1728.000
 27:   571,429    1.750     71,429   14.000      8,929  112.000      2,232  448.000        558 1792.000
 28:   551,724    1.813     68,966   14.500      8,621  116.000      2,155  464.000        539 1856.000
 29:   533,333    1.875     66,667   15.000      8,333  120.000      2,083  480.000        521 1920.000
 30:   516,129    1.938     64,516   15.500      8,065  124.000      2,016  496.000        504 1984.000
 31:   500,000    2.000     62,500   16.000      7,813  128.000      1,953  512.000        488 2048.000
 32:   484,848    2.062     60,606   16.500      7,576  132.000      1,894  528.000        473 2112.000
 33:   470,588    2.125     58,824   17.000      7,353  136.000      1,838  544.000        460 2176.000
 34:   457,143    2.188     57,143   17.500      7,143  140.000      1,786  560.000        446 2240.000
 35:   444,444    2.250     55,556   18.000      6,944  144.000      1,736  576.000        434 2304.000
 36:   432,432    2.313     54,054   18.500      6,757  148.000      1,689  592.000        422 2368.000
 37:   421,053    2.375     52,632   19.000      6,579  152.000      1,645  608.000        411 2432.000
 38:   410,256    2.438     51,282   19.500      6,410  156.000      1,603  624.000        401 2496.000
 39:   400,000    2.500     50,000   20.000      6,250  160.000      1,563  640.000        391 2560.000
 40:   390,244    2.563     48,780   20.500      6,098  164.000      1,524  656.000        381 2624.000
 41:   380,952    2.625     47,619   21.000      5,952  168.000      1,488  672.000        372 2688.000
 42:   372,093    2.687     46,512   21.500      5,814  172.000      1,453  688.000        363 2752.000
 43:   363,636    2.750     45,455   22.000      5,682  176.000      1,420  704.000        355 2816.000
 44:   355,556    2.812     44,444   22.500      5,556  180.000      1,389  720.000        347 2880.000
 45:   347,826    2.875     43,478   23.000      5,435  184.000      1,359  736.000        340 2944.000
 46:   340,426    2.938     42,553   23.500      5,319  188.000      1,330  752.000        332 3008.000
 47:   333,333    3.000     41,667   24.000      5,208  192.000      1,302  768.000        326 3072.000
 48:   326,531    3.063     40,816   24.500      5,102  196.000      1,276  784.000        319 3136.000
 49:   320,000    3.125     40,000   25.000      5,000  200.000      1,250  800.000        313 3200.000
 50:   313,725    3.188     39,216   25.500      4,902  204.000      1,225  816.000        306 3264.000
 51:   307,692    3.250     38,462   26.000      4,808  208.000      1,202  832.000        300 3328.000
 52:   301,887    3.313     37,736   26.500      4,717  212.000      1,179  848.000        295 3392.000
 53:   296,296    3.375     37,037   27.000      4,630  216.000      1,157  864.000        289 3456.000
 54:   290,909    3.437     36,364   27.500      4,545  220.000      1,136  880.000        284 3520.000
 55:   285,714    3.500     35,714   28.000      4,464  224.000      1,116  896.000        279 3584.000
 56:   280,702    3.562     35,088   28.500      4,386  228.000      1,096  912.000        274 3648.000
 57:   275,862    3.625     34,483   29.000      4,310  232.000      1,078  928.000        269 3712.000
 58:   271,186    3.688     33,898   29.500      4,237  236.000      1,059  944.000        265 3776.000
 59:   266,667    3.750     33,333   30.000      4,167  240.000      1,042  960.000        260 3840.000
 60:   262,295    3.813     32,787   30.500      4,098  244.000      1,025  976.000        256 3904.000
 61:   258,065    3.875     32,258   31.000      4,032  248.000      1,008  992.000        252 3968.000
 62:   253,968    3.938     31,746   31.500      3,968  252.000        992 1008.000        248 4032.000
 63:   250,000    4.000     31,250   32.000      3,906  256.000        977 1024.000        244 4096.000
 64:   246,154    4.063     30,769   32.500      3,846  260.000        962 1040.000        240 4160.000
 65:   242,424    4.125     30,303   33.000      3,788  264.000        947 1056.000        237 4224.000
 66:   238,806    4.188     29,851   33.500      3,731  268.000        933 1072.000        233 4288.000
 67:   235,294    4.250     29,412   34.000      3,676  272.000        919 1088.000        230 4352.000
 68:   231,884    4.313     28,986   34.500      3,623  276.000        906 1104.000        226 4416.000
 69:   228,571    4.375     28,571   35.000      3,571  280.000        893 1120.000        223 4480.000
 70:   225,352    4.437     28,169   35.500      3,521  284.000        880 1136.000        220 4544.000
 71:   222,222    4.500     27,778   36.000      3,472  288.000        868 1152.000        217 4608.000
 72:   219,178    4.563     27,397   36.500      3,425  292.000        856 1168.000        214 4672.000
 73:   216,216    4.625     27,027   37.000      3,378  296.000        845 1184.000        211 4736.000
 74:   213,333    4.688     26,667   37.500      3,333  300.000        833 1200.000        208 4800.000
 75:   210,526    4.750     26,316   38.000      3,289  304.000        822 1216.000        206 4864.000
 76:   207,792    4.813     25,974   38.500      3,247  308.000        812 1232.000        203 4928.000
 77:   205,128    4.875     25,641   39.000      3,205  312.000        801 1248.000        200 4992.000
 78:   202,532    4.938     25,316   39.500      3,165  316.000        791 1264.000        198 5056.000
 79:   200,000    5.000     25,000   40.000      3,125  320.000        781 1280.000        195 5120.000
 80:   197,531    5.062     24,691   40.500      3,086  324.000        772 1296.000        193 5184.000
 81:   195,122    5.125     24,390   41.000      3,049  328.000        762 1312.000        191 5248.000
 82:   192,771    5.188     24,096   41.500      3,012  332.000        753 1328.000        188 5312.000
 83:   190,476    5.250     23,810   42.000      2,976  336.000        744 1344.000        186 5376.000
 84:   188,235    5.312     23,529   42.500      2,941  340.000        735 1360.000        184 5440.000
 85:   186,047    5.375     23,256   43.000      2,907  344.000        727 1376.000        182 5504.000
 86:   183,908    5.438     22,989   43.500      2,874  348.000        718 1392.000        180 5568.000
 87:   181,818    5.500     22,727   44.000      2,841  352.000        710 1408.000        178 5632.000
 88:   179,775    5.563     22,472   44.500      2,809  356.000        702 1424.000        176 5696.000
 89:   177,778    5.625     22,222   45.000      2,778  360.000        694 1440.000        174 5760.000
 90:   175,824    5.687     21,978   45.500      2,747  364.000        687 1456.000        172 5824.000
 91:   173,913    5.750     21,739   46.000      2,717  368.000        679 1472.000        170 5888.000
 92:   172,043    5.813     21,505   46.500      2,688  372.000        672 1488.000        168 5952.000
 93:   170,213    5.875     21,277   47.000      2,660  376.000        665 1504.000        166 6016.000
 94:   168,421    5.937     21,053   47.500      2,632  380.000        658 1520.000        164 6080.000
 95:   166,667    6.000     20,833   48.000      2,604  384.000        651 1536.000        163 6144.000
 96:   164,948    6.063     20,619   48.500      2,577  388.000        644 1552.000        161 6208.000
 97:   163,265    6.125     20,408   49.000      2,551  392.000        638 1568.000        159 6272.000
 98:   161,616    6.188     20,202   49.500      2,525  396.000        631 1584.000        158 6336.000
 99:   160,000    6.250     20,000   50.000      2,500  400.000        625 1600.000        156 6400.000
100:   158,416    6.313     19,802   50.500      2,475  404.000        619 1616.000        155 6464.000
101:   156,863    6.375     19,608   51.000      2,451  408.000        613 1632.000        153 6528.000
102:   155,340    6.438     19,417   51.500      2,427  412.000        607 1648.000        152 6592.000
103:   153,846    6.500     19,231   52.000      2,404  416.000        601 1664.000        150 6656.000
104:   152,381    6.562     19,048   52.500      2,381  420.000        595 1680.000        149 6720.000
105:   150,943    6.625     18,868   53.000      2,358  424.000        590 1696.000        147 6784.000
106:   149,533    6.688     18,692   53.500      2,336  428.000        584 1712.000        146 6848.000
107:   148,148    6.750     18,519   54.000      2,315  432.000        579 1728.000        145 6912.000
108:   146,789    6.813     18,349   54.500      2,294  436.000        573 1744.000        143 6976.000
109:   145,455    6.875     18,182   55.000      2,273  440.000        568 1760.000        142 7040.000
110:   144,144    6.938     18,018   55.500      2,252  444.000        563 1776.000        141 7104.000
111:   142,857    7.000     17,857   56.000      2,232  448.000        558 1792.000        140 7168.000
112:   141,593    7.063     17,699   56.500      2,212  452.000        553 1808.000        138 7232.000
113:   140,351    7.125     17,544   57.000      2,193  456.000        548 1824.000        137 7296.000
114:   139,130    7.187     17,391   57.500      2,174  460.000        543 1840.000        136 7360.000
115:   137,931    7.250     17,241   58.000      2,155  464.000        539 1856.000        135 7424.000
116:   136,752    7.313     17,094   58.500      2,137  468.000        534 1872.000        134 7488.000
117:   135,593    7.375     16,949   59.000      2,119  472.000        530 1888.000        132 7552.000
118:   134,454    7.437     16,807   59.500      2,101  476.000        525 1904.000        131 7616.000
119:   133,333    7.500     16,667   60.000      2,083  480.000        521 1920.000        130 7680.000
120:   132,231    7.563     16,529   60.500      2,066  484.000        517 1936.000        129 7744.000
121:   131,148    7.625     16,393   61.000      2,049  488.000        512 1952.000        128 7808.000
122:   130,081    7.687     16,260   61.500      2,033  492.000        508 1968.000        127 7872.000
123:   129,032    7.750     16,129   62.000      2,016  496.000        504 1984.000        126 7936.000
124:   128,000    7.813     16,000   62.500      2,000  500.000        500 2000.000        125 8000.000
125:   126,984    7.875     15,873   63.000      1,984  504.000        496 2016.000        124 8064.000
126:   125,984    7.938     15,748   63.500      1,969  508.000        492 2032.000        123 8128.000
127:   125,000    8.000     15,625   64.000      1,953  512.000        488 2048.000        122 8192.000
128:   124,031    8.063     15,504   64.500      1,938  516.000        484 2064.000        121 8256.000
129:   123,077    8.125     15,385   65.000      1,923  520.000        481 2080.000        120 8320.000
130:   122,137    8.188     15,267   65.500      1,908  524.000        477 2096.000        119 8384.000
131:   121,212    8.250     15,152   66.000      1,894  528.000        473 2112.000        118 8448.000
132:   120,301    8.313     15,038   66.500      1,880  532.000        470 2128.000        117 8512.000
133:   119,403    8.375     14,925   67.000      1,866  536.000        466 2144.000        117 8576.000
134:   118,519    8.438     14,815   67.500      1,852  540.000        463 2160.000        116 8640.000
135:   117,647    8.500     14,706   68.000      1,838  544.000        460 2176.000        115 8704.000
136:   116,788    8.563     14,599   68.500      1,825  548.000        456 2192.000        114 8768.000
137:   115,942    8.625     14,493   69.000      1,812  552.000        453 2208.000        113 8832.000
138:   115,108    8.688     14,388   69.500      1,799  556.000        450 2224.000        112 8896.000
139:   114,286    8.750     14,286   70.000      1,786  560.000        446 2240.000        112 8960.000
140:   113,475    8.812     14,184   70.500      1,773  564.000        443 2256.000        111 9024.000
141:   112,676    8.875     14,085   71.000      1,761  568.000        440 2272.000        110 9088.000
142:   111,888    8.938     13,986   71.500      1,748  572.000        437 2288.000        109 9152.000
143:   111,111    9.000     13,889   72.000      1,736  576.000        434 2304.000        109 9216.000
144:   110,345    9.063     13,793   72.500      1,724  580.000        431 2320.000        108 9280.000
145:   109,589    9.125     13,699   73.000      1,712  584.000        428 2336.000        107 9344.000
146:   108,844    9.188     13,605   73.500      1,701  588.000        425 2352.000        106 9408.000
147:   108,108    9.250     13,514   74.000      1,689  592.000        422 2368.000        106 9472.000
148:   107,383    9.313     13,423   74.500      1,678  596.000        419 2384.000        105 9536.000
149:   106,667    9.375     13,333   75.000      1,667  600.000        417 2400.000        104 9600.000
150:   105,960    9.437     13,245   75.500      1,656  604.000        414 2416.000        103 9664.000
151:   105,263    9.500     13,158   76.000      1,645  608.000        411 2432.000        103 9728.000
152:   104,575    9.563     13,072   76.500      1,634  612.000        408 2448.000        102 9792.000
153:   103,896    9.625     12,987   77.000      1,623  616.000        406 2464.000        101 9856.000
154:   103,226    9.688     12,903   77.500      1,613  620.000        403 2480.000        101 9920.000
155:   102,564    9.750     12,821   78.000      1,603  624.000        401 2496.000        100 9984.000
156:   101,911    9.813     12,739   78.500      1,592  628.000        398 2512.000        100 10048.000
157:   101,266    9.875     12,658   79.000      1,582  632.000        396 2528.000         99 10112.000
158:   100,629    9.938     12,579   79.500      1,572  636.000        393 2544.000         98 10176.000
159:   100,000   10.000     12,500   80.000      1,563  640.000        391 2560.000         98 10240.000
160:    99,379   10.062     12,422   80.500      1,553  644.000        388 2576.000         97 10304.000
161:    98,765   10.125     12,346   81.000      1,543  648.000        386 2592.000         96 10368.000
162:    98,160   10.188     12,270   81.500      1,534  652.000        383 2608.000         96 10432.000
163:    97,561   10.250     12,195   82.000      1,524  656.000        381 2624.000         95 10496.000
164:    96,970   10.313     12,121   82.500      1,515  660.000        379 2640.000         95 10560.000
165:    96,386   10.375     12,048   83.000      1,506  664.000        377 2656.000         94 10624.000
166:    95,808   10.438     11,976   83.500      1,497  668.000        374 2672.000         94 10688.000
167:    95,238   10.500     11,905   84.000      1,488  672.000        372 2688.000         93 10752.000
168:    94,675   10.563     11,834   84.500      1,479  676.000        370 2704.000         92 10816.000
169:    94,118   10.625     11,765   85.000      1,471  680.000        368 2720.000         92 10880.000
170:    93,567   10.687     11,696   85.500      1,462  684.000        365 2736.000         91 10944.000
171:    93,023   10.750     11,628   86.000      1,453  688.000        363 2752.000         91 11008.000
172:    92,486   10.813     11,561   86.500      1,445  692.000        361 2768.000         90 11072.000
173:    91,954   10.875     11,494   87.000      1,437  696.000        359 2784.000         90 11136.000
174:    91,429   10.938     11,429   87.500      1,429  700.000        357 2800.000         89 11200.000
175:    90,909   11.000     11,364   88.000      1,420  704.000        355 2816.000         89 11264.000
176:    90,395   11.063     11,299   88.500      1,412  708.000        353 2832.000         88 11328.000
177:    89,888   11.125     11,236   89.000      1,404  712.000        351 2848.000         88 11392.000
178:    89,385   11.188     11,173   89.500      1,397  716.000        349 2864.000         87 11456.000
179:    88,889   11.250     11,111   90.000      1,389  720.000        347 2880.000         87 11520.000
180:    88,398   11.312     11,050   90.500      1,381  724.000        345 2896.000         86 11584.000
181:    87,912   11.375     10,989   91.000      1,374  728.000        343 2912.000         86 11648.000
182:    87,432   11.438     10,929   91.500      1,366  732.000        342 2928.000         85 11712.000
183:    86,957   11.500     10,870   92.000      1,359  736.000        340 2944.000         85 11776.000
184:    86,486   11.563     10,811   92.500      1,351  740.000        338 2960.000         84 11840.000
185:    86,022   11.625     10,753   93.000      1,344  744.000        336 2976.000         84 11904.000
186:    85,561   11.688     10,695   93.500      1,337  748.000        334 2992.000         84 11968.000
187:    85,106   11.750     10,638   94.000      1,330  752.000        332 3008.000         83 12032.000
188:    84,656   11.813     10,582   94.500      1,323  756.000        331 3024.000         83 12096.000
189:    84,211   11.875     10,526   95.000      1,316  760.000        329 3040.000         82 12160.000
190:    83,770   11.937     10,471   95.500      1,309  764.000        327 3056.000         82 12224.000
191:    83,333   12.000     10,417   96.000      1,302  768.000        326 3072.000         81 12288.000
192:    82,902   12.063     10,363   96.500      1,295  772.000        324 3088.000         81 12352.000
193:    82,474   12.125     10,309   97.000      1,289  776.000        322 3104.000         81 12416.000
194:    82,051   12.188     10,256   97.500      1,282  780.000        321 3120.000         80 12480.000
195:    81,633   12.250     10,204   98.000      1,276  784.000        319 3136.000         80 12544.000
196:    81,218   12.313     10,152   98.500      1,269  788.000        317 3152.000         79 12608.000
197:    80,808   12.375     10,101   99.000      1,263  792.000        316 3168.000         79 12672.000
198:    80,402   12.437     10,050   99.500      1,256  796.000        314 3184.000         79 12736.000
199:    80,000   12.500     10,000  100.000      1,250  800.000        313 3200.000         78 12800.000
200:    79,602   12.562      9,950  100.500      1,244  804.000        311 3216.000         78 12864.000
201:    79,208   12.625      9,901  101.000      1,238  808.000        309 3232.000         77 12928.000
202:    78,818   12.688      9,852  101.500      1,232  812.000        308 3248.000         77 12992.000
203:    78,431   12.750      9,804  102.000      1,225  816.000        306 3264.000         77 13056.000
204:    78,049   12.813      9,756  102.500      1,220  820.000        305 3280.000         76 13120.000
205:    77,670   12.875      9,709  103.000      1,214  824.000        303 3296.000         76 13184.000
206:    77,295   12.938      9,662  103.500      1,208  828.000        302 3312.000         75 13248.000
207:    76,923   13.000      9,615  104.000      1,202  832.000        300 3328.000         75 13312.000
208:    76,555   13.062      9,569  104.500      1,196  836.000        299 3344.000         75 13376.000
209:    76,190   13.125      9,524  105.000      1,190  840.000        298 3360.000         74 13440.000
210:    75,829   13.187      9,479  105.500      1,185  844.000        296 3376.000         74 13504.000
211:    75,472   13.250      9,434  106.000      1,179  848.000        295 3392.000         74 13568.000
212:    75,117   13.313      9,390  106.500      1,174  852.000        293 3408.000         73 13632.000
213:    74,766   13.375      9,346  107.000      1,168  856.000        292 3424.000         73 13696.000
214:    74,419   13.438      9,302  107.500      1,163  860.000        291 3440.000         73 13760.000
215:    74,074   13.500      9,259  108.000      1,157  864.000        289 3456.000         72 13824.000
216:    73,733   13.563      9,217  108.500      1,152  868.000        288 3472.000         72 13888.000
217:    73,394   13.625      9,174  109.000      1,147  872.000        287 3488.000         72 13952.000
218:    73,059   13.687      9,132  109.500      1,142  876.000        285 3504.000         71 14016.000
219:    72,727   13.750      9,091  110.000      1,136  880.000        284 3520.000         71 14080.000
220:    72,398   13.812      9,050  110.500      1,131  884.000        283 3536.000         71 14144.000

```

* = may not work reliably, testing shows.

Space restraints preclude including the entire list, see the page mentioned above for a few more rows.
> 1 votes

---
Tags: arduino-nano, pwm, timers, analogread
---


title: Arduino Bluepill STM32 spi doesn't work

text:
# Question
Title: Arduino Bluepill STM32 spi doesn't work
Has anyone successfully use SPI1 of those pins?

```
SCLK -> PB3
SDIO -> PB5
SDO -> PB4
MISO CS -> PA15

```

I've tried to use another side of SPI1 pins on the other sides of the board (PA4, 5, 6, 7) and i can successfully communicate with

# Answer
> 0 votes
It depends on how you use the SPI object. If you use the SPI object directly like what Arduino Uno without creating an instance object, the SPI construct will default to the PA4 - PA7, see the default pins definition and default Class construct of Blue Pill.

For STM32 Arduino Core (Stm32duino), there are four STM32 Arduino Core specific APIs for configure the alternative SPI pins.

```
void setMISO(uint32_t miso)
void setMOSI(uint32_t mosi)
void setSCLK(uint32_t sclk)
void setSSEL(uint32_t ssel)

```

These **must** be called before the `SPI.begin()`.

Another alternative way of using the alternative SPI pins is to create an SPI object and pass-in the pin assignments like this:

```
#include <SPI.h>

SPIClass mySPI(PB5, PB4, PB3, PB15); //mosi, miso, sclk, ssel

```

See the alternative construct API, and further information on STM32duino wiki page.

---
Tags: spi, stm32
---


title: What do I need for a plug?

text:
# Question
Title: What do I need for a plug?
I've manage to build myself an RFID music player which I'm pretty chuffed with. It's definitely a bit home made but it woks and I'm proud of it. I don't know what plug type to buy to sort my problem below:

As you can see from the second photo, my wiring is a big mess. I've wired up all the components on the lid (the RFID reader, three buttons, and a speaker) with 21 single plug wire connections. As you can clearly see from the photo, it's a dogs breakfast of wires. Worse, the wiring is fragile and connections can break when I open and close the box.

The fix, I think, is fairly simple: to wire up a multi-wire plug connection between the lid and the box. That is have all the wires from the lid feed into one side of a plug, and all the wires on the bottom feed into the other side of the plug. That way, I can bundle all the wires up and attach them neatly out of the way, with the only moving part being the large multi-wire plugs.

I would really like one plug (male and female) with at least 21 pins, or few smaller pinned plugs to clean everything up. I don't know what to search for - when I google search for plugs, wiring harness, connections, etc, I get a variety of plugs and wires that just don't seem quite what I'm looking for.

Ideally, I'd like to be able to set up the plug by just screwing in each of the bare tinned wire ends. That way, alls I have to do is cut each single wire plug off, strip back the wire, tin it, then screw it into the plug in the right spot. Do that 21 times for each side and hey presto: 2 neat plugs.

Can someone please let me know what plug type I need? Or any other helpful suggestions?

# Answer
You could have use say 4 long stand-off spacers and mounted the circuit board on the underside of the lid (as you have done with the RFID reader), possibly inverting it for easier access to the arduino usb socket and SD card, so the lid could be removed without stressing the wiring. If you had used a printed circuit board then edge connectors would have been a possibility. I suppose you could use 0.1" header pins on the circuit board and use DuPont or similar connectors.
> -1 votes

---
Tags: arduino-nano, wires, project, enclosure
---


# Question
Title: IR Receiver Remote Controller for Windows
My dad watches netflix on his pc with his wireless mouse, hes gotten older and cannot hit the volume slide well enough.

I have an arduino kit (ard nano), an IR recevier and remote controller laying around (all from the arduino kit).

I want to use the remote control when you press volume down on it to make the windows volume go down. I tried using chatgpt but have gotten nowhere, what would be the best simplest solution for this.

I was thinking it would be an easy read-in of the data from the receiver but how would you transfer this data on to windows? Is this possible, I havent found many examples online

Thank you all :)

# Answer
There are USB / HID keyboard codes for volume. Here we see volume up is 0x80 and volume down is 0x81.

Consider obtaining an Arduino board which is capable of supporting a USB / HID port so that you can easily emulate a keyboard. It would be best to choose a board with hardware USB / HID support. But it may be possible to emulate (limited?) USB / HID support using software only.

There are plenty of Arduino USB / HID project (here and here are just 2 examples). This should get you started designing an Arduino sketch which can transmit a keyboard's volume up and down control codes into one of the computer's USB ports.

And there are plenty of Arduino ASK / IR receiver projects (here and here are just 2 examples). As there are many IR remote control codes, this part of the project might take a bit of research to uncover the codes used in the IR remote control you posses.
> 1 votes

---
Tags: ir, remote-control, windows
---


# Question
Title: Program to Multiply Numbers Won't Actually Multiply Them
I am trying to write a program which takes in a number of pairs to be multiplied, then prints out the result of each multiplication. Instead of doing this, the program just prints out the number of multiplications and the numbers, but it never does the multiplications or add the newline characters (despite me explicitly using println). In the example below I specify 2 number pairs to multiply, and then enter 3,4,7,8 (entering a NL character after each number, but spaces and commas cause the same problem).

I thought my approach would work, but I believe that there is something I am doing with the serial input that is causing the code not work (although there could be some other issue). I also wonder if maybe it's because I'm running this in Tinkercad and not the real Arduino IDE. Any help would be greatly appreciated.

```
void loop()
 {
  int numOfMults = 0;                             // number of pairs to multiply
  float *numArray;                                // pointer to beginning of array memory block
  numArray = (float *)malloc(sizeof(float)*50);   // dynamically allocate an array that can hold up to 50 floats

  numOfMults = Serial.parseInt(); // take in the number of multiplications from user

  Serial.println(numOfMults);

  // take in the specified amount of numbers (2 times the num of multiplications) in format: 1,2,3...
  // then convert that into an array of floats, where every 2 indices
  // is a pair of numbers to multiply
  for (int i = 0; i < (2*numOfMults) ;i++)
    {
      numArray[i] = Serial.parseFloat();
    }
      multNums(numOfMults,numArray);  // call function to get the product of all the numbers

      delay(5000);                    // wait 5 seconds before starting the loop again
 }

void multNums(int numofNums,float nums[])
{
  float *productArray;                                 // pointer to beginning of the product array memory block
  productArray = (float *)malloc(sizeof(float)*25);    // dynamically allocate an array that can hold up to 25 floats (for the products)

  // multiply all the number pairs in the array, store the product in another
  for(int i=0;i<(2*numofNums);i+2)
  {
      productArray[i/2] = nums[i]*nums[i+1];         // multiply current number pair, store in the product array one index at a time
  }
  // print the products
  for(int i=0; i < sizeof(productArray) ;i++)
  {
    Serial.println(productArray[i]);
  }
}

```

# Answer
> 1 votes
Ok I figured it out.

In the for loop I had to use i +=2, and not i+2.

What a dumb mistake..

# Answer
> 1 votes
There are quite a few issues in this code:

* In C++, you are supposed to do dynamic allocation with `new` rather than `malloc()`.
* If you allocate dynamic memory in a loop and forget to free it (with `free()`/`delete`), you will quite quickly run out of memory.
* Actually, you do not even need to do any dynamic allocation at all: automatic allocation is the safest way to handle these arrays.
* Since you know the exact size you need, allocate that rather than a default size.
* `multNums` receives as a parameter the number of multiplications, not the length of the array.
* `i+2` does not change the value of `i`. You meant `i+=2`.
* `sizeof(productArray)` does not give the length of the array, but its size in bytes. Besides, your last loop is supposed to iterate only through the initialized part of the array.

If you fix those issues, the program should work as expected.

---
Tags: arduino-uno, serial, array, loop
---


# Question
Title: Writing a float to a BLE characteristic. What data format?
I am currently working on a python-based Bluetooth Low Energy client for OS X and I got stuck while trying to write a remote float characteristic value.

First of all: my setup is an Arduino 101 with integrated BLE module and a Macbook. On the Arduino side the code is working well, I can read and write BLE characteristic's from a BLE explorer app on my phone.

Also I did achieve to read out the characteristics float values in my python script on the Macbook. Yet I did not fully understand what exactly I am doing. After requesting the characteristic's value from the peripheral, the peripheral answers and I get what I think is binary data? I could manage to unpack the data to a float by using.

```
     def characteristic_to_float(data):
        float_value = struct.unpack('f', data)[0]
        return float_value

```

The received floats are correct. But I couldn't get my python code to properly write a float value to the peripheral. I tried this:

```
    a_number = 5.3

    def float_to_characteristic(float_value):
        val = struct.pack('<f', float_value)[0]
        return val

    characteristic_1.write_value(float_to_characteristic(a_number))

```

The python code itself will run through without an error, but the Arduino doesn't receive the data. I am sure of that, because I implemented a function on it that sends out a Serial print when a characteristic has been written.

Remember the characteristics are read & write and I could verify this by using my phone. I think I got something wrong with the struct.pack thing, since I can't find any information about what data format is needed...

Does someone know how I can pack or convert the float to the right data format? Unfortunately the lib I use (Adafruit BluefruitLE) does not have a documentation.

Thanks!

# Answer
> 1 votes
I could solve the issue by taking another look in the documentation of the struct lib in python. I tested different pack and unpack methods and wondered where the \[0\] in my code came from (I did copy it from somewhere). So what I found working for my setup simply is:

```
def float_to_characteristic(float_value):
       val=struct.pack('<f',float_value)
       return val

```

When I send this packed value through BLE the Arduino will accept it.

# Answer
> 1 votes
Two solutions came to my mind if am gonna do your thing, 1) convert the number to a string char by char and send it as it is then unpack it as char by char , for example 5.3 -- \> "5.3" it will be received then you have to decompose it 5 and . and 3 (inefficient solution because of conversion of types will be alot)

2) calculate the number of decimal digits and send it with the number something like: 5.3 ---\> 53 and one decimal point, you would send it as 53:1 and then unpack it and reconstruct it

the second solution would be better for me since i have to send it as 2 things number: decimal point and then reconstruct it, this library will ease the reconstruction of decimal point sent by 53:1 (if you want to send floats in two directions) SimpleSerialExtractor

# Answer
> 0 votes
I used this way: define a BLE format descriptor (0x2904) Attach the descriptor to the characteristic

```
struct BLE2904_Data {
  uint8_t m_format;
  int8_t m_exponent;
  uint16_t m_unit;
  uint8_t m_namespace;
  uint16_t m_description;
} __attribute__((packed));

struct BLE2904_Data desc1;   // must remain valid memory for ArduinoBLE

  desc1.m_format = 0x14;  // float
  desc1.m_exponent = 0x0;
  desc1.m_unit = 0x2728;  // voltage
  desc1.m_namespace = 1;
  desc1.m_description = 0x10f;

  BLEDescriptor voltageLabelDescriptor("2904", (uint8_t*)&desc1, sizeof(desc1));
  batteryLevelCharacteristic.addDescriptor(voltageLabelDescriptor);

```

The 2904 descriptor sets the data type see here for more details:

---
Tags: bluetooth, python, data-type
---


# Question
Title: Why is my Arduino is getting power from the 5V pin?
I have an Arduino that is controlling two 6V DC motors through a L298N motor driver. The motor driver is being powered (from its Vin pin) by a 7.4V external source.

I then have the 5V pin from the motor driver connected to the 5V pin on an Arduino UNO to power the logic board.

Now, when I plugged in my Arduino to my computer to upload the sketch, everything was fine. However, when I unplugged the Arduino from the laptop, the Arduino was still being powered somehow from the 7.4V external source, though that source should only be powering the motors. I thought that unplugging the Arduino from the laptop would have cut power to the Arduino, but it was still somehow being powered by the external source.

What is going on here?

# Answer
The Arduino Uno can be powered from the 5 volts present on the USB cable or from an external 5 volts connected to the Arduino's 5V and GND (ground) pins.

In general, power supply outputs should never be connected in parallel unless they are designed for such an unusual configuration. From the description in the Question, it appears the USB power and the L289N power supplies were connected in parallel. Fortunately, the Arduino design include a power cut off shich. Look for part "T1" in this schmatic. If power is applied from both the 5V pin and the USB port, the 5V pin is used and the USB power is cut off.

To answer your question specifically:

* Assuming this is your board's schematic (note, this is a link to an RAR file which contains a JPG of what is likely the wb291111 board's schematic) and assuming you have J6 jumper installed.
* If the Arduino 5V and GND (ground) pins were connected to the L289N board and the L289N board was supplying 5V power to the Arduino board, the Arduino board was never powered from the computer's USB port as transistor "T1" would have disconnected the USB power from the Arduino.
> 0 votes

---
Tags: arduino-uno, l298n
---


# Question
Title: ESP32-CAM rst:0x8 TG1WDT_SYS_RESET bootloop
I have ESP32-CAM that I plan to use as a simple security camera. I tested the software and it was working perfectly. I programmed it using FTDI programming board with 5V. After testing everything I decided to power it with an old adapter (5V 160mA) I had for some time but when I powered with adapter the power started flickering. When I noticed it I immediately unplugged the adapter but since then I started getting stuck in bootloop. Here is the output I get:

```
12:56:10.663 -> ets Jul 29 2019 12:21:46
12:56:10.667 ->
12:56:10.667 -> rst:0x1 (POWERON_RESET),boot:0x3 (DOWNLOAD_BOOT(UART0/UART1/SDIO_REI_REO_V2))
12:56:10.667 -> waiting for download
12:56:49.327 -> ets Jul 29 2019 12:21:46
12:56:49.327 ->
12:56:49.327 -> rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
12:56:49.327 -> configsip: 0, SPIWP:0xee
12:56:49.327 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
12:56:49.327 -> mode:DIO, clock div:2
12:56:49.327 -> load:0x3fff0030,len:1344
12:56:49.327 -> load:0x40078000,len:13836
12:56:49.327 -> load:0x40080400,len:3608
12:56:49.327 -> entry 0x400805f0
12:56:50.707 -> ets Jul 29 2019 12:21:46
12:56:50.707 ->
12:56:50.707 -> rst:0x8 (TG1WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
12:56:50.707 -> configsip: 0, SPIWP:0xee
12:56:50.707 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
12:56:50.707 -> mode:DIO, clock div:2
12:56:50.707 -> load:0x3fff0030,len:1344
12:56:50.707 -> load:0x40078000,len:13836
12:56:50.707 -> load:0x40080400,len:3608
12:56:50.707 -> entry 0x400805f0
12:56:52.086 -> ets Jul 29 2019 12:21:46
12:56:52.086 ->
12:56:52.086 -> rst:0x8 (TG1WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
12:56:52.086 -> configsip: 0, SPIWP:0xee
12:56:52.086 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
12:56:52.086 -> mode:DIO, clock div:2
12:56:52.086 -> load:0x3fff0030,len:1344
12:56:52.086 -> load:0x40078000,len:13836
12:56:52.086 -> load:0x40080400,len:3608
12:56:52.086 -> entry 0x400805f0

```

It keeps going like this. I can upload new code without any problems but every code I upload gets stuck in this exact bootloop. Load and entry adresses does not change. I also tried programming with arduino nano instead of ftdi but nothing changed.

I am using Arduino IDE 2.0.0 on Linux Mint 21 OS. I also tried it on Windows 10 but the results didn't change. I am quite new to ESP32 so I don't know how to debug it either.

Thanks in advance.

##############

UPDATE 25/10/2022

After timemage's comment I tried a few more codes and one of arduino ide's example codes ran once with error. I couldn't get the error log but there was something like "PSRAM ID Read error 0xffffff" and another log pointing to a corrupted address.

After that I tried uploading another sketch without PSRAM with following settings:

* Board: ESP32 Dev Module
* CPU frequency: 240MHz(WiFi/BT)
* Events run on: Core 1
* Flash frequency: 80MHz
* Flash mode: QIO
* Flash size: 4MB(32Mb)
* Arduino runs on: Core 1
* PSRAM: Disabled
* Partition scheme: Huge APP(3MB No OTA/1MB SPIFFS)
* Upload speed: 115200

and it worked. But I need PSRAM for my project. So my question is: can it be a hardware problem ? If not, how can I fix it ?

Thanks again.

# Answer
> 1 votes
1. Is your esp32\_cam comes with PSRAM? I had a program running on esp32 wrover with PSRAM, the same code could not run on esp32 wroom. After checking, the esp32 wroom does not come with PSRAM.
2. Say that the esp32\_cam does come with PSRAM, how do you initilize it?
3. My code has ISR to force shutdown after 15min of wakeup from deep sleep, I will get the same error with reset when there is a while loop or for loop, and i missed these 2 line of codes. vTaskDelay( 3 / portTICK\_PERIOD\_MS ); esp\_task\_wdt\_reset();

hopefully, this helps.

# Answer
> 0 votes
I got the same "rst:0x8 (TG1WDT\_SYS\_RESET),boot:0x13 (SPI\_FAST\_FLASH\_BOOT)" and crash when using the M5stack-Timer-Camera after doing a "SerialM.setDebugOutput(true);" then starting the camera with "camera\_init()" and then doing an "EEPROM.commit".

When I remove the "SerialM.setDebugOutput(true);" the error/crash goes away and instead I just get a (Serial-Terminal) warning of "cam\_hal: EV-EOF-OVF" when doing an "EEPROM.commit".

So in my case I suspect that the "SerialM.setDebugOutput(true)" was causing the "cam\_hal: EV-EOF-OVF" error message to crash during the "EEPROM.commit".

# Answer
> 0 votes
From my personal experience working with the ESP-CAM's ESP32-s3 chip, the particular error is the result of an invalid line of code.

The best way to address this is to look very closely at the code that you've written, for some of the errors you may introduce through the arduino ide may not be caught in the compilation process.

For example, I was building out a UART shell using the same processor.

My code was producing the same error because of this code here:

```
private:
    size_t commandsLen = 1;
    string commands[1]{
        "lcdcam"
    };

```

I was able to fix the reset loop by correcting the syntax in my string array. Which was missing an equals sign.

The following modification fixed my particular issue, and odds are that your problem is syntax related like mine.

```
private:
    size_t commandsLen = 1;
    string commands[1] = {
        "lcdcam"
    };

```

Edit: Upon further inspection, there was an additional issue that also caused this error.

Take the following code into consideration:

```
public:
    bool commandSwitch(Uart uart, BosCommand cmd){
        if(cmd.getCommandLength() <= 0){
            sendOutput(uart, "Failed to find commands.\n\r");
            return false;
        }
        string target = cmd.getCommandArg(0);

        if(target == "lcdcam"){
            BosCommandSwitch targetCmd;
            targetCmd.init(uart, cmd);
            return targetCmd.process();
        }else{
           // removed
        }
        return false;
    }

```

The issue is that the processor doesn't like it when I declare the BosCommandSwitch class inside the if logic. Not only did fixing the string array correct the reset bug, but moving the declaration of the class object up into the private section of my class allowed all my code to run without the automated reset.

```
private:
    BosCommandSwitch targetCmd;
public:
    bool commandSwitch(Uart uart, BosCommand cmd){
        if(cmd.getCommandLength() <= 0){
            sendOutput(uart, "Failed to find commands.\n\r");
            return false;
        }
        string target = cmd.getCommandArg(0);

        if(target == "lcdcam"){
            targetCmd.init(uart, cmd);
            return targetCmd.process();
        }else{
           // removed
        }
        return false;
    }

```

I believe that the issue is related to memory allocation. Once you get deep into logic, you reduce the amount of available memory in a particular region. Though this is just speculation on my part.

# Answer
> -1 votes
I had a similar problem when running test code for a data input module based on the NodeMCU-32s board. The board would reset about once per second with that same error. That turned out to be my error. I had confused the physical pin number of the board with the GPIO number. I am assuming that trying to read GPIO pins that are not routed to the chip pins was still accessing internal registers, and was enough to initialize the watchdog timer. Since I was otherwise doing nothing to the watchdog, (like resetting it frequently,) the watchdog was properly doing its job and resetting the part. This wasn't obvious to me. In the Arduino environment, setting Tools-\>Core Debug Level to Verbose gave some clues. Turning off some of my use of GPIO inputs also got me to a point where the watchdog error stopped, and from there I was able to proceed. So long story shorter, I recommend checking your pin assignments for IO!

---
Tags: arduino-ide, esp32, bootloader, ftdi
---


# Question
Title: Program SMT32 black-pill without pushing buttons or propriatary devices
Are there any options for programming an STM32 black-pill from the Arduino IDE without first having to manually push buttons to go into DFU mode or having to buy an ST-Link device?

A solution that leverages a second micro-controller board (I have Arduino Nanos, Pi Picos and ESP32 boards available) or requires some (easy) soldering would be fine.

# Answer
> -1 votes
Your question is one I was recently interested in as I too have begun using Blue/Black Pills, and I am still learning!

1. Have you got your Arduino IDE set up, and have you added the plugin for the STM32 boards? If not then you can find a tutorial in many places on the internet, one example being on youtube, if you prefer video tutorials... https://www.youtube.com/watch?v=b1123kz\_3MM Some are better than others and I prefer a written instruction, with or without pics! Essentially you have to add:- https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package\_stm\_index.json to your list or boards in the preferences. Many Tutorials will explain in detail.
2. Programming options include:

1. STLink-v2.1 etc. The STLink-v2.1 is easy to source, cheap, and after it is eventually replaced by something else you can even repurpose it as if it is a STM32 USB stick!
    2. FTDI USB to TTL breakout adapter, 3.3v only, connected to the SWD pins on the opposite end to the USB socket.
    3. An Arduino board acting as a TTL/SWD adapter but already kind (talking) to Arduino!
    4. Burning an STM32-Arduino boot-loader onto the blue/black pill, and plug it in like an Arduino, using tutorials.
    5. Install STM32CubeProg, on your host computer, which is free and a very good IDE.
    6. NO DOUBT a search engine (of traditional values!) can find other options including JTAG, JLink, Bus-Pirate, etc. (Avoid search engines that send you straight to selling sites!)

All of these need to be searched, read and understood before a logical choice is made, but all of them are usable choices. Every reader will know that you will get user advice insisting that you do what they have done, or worse, warning you to avoid methods that others have used successfully. Caveat Emptor!

Follow the easiest path to begin with, one of those that are given in the Arduino site perhaps, and investigate others when you have found what you want the process to do, and which process suits your methods and budget. Much depends on memory needs and applications.

---
Tags: uploading, programmer, stm32
---


# Question
Title: How to get rid of low quality sound out from DFPlayer plus amplifier?
I use my Seeeduino V4, DFPlayer mini, and this speaker module from AliExpress to create an automatic doorbell. The problem is that it seems that this speaker module's Yurobot amplifier is not powerful enough to create a noise-free loud sound. Also, the bundled speaker is 0.5 W, 8 Ω.

There is a volume selector on the speaker module. If it is selected to a value a bit higher than 0 then the sound's quality is quite high (click here to listen), but the volume is not enough by far for a doorbell, even though the DFPlayer's programmed volume is set to maximum.

But if I increase the amplifier's volume selector to something near maximum, I start hearing some very scary noises (please click here to listen).

How can I increase the volume without having hard-to-listen-to noises? Maybe I need to buy another, better amplifier?

# Answer
The DFPlayer already has a 3 W amplifier on it, so you can connect a speaker directly to the DFPlayer. There is no need for an extra amplifier.

If you do connect an extra amplifier to the DPlayer, and turn the volume of the DFPlayer up too far, the input of the second amplifier will clip and it won't sound good.

Also, the output of the DFPlayer is probably from a class-D amplifier designed to be connected directly to a speaker; it won't play nice with other amplifiers.

You should try how the DFPlayer sounds when you connect a speaker directly to it. The 0.5 W speaker you have is not a good fit; it can't handle the power of the DFPlayer's amplifier.

A 3 W (or more), 8 Ω speaker would be good for this if you want to use the maximum power the DFPlayer can deliver. According to most publications on the interwebs a 2 W, 8 Ω speaker will also do, but I would be careful with turning the volume all the way up.

Note that the DFPlayer can pull a fair bit of current (about 25 mA in standby, and in the order of 200 mA when playing) and it needs a power supply that can deliver that.
> 1 votes

# Answer
Interesting! The wattage rating of the speaker does not affect its loudness, the efficiency does at a given wattage. Wattage is the maximum amount of power you can drive the speaker with, that does not indicate the source can provide more or less. The SPL (SPL stands for sound pressure level and is also commonly referred to as efficiency and sensitivity. This parameter represents how loud a speaker is. A higher SPL equates to a louder speaker). To get more volume out of a speaker you have to put more power in. Ohm's Law explained this. The impedance (AC Resistance) of the speaker varies with frequency but typically a nominal number such as 8 ohms is used. Looking at Ohm's law the only way to get more power is to lower the impedance or increase the voltage with voltage being the most popular as well as the easiest. Putting more power into a speaker then it is rated at will eventually destroy it as well as distort the sound. This may not be noticeable to the human ear at low amounts but it is there. Also the sound coming out is directly related to the signal going in. Clipping is a common occurrence when the amplifier is being over driven ie. it is asked to put out a higher voltage then it is capable of. There is an old saying garbage in garbage out. That includes the components as well. To solve your problem you probably need an amplifier capable of doing what you want and a speaker that will at a minimum handel the worse case power you will send it.
> 0 votes

# Answer
i was experiencing the same phenomen in my project , and got to this page in my research . I am using a tda 2003 amplifier and the speaker is a intercom that i modify so changing the speaker is out of question also the amplifier is a good and versatile . The problem is in the gain setting of the amplifier . I was using a 220ohm resistance on the gain setting . going back an forth i was getting better sound with low gains. i hooked up a potetiometer in the place of the resistance to fine tune the gain aand at 8 ohms i get the sound that i want.
> 0 votes

---
Tags: audio, sound, debugging, speaker
---


# Question
Title: Pro Micro Double Reset help; Not able to get upload done in 8 seconds
I have timed the double reset as best as possible multiple times but the upload doesn't happen before the board leaves bootloader mode.

this is all I'm given as an error which doesn't appear until after the board leaves bootloader mode (after the 8 seconds) The one thing that I haven't been able to find info on is the fact that I do not have a SparkFun version, I have a non branded from ebay if that makes any difference

How can I fix?

```
Sketch uses 3460 bytes (12%) of program storage space. Maximum is 28672 bytes. Global variables
 use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.

avrdude: ser_open(): can't open device "\\.\COM11": The system cannot find the file specified.

Failed uploading: uploading error: exit status 1

```

# Answer
> -1 votes
* Remove the power to the board
* **Hold down** reset while you power it up.
* Release reset when the IDE says that it is uploading.

---
Tags: bootloader, uploading, arduino-pro-micro, reset, upload
---


title: Arduino IDE Auto Format Error

text:
# Question
Title: Arduino IDE Auto Format Error
Whenever I try to format a sketch in the IDE (1.8.19) I get this output in the terminal:

```
Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: 'java.lang.String cc.arduino.packages.formatter.AStyleInterface.AStyleMain(java.lang.String, java.lang.String)'
          at cc.arduino.packages.formatter.AStyleInterface.AStyleMain(Native Method)
          at cc.arduino.packages.formatter.AStyle.run(AStyle.java:80)
          at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
          at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
          at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
          at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
          at java.base/java.security.AccessController.doPrivileged(Native Method)
          at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
          at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
          at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
          at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
          at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
          at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
          at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
          at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

```

...And formatting fails.

I can use astyle from the command line (linux mint) and it works well.

Guessing that some basic package was missing, or corrupted, I reinstalled Arduino, but the issue remained.

I don't precisely recall any specific changes made to my system prior to encountering this behavior, as it's been like this for at least 8 or 9 months now. I hadn't used Arduino for some time up until that point and it may have been a fresh instal.

Since I just started a new project for a buddy of mine and encountered the bug again I decided maybe it was time to see about a better solution.

Any help troubleshooting this would be greatly appreciated.

# Answer
I googled the first line of stack trace and found similar issue on github (but for SUSE linux). In this issue the Arduino IDE was installed by system package manager and after downloading latest package from arduino.cc/en/software it started working.

In general Arduino IDE linux packages are somehow problematic (as far as I know Ubuntu has still version around 1.0.6) and it's better to use latest version directly from arduino.cc
> 2 votes

---
Tags: ide, java
---


# Question
Title: Problem with some sensors but not with servos
I use a lot Arduino Uno, but in this case, I have some BQ ZUM BT-328 boards, which are based on Arduino BT. The problem with some of BQ ZUM BT-328 boards is that the ultrasonic sensor (HC-SR04) is not working in any pin. However, apparantely, the boards work and the 2 servos (SM-S4306R) work fine too. When I change the ultrasonic sensor to other pins and with other wires, it is not working yet. However, I use that sensor in another different BQ ZUM BT-328 board and it is working fine, and if I add the same setup (2 SM-S4306R) and same code, it continues working fine. Then, the problem is just in some boards, not in everyone.

The ultrasonic example is:

```
long distance;
long responseTime;

int pinTrig = 9;
int pinEcho = 8;

void setup(){
  Serial.begin(9600);
  pinMode(pinTrig, OUTPUT);
  pinMode(pinEcho, INPUT);
}

void loop(){
  digitalWrite(pinTrig, LOW);
  delayMicroseconds(5);

  digitalWrite(pinTrig, HIGH);
  delayMicroseconds(10);
  responseTime = pulseIn(pinEcho, HIGH);
  Serial.println("Tiempo "+ String(responseTime)+" microsegundos");

  distance = int(0.01716*responseTime);

  Serial.println("Distancia "+ String(distance)+"cm");
  delay(500);
}

```

Then, I suppose that those BQ ZUM BT-328 boards have some problem and maybe they are starting to fail. I say this, because the same problem works in some boards and in others fails. In those board in which it fails I checked the correct connection of pins (GND, VCC, digitals), change the pin and the wires without result. However, the servos continue to work fine and I can upload the code to the board. My questions are:

Am I correct and they are failing?

Why they are just failing with that sensor and not the SM-S4306R? I mean, maybe some specific component of the board is failing?

# Answer
> 0 votes
Looks like in your sample code you did not complete the 10us pulse.

```
  digitalWrite(pinTrig, LOW);
  delayMicroseconds(5);

  digitalWrite(pinTrig, HIGH);
  delayMicroseconds(10);
  digitalWrite(pinTrig, LOW); // you missed this

```

See example.

---
Tags: sensors, hardware, ultrasonics
---


# Question
Title: What are exactly XTAL1 and XTAL2 pins in Arduino Uno/Nano?
I know that the blow red encircled component is the 16MHz Crystal Oscillator (XTAL):

But PB6 and PB7 pins are called XTAL1 and XTAL2 pins which are not accessible by the Arduino board.

Are these pins where the 16MHz crystal oscillator is connected. But if so why are they two of them? I searched net but couldn't find explicit information about these.

How many clocks in total this board have?

# Answer
> 1 votes
Yes they connect to the crystal. There's two of them because a crystal has two pins.

# Answer
> 2 votes
The Crystal in Red is for the Atmega16U2 that manages the USB interface with its high speed connection to the PC (12 MHz for USB2 I think).

The Resonator in Yellow is for the Atmega328P. It is less precise than the crystal oscillator.

PB6 and PB7 are dedicated to the external crystal or resonator by the fuse settings used for Arduino.

You can read more about the XTAL1, XTAL2 pins and the fuses from the device datasheet

https://www.microchip.com/wwwproducts/en/ATMEGA328P

You can connect a crystal to the pins, but you will also need 22pF caps to connect from the pins to Gnd. And remove the resonator. Current Uno layout does not really support making those connections.

# Answer
> 2 votes
XTAL1 is the input and XTAL2 is the output of the oscillator. Using 8MHz internal RC oscillator instead of the crystal, you can use PB6 and PB7 as I/O, like other I/Os.

---
Tags: arduino-uno, oscillator-clock
---


# Question
Title: digitalRead not reading input pin of ESP8266-01
I am trying to use a on-off switch with the ESP8266 to change whether GPI02 is HIGH or LOW. I am using GPIO3 as input. My circuit looks like this:

The red area to the right is a relay, I wasn't sure how to make it work in fritzing but I am sure that it is wired correctly, it just has a signal, +, and -, pin. The more important stuff is happening with the ESP8266. First, here is the code:

```
/*
  This a simple example of the aREST Library for the ESP8266 WiFi chip.
  This example illustrate the cloud part of aREST that makes the board accessible from anywhere
  See the README file for more details.

  Written in 2015 by Marco Schwartz under a GPL license.
*/

// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>

// Clients
WiFiClient espClient;
PubSubClient client(espClient);

// Create aREST instance
aREST rest = aREST(client);

// Unique ID to identify the device for cloud.arest.io
char* device_id = "ew1zard";

// WiFi parameters
const char* ssid = "MaisonBlanche";
const char* password = "7932gLBw";

// Functions
void callback(char* topic, byte* payload, unsigned int length);

void setup(void)
{
  // Set input / output pin
  pinMode(3, INPUT);
  pinMode(2, OUTPUT);
  //pinMode(2, OUTPUT);
  //digitalWrite(3, 0);

  // Start Serial
  Serial.begin(115200);

  // Set callback
  client.setCallback(callback);

  // Give name & ID to the device (ID should be 6 characters long)
  rest.set_id(device_id);
  rest.set_name("esp8266");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Set output topic
  char* out_topic = rest.get_topic();
}

void loop() {

  // Connect to the cloud
  rest.handle(client);

  int read3 = digitalRead(3);
  Serial.println(read3 + " input");
  digitalWrite(2, read3);

}

// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {

  Serial.println("request from interwebs");
  rest.handle_callback(client, topic, payload, length);

}

```

The output of the `Serial.println` is always `input` (there is no HIGH or LOW or 1 or 0, or whatever it should be, before the input. I have verified that the switch is working. In the `on` position it is sending `3.3v` to GPIO3 (I have measured it with my multimeter) and still the input never changes. In the `off` position it sends 0v and the ESP8266 just acts as if there is nothing to read it seems. Since I am using this with `aREST` and you can set the mode of pins through that, I thought maybe I had to set the `pinMode` with the `aREST` request `cloud.arest.io/xxxxx/mode/3/i` and it verifies with a JSON response that the pin is being set to input, but still no reading. Do I not have the ESP8266 wired correctly for this? Maybe I need some pull-ups/pull downs or I can't use the pins in the configuration I am using them? One other thing, when I set the input pin with aREST, it turns on the relay (sending something through GPIO2 for some reason). If I don't set the input with `aREST` the relay stays off.

**UPDATE** I tried with this code to rule out that it might be `aREST`:

```
void setup() {
  // put your setup code here, to run once:
  pinMode(3, INPUT);
  pinMode(2, OUTPUT);

  // Start Serial
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  int read3 = digitalRead(3);
  Serial.print(read3);
  Serial.println(" input");
  digitalWrite(2, read3);
}

```

It always outputs `0 input`, the ESP8266 seems to be ignoring that input pin.

**UPDATE** I am now trying with GPIO0 as input. I have the switch wired to ground, and it leads to GPIO0. When I turn it on, GPIO0 reads `1` (on), then I use the switch and it turns the relay off correctly, then I try and turn it on again, and nothing happens, GPIO0 continues to be read at `0`. So I can't use the switch past the initial `off`.

# Answer
> 3 votes
The expression `read3 + " input"` performs pointer arithmetic, i.e. you either add 0 or 1 to the start adress of `" input"`, so you get either `" input"` or `"input"`. Does the leading space disappear when pressing the button?

To correct your code you can print the number separately:

```
Serial.print(read3);
Serial.println(" input");

```

You should get rid of the rest and pub-sub code. You can add this later after having solved the problem with the button.

Also note that GPIO03 uses the same pin as RX. The docs state the following:

```
Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX).

```

So it should work after disabling Serial and after providing a pull down resistor. The resistor is needed to prevent having a floating input.

# Answer
> 0 votes
The issue occurs when you try to use the RX port (3) and you also define Serial.begin. This is double dipping. You can only use the RX/TX as a single unit of digital or serial communication.

# Answer
> -1 votes
There are certain pins that output a 3.3V signal when the ESP8266 boots. This may be problematic if you have relays or other peripherals connected to those GPIOs. The following GPIOs output a HIGH signal on boot: GPIO1, GPIO3, GPIO9, GPIO10. GPIO3: pin must high at BOOT and is pulled up to that position. I have no idea what will happen if low at that point. Since I2C I/O modules are cheep I use them and do not worry about the rest of the pins. Not the cheapest but keeps me out of trouble. It makes my life a bit easier as well as I pull up the I2C lines to the 3.3V and connect the PCF8574 to 5 Volts. No problem as the SCL and SCI are by definition Open Drain or Open Collector (Bipolar parts). This made my first try with a LCSD work first shot. I tried the 3.3V and it would not work.

---
Tags: arduino-uno, esp8266, pins, switch, pull-up
---


# Question
Title: SIM7600 MQTT CONNECTION TO shiftr.io broker
I am trying to use SIM7600 MQTT command to publish and subscribe to shiftr.io broker.

I have not been able to get pass stage of connecting to broker.

I use this AT+CMQTTCONNECT=0,"tcp://instance.cloud.io:1883",90,1,"username","token"

I get this error code. +CMQTTCONNECT: 0, 25

Of which code 25 indicate DNS error

# Answer
You answered your own question with "DNS error".

The domain name that you're using, `instance.cloud.io`, is currently not valid. You can verify this quite simply by searching the web for any web site that looks up domain names for you and searching for that domain name.

In this case, "instance" is most likely a placeholder for the correct name. You need to go back to whatever tutorial or instructions you were following for this and use the correct name for this to work.
> 0 votes

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