title: DHT11 is returning nonsensical values

text:
# Question
Title: DHT11 is returning nonsensical values
I am trying to get humidity and temperature readings (eventually to trigger a misting system), but the values keep returning as 0C and 0%humidity (in general). Originally, I was using an am2320 sensor and using the analog pins. Here, I used the following code:

```
#include "dht.h"
#define dht_apin A2 // Analog Pin sensor is connected to
#define MIST 7
#define LIGHT 2

dht DHT;

void setup(){
 pinMode(MIST, OUTPUT);
 pinMode(LIGHT, OUTPUT);
  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(1000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    DHT.read11(dht_apin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");

    delay(5000);     //Wait 5 seconds before accessing sensor again.

  }

  //Fastest should be once every two seconds.

// end loop()
}

```

Thinking the sensor may have not been working, I tried using a different sensor (DHT11), and following the tutorials got the same result using this code:

```
#include <dht11.h>
#define DHT11PIN 4

dht11 DHT11;

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

}

void loop()
{
  Serial.println();

  int chk = DHT11.read(DHT11PIN);

  Serial.print("Humidity (%): ");
  Serial.println((float)DHT11.humidity, 2);

  Serial.print("Temperature (C): ");
  Serial.println((float)DHT11.temperature, 2);

  delay(2000);

}
// end loop()

```

The Arduino is being powered by a wall wart and is also connected to my computer via USB (I read that sometimes the USB doesn't supply enough power). The weird part is that for about 1 minute I got reasonable results (humidity ~50%, temp 22C). Then, I tried adding an if loop to turn on an LED if the humidity dropped below 60% (thinking I could use the same code to operate a relay to turn on a misting system). The LED lit up, but the readout went back to the 0%humidity and 0C. I have since deleted this loop but cannot seem to get reasonable measurements. If I change the signal pin, I sometimes get a new readout 255% humidity and 255C, but I haven't been able to repeat this reliably.

For the wiring: S to pin, + to 5V, - to GND

Note: I have tried every analog pin and "regular" pin, so the code may designate something that is different in my picture. When testing, I have triple checked that the signal pin in the code is correct for my wiring configuration. I've also tried with a different Arduino with the same result. I'm pretty new at this, but the code is pretty much copy-paste and there are only 3 wires. I've read that there are many DHT libraries, so I'm thinking my issue has something to do with that, but I have no clue how to judge the appropriateness of a library for my application.

\[\[\[\[\[\[\[\[\[\[\[\[p

# Answer
You need to add the following line of code in the setup() function:

```
    dht.begin();

```
> 1 votes

# Answer
Connect the sensor as in this diagramm (including a 10k resistor!):
Watch the empty connector opposite to your breadboard plug-in and use the following test sketch with this library:

```
// Example testing sketch for DHT humidity/temperature sensor

#include "DHT.h"

#define DHTPIN 4     // Digital pin connected to the DHT sensor

#define DHTTYPE DHT11   // DHT 11

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println(F("DHTxx test!"));

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));
}

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: activate a relay with two esp8266 -12e pins
I have an esp8266-12e that I want to activate the reset side of a latching relay. The problem is that the 12e only puts out 12mA/pin and the relay needs more than that. I am using a transistor on the set side from a rf antenna signal. I only have one 3.3v power source. Is there a way to have two pins go HIGH at the exact same time and be connected to the reset side of the relay so there is enough current? Would this work, would it hurt anything, and how would I write the code for it and how would I wire it up?

I have tried the code where one pin is written HIGH right after the other like this

```
digitalWrite (5,HIGH);
digital Write (6,HIGH);

```

but I think pin 5 goes of before pin 6. Any way to get them to go off at the same time?

Thanks for the help

# Answer
That is not a good idea.

Isolating the relay from the IO pin is not just about the current limit of an IO pin, it's also about preventing back-EMF spikes from the relay coil(s) from damaging the delicate internals of the chip.

Instead you *must* at least use a transistor and a back-EMF protecting diode.

However - if you *did* want to theoretically have two pins *safely* controlled to provide double the current (though I stress again, do *not* do this for driving a relay), it is possible.

But it's not straight forward.

It's not possible on the ESP8266 to use port manipulation to make two pins change state at the same time. However it is possible to go *via a third state* that makes it safe.

**Note: this will only be "safe" for IO pins that do not do strange things at bootup, and many of the pins on the ESP8266 do strange things.**

IO pins actually have three states, not two:

* High
* Low
* High Impedance

The latter is the state the pin is in when in INPUT mode. And we can use that to our advantage.

When in High Impedance mode it's like the pin is disconnected. So we could:

1. Make sure both pins are in INPUT mode
2. Switch one pin to OUTPUT and set it to the desired state
3. Switch it back to INPUT mode (keeping the desired state latched)
4. Switch the other pin to OUTPUT and set it to the desired state
5. Set the first pin back to OUTPUT mode again.

This can be slightly compressed as we don't really need to set both pins to INPUT at the start, only one. So here's some code that might do it:

```
void digitalDoubleWrite(int pina, int pinb, bool level) {
    pinMode(pina, INPUT);
    pinMode(pinb, OUTPUT);
    digitalWrite(pinb, level);
    pinMode(pinb, INPUT);
    pinMode(pina, OUTPUT);
    digitalWrite(pina, level);
    pinMode(pinb, OUTPUT);
}

```

You might ask why we'd want to switch to OUTPUT just to latch a level into the pin. Well, that's because of a quirk of the Arduino API. A historical artefact that is lingering in there to this day:

* `digitalWrite()` on a pin set to INPUT mode was used to turn the internal pullup resistor on and off

It's actually how the AVR's IO ports control the pullup resistors internally, and that has most often been copied in software for other chips to maintain backward compatibility with old code. So as a result we have to switch to OUTPUT mode so that the API code knows that we mean to set the output latch state and not the pullup resistor state.
> 0 votes

---
Tags: esp8266, arduino-ide, relay
---


title: Relay doing opposite to digital pin

text:
# Question
Title: Relay doing opposite to digital pin
I have a Arduino UNO with a Ethernet shield which hosts a basic HTML page with a button on it which controls a Relay module.

I'm trying to connect to a computer's power button so I can turn it on remotely.

I have found out that the relay basically does the opposite to the digital pin's output

Normally open Relay
HIGH = Open
LOW = Closed

I connected it through a NOT Gate made using a NPN transistor and it works perfectly how I wanted it.

Now to the question... Is there a way to write the code to make the digital pin = HIGH straight away and fast enough to not allow the relay to close the circuit and accidentally turn the computer on/off when the Arduino restarts, so I don't have to use a NOT Gate.

# Answer
I've solved the problem, Thanks to everyone who helped.
I don't need a NOT gate anymore, here's what I added to make it work:

void setup() {
startup();
}

void startup() {
digitalWrite(relay1, HIGH);
digitalWrite(relay2, HIGH);
}

void loop() {

}

(I removed the rest of the code to keep it simple and easy to understand)
> 0 votes

# Answer
The relay module you have is this one from SainSmart:

The schematic is like this:

As you can see you connect VCC to +5V and IN2 to your IO pin. Setting the IO to LOW will then turn on the LED and the optocoupler together.

But that's not the only way you can connect it up.

Connect VCC to the IO pin and IN2 to GND instead. Then you set your output HIGH to turn it on.

The arrangement shown in the schematic is commonly done because some MCUs are able to sink more current than they can source thorugh an IO pin. That is not the case with an Arduino which has symmetric IO pins that can sink and source the same amount of current.
> 1 votes

# Answer
You could use a less invasive way to turn on your computer: wake on LAN. In this case you only need to generate the magic packet.

It won't work in forcibly turning off the PC, but it's more generic and doesn't require HW hacking.
> 0 votes

# Answer
To ensure that relay doesn't switch between NO-NC when controller is *away* relay will need some memory.

Imagine having a 1 bit memory driving relay. If arduino dies/restart, its own GPIO may change, but relay's memory will remember last state and stay there, till controller instructs otherwise, granted relay circuit and its memory element don't lose power.

This also means there will be at least 2 lines required from uC to control this relay now.

I'd prefer to use some kind of serial shift register, e.g. CD4094, CD4042, CD4099 etc because that allows me to control more than one relays from same 2 lines on uC.

You may find some other part more suitable for your application.
> 0 votes

# Answer
Try This:

```
const On  = LOW;    // For non inverted logic swap on and off.
const Off = HIGH;
const pump = 5;

void setup() {
  pinMode(pump, OUTPUT);    // sets the digital pin 13 as output
}

digitalWrite(pump, On);
digitalWrite(pump, Off);

```
> 0 votes

---
Tags: arduino-uno, ethernet, relay
---


title: Garbled serial on custom arduino UNO

text:
# Question
Title: Garbled serial on custom arduino UNO
I built my own Arduino UNO for a project at school. I think I have got the USB bootloader and Windows drivers all situated as the UNO shows up as an UNO in the device manager. When I try to load a sketch I get the error: avrdude: stk500\_getsync(): not in sync: resp=0x10. (previously I received the same message with the message ending with resp=0x00)

I loaded a serial echo program using the ICSP and sent the message "serial test" to the UNO. I received this message back: {u{m}o¿wu{w

Can anyone help me troubleshoot this problem as I have ran out of things to test or look into.

Thanks in advance.

Edit: Added requested pictures of TX and RX. These were taken at Pin 0 and 1 of the headers. The scope showed the same results at the pins of the 328P but I couldn't operate the scope and hold the probe at the same time.

# Answer
> 3 votes
Sorry for the delay. I posted this question on the EE board as suggested and forgot to come back here and close this out. It was an issue with the fuses. My initial attempt to setup the 16u2 missed the step where I was supposed to change the fuses. I thought this was accomplished when loading the firmware, but was mistaken.

# Answer
> 0 votes
From the scope picture it appears you have a ground problem. All the grounds must be connected together even the scope. It appears like you have a pseudo phantom ground via the mains power system. Did you set the baud in the uno with Serial.begin(your baud rate);? The baud must be the same on both ends. For a check you should get a UNO and see if it works with that the problem is your board. Also be sure Tx on the UNO goes to RX on the receiving end and visa versa.

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


# Question
Title: Swap two arrays (using pointers, not copy)
I've got two arrays, defined as:

```
uint8_t array1[10];
uint8_t array2[10];

```

I'd like to swap the arrays (actually the pointers to each array) using code like this:

```
uint8_t *tmp = array1;
array1 = array2;
array2 = tmp;

```

However, I keep getting errors like:

```
invalid array assignment

```

for the last two lines. I don't recall this being such a problem in traditional C++. I've tried all sorts of casting to no avail. Is there something I'm missing?

I can get the code to run properly if I switch the declarations for the arrays to use `new` and have them just be more-or-less pointers rather than arrays, but I'd rather not have to do that:

```
uint8_t *array1 = new uint8_t[10];
uint8_t *array2 = new uint8_t[10];

```

Code is running on an ARM-based SAMD51 (Cortex M4 processor).

Thanks for any tips!

# Answer
Figured it out. Though using `new` works, I wanted to keep the buffers out of the heap. The following declarations work with the swap code:

```
uint8_t a1[10];
uint8_t a2[10];
uint8_t *array1 = a1;
uint8_t *array2 = a2;

uint8_t *tmp = array1;
array1 = array2;
array2 = tmp;

```
> 2 votes

---
Tags: array, pointer
---


# Question
Title: With the press of a button, I need to play an intro sound file, then one of 50 other sounds in order, each time a button is pressed
I need to play an intro file and one of 50 different files after it in order each time the switch is pressed, with a short delay between the intro and next file.

For example let's say the intro is called "intro.wav," and each of the 50 other sound files are just named 01.wav-50.wav.

The logic would be:

```
TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 01.wav
END

```

```
TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 02.wav
END

```

```
TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 03.wav
END

```

and so on, until all 50 files are played, then start over.

The messages are going to be a curated group of words. I'm not sure what the intro will be yet, but it will just be something like:

intro.wav = "The word of the day is"

01.wav = "help"

02.wav = "climb"

03.wav = "think"

I'm looking for some guidance on where to start with this, if an Arduino product would be suitable, and if so, which one. I've worked with the Adafruit Audio FX Sound Board before, and that can *almost* do what I need it to do, but not by itself. It looks like I'll need an Arduino of some kind to accomplish this, so I went ahead ordered an Uno.

I'm not married to the idea of having the intro and word files separate either. If I need to create all 50 files to contain the intro and the word, that would be fine, as long as each one is triggered sequentially.

In that scenario, 01.wav could be "The word of the day is ... help" and the button would basically be the "next track" command. I don't really have a problem with doing that because I'm all about keeping things simple and I don't think I'd run out of space, but I think it would be less time consuming to just dump all the individual word files onto the card.

The important thing is that the track(s) would play once, then stop, and when the button is pressed again, the next one plays.

# Answer
> 1 votes
You will find all the code and thelibrary you need on the Adafruit learn center.
For such a project I would use a DF-robot (clone) MP3 player (~4$), an Uno, a speaker and an SD card. The library for the player includes examples to get you started and the sound project you plan is possible even with low programming skills. Look at the example codes provided and start to program.

---
Tags: arduino-uno, adafruit, audio, sound
---


# Question
Title: Need help with using pulseInLong to time a sensor
I have a setup consisting of a magnet suspended above a sensor coil. It acts as a pendulum and creates a ~ 4 mV signal when it swings over the coil - this goes through two stages of an LM358 to generate a 5V signal. The signal is very messy with lots of 'ringing' This signal is fed into pin A0 of an Arduino Uno. I used MegunoLink.h and Filter.h which is an exponential filter library then applied constrain and map, finally converting to a clean 0 - 400 (units?) square wave of about 1 second with a varying duty cycle. This is the information I want as it tells me that the magnet is homing in on the sensor (the duty cycle increases as it gets close). But when I apply pulseInLong I only get a string of zeros on the serial monitor. What am I doing wrong? Here is the sketch:

```
//  Coding by Jeremy 130520
//  further development for ricochet module
//https://www.megunolink.com/documentation/arduino-libraries/exponential-filter/
//https://www.google.com/search?q=how+to+use+arduino+pulsein

#include "MegunoLink.h"
#include "Filter.h"
// Create a new exponential filter with a weight of 5 and an initial value of 0.
ExponentialFilter<long> ADCFilter(5, 0);

int coilPin = 8;
int analogIn = A0;
unsigned long pulseLength;
unsigned long signal_1;

void setup()
{
  pinMode(coilPin, OUTPUT);
  pinMode(analogIn,INPUT);
  Serial.begin(9600);
  }

void loop()
{
 int RawValue = analogRead(analogIn);
  ADCFilter.Filter(RawValue);
 signal_1 =(ADCFilter.Current());
 signal_1 = constrain(signal_1,80, 200);
 signal_1 = map(signal_1, 80, 200,0,400);
 if (signal_1 >= 200) {signal_1 = 400; digitalWrite(coilPin, HIGH);}
 if (signal_1 < 200) {signal_1 = 0; digitalWrite(coilPin, LOW);}

 Serial.println(signal_1); //using the plotter

//pulseLength = pulseInLong(coilPin, HIGH);
 //Serial.println(pulseLength);
 delay(10);
}

```

# Answer
> 0 votes
You cannot use `pulseInLong()` because it is a *blocking function*. It waits until the input rises, then waits until it falls again, and only then it returns a value. While it's waiting, the rest of the program cannot run. This means you will not be able to actually generate the signal you are trying to time.

The easiest solution is to time things yourself with `micros()`. You have to implement an *edge detector*, i.e. some logic that remembers the previous state of the signal and notices when it changes:

```
static bool is_high;  // is the input currently HIGH?
static uint32_t time_of_rise;  // when did it rise?

if (!is_high && signal_1 >= 200) {  // rising edge
    time_of_rise = micros();
    is_high = true;
} else if (is_high && signal_1 < 200) {  // falling edge
    uint32_t pulse_width = micros() - time_of_rise;
    is_high = false;
    Serial.println(pulse_width);
}

```

---
Tags: sensors
---


# Question
Title: Is it possible to count rising edges of a 4 MHz clock on an Arduino Due and trigger an interrupt like all 4'000'000 edges?
I am struggling with my Arduino Due and the Timer Counter functionallity. The following is what I am trying to achieve:

I want to execute a function to a specific point of time or more precisley after a specific amount of rising edges given by an external clock signal with a frequency of approx. 4 MHz. Thus I read the Atmel Datasheet, Section 36, Timer Counter. My approach was to trigger an interrupt every rising edge and increment a counter variable until I reached the desired amount of rising edges and call my function then. I can confirm that I am in fact counting rising edges with my current approach but I am reading way too slow. Is there any kind of register or hardware counter which automates the counting process. Like I set the register to a specific value and wait for an overflow, execute my function and reset the register? From my web research I found that this is possible on the Uno and Mega but I could not find anything for the Due and to be honest I am a bit overwhelmed by the Atmel Datasheet. Why not just use an Arduino Due or Mega then? I need the 3.3 Volts of the Due and from what I found the Uno and Mega are 5 V devices.

This is my code:

```

// define capture channels
#define CAPTURE_TC TC0
#define CAPTURE_CHANNEL 0
#define CAPTURE_IRQn TC0_IRQn
#define CAPTURE_Handler TC0_Handler
#define CAPTURE_ID ID_TC0
#define CAPTURE_PIN 2
#define CAPTURE_CLOCK_SELECTION TC_CMR_TCCLKS_TIMER_CLOCK3

// clock divisors corresponding to CAPTURE_CLOCK_SELECTION
static const uint32_t divisors[5] = { 2, 8, 32, 128, 0};

volatile uint32_t captured_pulses = 0;
volatile uint32_t captured_ra = 0;
volatile uint32_t captured_rb = 0;
volatile float frequency, duty_cycle, active_time;

/*
* Function:  setup
* ------------------------------------------------------------------------------
* Setup code. Will be executed once.
*/
void setup() {

  // init serial connection
  Serial.begin(115200);
  Serial.print("Initializing...");

  // configure the PIO pin as peripheral
  const PinDescription *config = &g_APinDescription[CAPTURE_PIN];
  PIO_Configure(config->pPort, config->ulPinType, config->ulPin, config->ulPinConfiguration);

  // enable timer peripheral clock
  pmc_enable_periph_clk(CAPTURE_ID);

  // configure the timer
  TC_Configure(CAPTURE_TC, CAPTURE_CHANNEL,
    CAPTURE_CLOCK_SELECTION   // Clock Selection
    | TC_CMR_LDRA_RISING      // RA Loading: rising edge of TIOA
    | TC_CMR_LDRB_FALLING     // RB Loading: falling edge of TIOA
    | TC_CMR_ABETRG           // External Trigger: TIOA
    | TC_CMR_ETRGEDG_FALLING  // External Trigger Edge: Falling edge
 );

  // configure TC interrupts
  NVIC_DisableIRQ(CAPTURE_IRQn);
  NVIC_ClearPendingIRQ(CAPTURE_IRQn);
  NVIC_SetPriority(CAPTURE_IRQn, 0);
  NVIC_EnableIRQ(CAPTURE_IRQn);

  // enable interrupts
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_IER = TC_IER_LDRBS;

  // start timer counter
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_CCR = TC_CCR_CLKEN | TC_CCR_SWTRG;

  Serial.println("ready!");

} // setup

/*
* Function:  loop
* ------------------------------------------------------------------------------
* Loop code. Will be executed repeatedly after setup completed.
*/
void loop() {

 // Serial.print("Captured rising edges: "); Serial.println(captured_ra);
} // loop

/*
* Function:  CAPTURE_Handler
* ------------------------------------------------------------------------------
*
*/
void CAPTURE_Handler() {
 if ((TC_GetStatus(CAPTURE_TC, CAPTURE_CHANNEL) & TC_SR_LDRBS) == TC_SR_LDRBS) {
   captured_pulses++;
   // captured_ra = CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RA;
   // captured_rb = CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RB;

   if (captured_pulses == 4164303) {
    captured_pulses = 0;
    // specific_function_call();
   }
 }
} // CAPTURE_Handler

```

Thanks for your time, any help is grealty appreciated.

# Answer
First of all excuse my inactivity but as you know it's crazy times right now. However I finally figured it out, it's for sure not the most elegant solution but it meets my requirements. Thanks for your help @KamilCuk.

Here is my code if anyone may ever have the same problem as I did. External signal goes on Digital Pin 2. Works fine with a 4.2 MHz external clock.

```

// define capture channels
#define CAPTURE_TC TC0
#define CAPTURE_CHANNEL 0
#define CAPTURE_IRQn TC0_IRQn
#define CAPTURE_Handler TC0_Handler
#define CAPTURE_ID ID_TC0
#define CAPTURE_PIN 2
#define CAPTURE_CLOCK_SELECTION TC_CMR_TCCLKS_TIMER_CLOCK3

/*
* Function:  setup
* ------------------------------------------------------------------------------
* Setup code. Will be executed once.
*/
void setup() {

  // init serial connection
  Serial.begin(115200);
  Serial.print("Initializing...");

  // configure the PIO pin as peripheral
  const PinDescription *config = &g_APinDescription[CAPTURE_PIN];
  PIO_Configure(config->pPort, config->ulPinType, config->ulPin, config->ulPinConfiguration);

  // enable timer peripheral clock
  pmc_enable_periph_clk(CAPTURE_ID);

  // configure the timer
  TC_Configure(CAPTURE_TC, CAPTURE_CHANNEL,
    CAPTURE_CLOCK_SELECTION   // Clock Selection
    | TC_CMR_LDRA_RISING      // RA Loading: rising edge of TIOA
    | TC_CMR_ABETRG           // External Trigger: TIOA
    | TC_CMR_CPCTRG           // RC Compare
  );

  // configure TC interrupts
  NVIC_DisableIRQ(CAPTURE_IRQn);
  NVIC_ClearPendingIRQ(CAPTURE_IRQn);
  NVIC_SetPriority(CAPTURE_IRQn, 0);

  // enable interrupts and start counter
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_IER = TC_IER_CPCS;                  // enable RC Compare Interrupt
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_CCR = TC_CCR_CLKEN | TC_CCR_SWTRG;  // the datasheet said I need this
  NVIC_EnableIRQ(CAPTURE_IRQn);                                                  // enable interrupts

  // set the trigger value for RC_Compare
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RC = 4164303;

  Serial.println("ready!");

} // setup

/*
* Function:  loop
* ------------------------------------------------------------------------------
* Main code. Will be executed repeatedly.
*/
void loop() {

} // loop

/*
* Function:  CAPTURE_Handler respectively TC0_Handler
* ------------------------------------------------------------------------------
* Timer capture trigger. Will be executed if TC0_RA == TC0_RC
*/
void CAPTURE_Handler() {
  // reset status register
  TC_GetStatus(CAPTURE_TC, CAPTURE_CHANNEL);

  // do something
  Serial.println("Trigger");
  // function_call()
}

```
> 2 votes

---
Tags: c++, c, arduino-due
---


# Question
Title: How to power 6 servo motors using battery to create a robotic arm?
I am trying to create a robotic arm. The problem is that I could not run all 6 servo motors -3 MG966r servo motors and 3 MG90S servo motors - simultaneously, using 12V and 3A AC to DC adaptor. Last time I tried, My arduino uno is totally broken. If you can, Could you provide the schematics for the circuit? or Is there any methods to solve this problem?. Also Is it a better idea to use servo motor shield?

# Answer
For this task you should use an extra power supply not running trough the Arduino. For this kind of setup I use PCA9865 16-channel servo dirver board cost around 5$, needs two pins only and can run all servos (strong 5V power supply provided =\> Amperage) simultaniously. For a max of 8 servos a 5V/2-2.5A power supply (wall wart) should be sufficient.
See this example circuit for how to connect:

The PCA9865 library has examples how to drive servos via program. As this board is an I/O board you could also attach joystick(s) or buttons to it to save pins on your board.
> 1 votes

---
Tags: arduino-uno, power, motor, servo, voltage
---


# Question
Title: How do I set a variable so that after a condition is met the loop ignores input?
I have a analog inputs to my Uno that I am cleaning up and using to keep a digital pin high until the output drops to zero. At this point I want to stop reading that input because it may come back up after being low for a short time. Is there any way to set a variable that can be triggered by that first zero that prevents the loop from sending the digital pin high from then on? Like a latch of some sort, or could I use an interrupt somehow?

# Answer
You've already described what you need to do. Just set a boolean variable. It really couldn't be easier.

```
boolean runThisPart = true;

void loop() {

  if(runThisPart) {
     // this part only runs if runThisPart is true
     //  if something happens and you don't want
     //  to run this part anymore then
     if(some-condition){
        runThisPart = false;
     }
  }
  //  The rest of your code can also set runThisPart
  //  to true or false to turn that section on or off.
}

```
> 0 votes

---
Tags: timing
---


# Question
Title: How can I use my Arduino sketches on my Raspberry Pi IDE?
I have installed the Arduino IDE 2:1.0.5 on my Raspberry Pi3 under Raspbian and am using a cobbler breakout which provides a nice breadboard. On that breadboard I have installed an Arduino Nano to do analog voltage readings, which it then communicates back to the Rpi3 via the USB serial port which shows up as /dev/ttyUSB0 on the Rpi3.

This port opens as a regular file in Python for further processing such as adding a date & time stamp (obtained by an NTP server) and saving the results to a data file that is displayed in gnuplot 4.6.

*You'll notice I am using 3.3 Volts for the fan to keep it quiet, and the two wires heading up to the top go to the voltage source I am monitoring. If you look closely you can see the voltage divider circuit.*

Here is today's solar plant voltages which this thing tracks. The block at the bottom means the inverter was on. Green means the battery bank is full.

**Anyway, it turns out that the same serial connection is supported by the Rpi Arduino IDE for programming.**

Rather than programming the Nano on a laptop and constantly having to unplug/replug it on the breadboard my goal is to use Rpi Arduino IDE for programming.

So I moved all my sketches over from the Arduino IDE on the laptop to the Rpi.

## But

.... then every time I start the Rpi IDE it throws error messages for all the sketches that have underscores in their names. Turns out the Rpi version will only allow alphanumeric directory names. I have a couple dozen sketches and this is not productive. It requires clicking OK for every directory it skips - which turns out to be all of them.

So my question is: What can I do about this?

# Answer
To fix this problem I came up with the following procedure which takes out all the underscores from the directories & filenames and capitalizes each word instead.

First, I copied all my sketches and libraries (from my documents/arduino directory) to a USB flash drive.

The Rpi Arduino IDE creates a sketchbook directory upon install, so I

Copied the libraries folder to ~/sketchbook/libraries

Copied the sketches folder to ~/sketchbook/AMSsketches

Then I wrote a custom script that is copied to my home directory on the Rpi, which can be obtained here as a text file (use Chromium or wget to copy it to the file ~/AMS2Rpi) - Here is the link: http://calttc.net/AMS2Rpi

which contains this code:

```
#! /bin/bash
#
#  AMS2Rpi - Converts MS Arduino IDE Sketch names to RPI Arduino IDE Sketch names
#
#                  SDsolar      2017-01-29
#
#  Reason:    Arduino IDE on MS inserts underscore characters in file & directory names
#             Arduino IDE on Rpi rejects all but alphanumeric characters
#
#  Solution:  Remove all but alphanumeric characters
#             and capitalize each word in the names
#
#  Usage:
#    Install Raspbian Arduino IDE 2:1.0.5 on the Raspberry Pi 3
#    Use a USB flash drive to copy sketches and libraries from the MS-based Arduino IDE
#      On the Rpi, copy the libraries directory to ~/sketchbook/libraries
#      On the Rpi, copy the sketches directory to ~sketchbook/AMSsketches
#    Copy this script to your home directory as AMS2Rpi using Chromium
#    cd
#    chmod +x AMS2Rpi
#    ./AMS2Rpi    (This will take some time)
#    cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMSRpiQ
#    chmod +x ~/AMS2RpiQ
#    ~/AMS2RpiQ
#    Open the Rpi Arduino IDE
#
#  Alternatively, if you have a lot of sketches you might want to
#    change the "mv -i" below to "mv"
#    and cat it into AM2SRpiX above
#    so you don't need to answer "y" for every rename.
#
#  Props to Marco Fioretti for his article at http://www.techrepublic.com/blog/linux-and-open-source/how-to-remove-weird-characters-from-file-and-directory-names-automatically/
# ---------------------------------------------------------------------
rm -f /tmp/AMS2R*
cd $1
find .  | awk '{ print length(), $0 | "sort -n -r" }' | \
        grep -v '^1 \.$' | cut -d/ -f2- > /tmp/AMS2Rpi_1
touch /tmp/AMS2Rpi_2
while read line
  do
  BASE=`basename "$line"`
  NEWBASE=`basename "$line" | perl -e '$N = <>; chomp ($N); $N =~ s/[^a-zA-Z0-9.]//g; $N =~ s/_+/_/g; $N= lc($N); $N =~ s/_([a-z])/_.uc($1)/eg; print ucfirst($N);' `
  if [ "$BASE" != "$NEWBASE" ]
  then
  OLDPATH=$(echo "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
  DIR=$(dirname "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
  echo "mv -i $OLDPATH $DIR/$NEWBASE" >> /tmp/AMS2Rpi_2
  fi
done </tmp/AMS2Rpi_1
rm -f /tmp/AMS2Rpi_1
mv /tmp/AMS2Rpi_2 /tmp/AMS2Rpi
exit

```

Then set it to executable and run it:

```
cd
chmod +x AMS2Rpi
./AMS2Rpi

```

When it is finished, I filter out just the directory I want (VERY IMPORTANT):

```
cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMS2RpiQ

```

(You can look at that file to verify it before running it)

```
chmod +x ~/AMS2RpiQ
~/AMS2RpiQ

```

Cleanup if you wish:

```
rm /tmp/AMS2R*
rm ~/AMS2RpiQ

```

Now the Arduino IDE on the Rpi opens cleanly and all my sketches are there.

Problem solved. It works great.
> 2 votes

# Answer
Turns out there are two easier answers if you are willing to do it manually.

You can use the Windows-based IDE to load each sketch then save them with an allowable name, before transferring them.

So, instead of going through the program, just do it by hand - this is best if you don't have too many, or if you are very patient.

Or jump in with both feet: use your USB flash drive to just move your libraries and sketches to the appropriate directories under sketchbook.

```
libraries go to ~/sketchbook/libraries
sketches go to ~/sketchbook/sketches
Go into the IDE preferences and tell it to look into ~/sketchbook/sketches

```

Manually rename any directories in both directories so they only have alphanumeric characters in the subdirectory names

The Rpi version of the Arduino IDE has no problem with filenames with underscores. It is just the directories it rejects if they are not strictly alphanumeric. But it really prefers that the files have the same names as the directories.

```
Each library must be added to the IDE using the
IDE menu Sketch..Import Library..Add Library

```

It stores them somewhere else in the IDE's guts.
> 0 votes

# Answer
here's an expression that strips every character that is not ( alpha numeric or space character, or period character) that is also Followed by an alpha numeric or space or period and replaces it by capitalising the following character.

```

find  ./ -depth | perl -wan -F'/' -e ' chomp; chomp($F[-1]);$x=$_; if ($F[-1]=~m/[^\p{Alnum}\d \.]/ and substr($F[-1],0,1) ne ".") {  $F[-1]=~s/[^\p{Alnum}\d \.]+([\p{Alnum}\d \.]{1})/uc($1)/eg; $y = join "\\",@F; system("mv",$x,$y);print "mv \"$x\" \"$y\"\n";}'

```

it ignores unix hidden file starting with "." And it also renames directories.

This will fail on edge cases where the last character in the name is a non alpha character.
> 0 votes

---
Tags: arduino-ide, arduino-nano, usb, sketch, programmer
---


# Question
Title: Arduino sends bad data ONLY when not connected at the launch my application
I'm trying to write a little sensor reading application with a light sensor attached to an Arduino, which writes the information from the sensor over serial. I have written a python program to read the data from the serial port. The good news, is that my program is working completely fine... only if I make sure that the Arduino USB is connected to my laptop before I launch my Python program.

I have myself forgotten to connect the Arduino before running the program before, which can leave it hanging... until you realise and plug the Arduino back in. It would be nice to have a window helping users if they ever make the same mistake.

Here is the Arduino sketch I have running on my Arduino.

```
int photoTran = A1;
  int reading = 0;

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

void loop() {
  // We just read the value on the analogPin
  reading = analogRead(photoTran);
  Serial.println(reading);
  delay(100);

}

```

Here is the little catcher part of the Python script which checks whether the Arduino is connected before I get into the main part of my application. When I plug in the Arduino before running the Python script, it can still sometimes take a few attempts before connecting. (Just FYI: the window(), button, values, variables are from the PySimpleGUI framework that I'm using.)

```
connected = False
while connected == False:
    button, values = window.Read(timeout=300)
    if button in (None, 'Exit'):
        break
    try:
        print("Attempting to connect")
        SER = serial.Serial(serial_port, baud_rate, timeout=0.1)
        connected = True
        ser.append(SER)
    except:
        time.sleep(0.1)
        attempts += 1
        window.FindElement('attempts').Update(attempts)
window.close()

# User exited from the GUI connection window
if not connected:
    sys.exit(0)

```

Later on in my Python code, I want to read the sensor data coming to us from the Arduino. ReadArduino, and CleanThe are the functions that I use to read data from the Arduino.

```
def ReadArduino( serialCon ):
""" Try to read in a value from the Arduino. Sometimes we might read a value from the serial
    port before the arduino has sent anything. In such cases we will wait a small time, and read again.
    Until we pick up our first non empty integer value."""
while True:
    val = serialCon.readline()
    print(val)
    val = cleanThe(str(val))
    if val != '':
        return val

def cleanThe( lineVal ):
""" The Arduino returns non-clean data back to us.
    We need to remove all the non-integer values to get
    a nice plottable integer value. Will accept '.' unconditionally for now,
    we may have to add conditions later. """
S = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.'}
clean = ''
for char in lineVal:
    if char in S:
        clean += char
return clean

```

Now the confusing part. When I run the application without the Arduino connected to my computer. It gets stuck in the while connected == False: while loop above. This is exactly what I want. Then when I plug it in, the serial port sets up and we break out of the loop. I even have a serial port object that I read from.

However, when I read from the serial port, I get back garbage hex values, without any sign of any useful integer values that I would expect.

Here are some sample raw val values that get read back when the python script is run with the Arduino connected before running: `b'336\r\n'
b'349\r\n'
b'343\r\n'
b'322\r\n'`

Then here is the output I receive when the Arduino was not connected to my computer before running the Python script.

```
b'\xe0\x00\xe0\x00\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\xe0\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\x00\xe0\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00'

b'\x00\x00\x00\xe0\x00\x00\xe0\x00\x00\xe0'

```

I have noticed, that when I am running my script with the Arduino plugged in from the start (i.e. the working case). The first value I read back from the Arduino is the same type of garbage hex:

```
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

```

It seems like in the working case, the hex is all sent on one line. Where as in the non-working case, these hex values, seem to be sent intermittently in smaller chuncks. Perhaps I could add a check to the Arduino code, to only write values back to serial if they are good? I do realise this may be more of a python serial issue than an Arduino issue, let me know if this is the case and I will move the post.

Has anyone experience some kind of problem like this before?

# Answer
> 1 votes
Just to explicitly show what I changed to my python code I thought I would answer my own question. The solution I found ended up being in the Python, but the other suggestions were useful for cleaning up the output of my Arduino. Here is the old auto connecting solution.

```
connected = False
window = sg.Window('Arduino Connection').Layout(layout)
attempts = 0
while connected == False:
    print("In connection while loop")
    button, values = window.Read(timeout=300)
    if button in (None, 'Exit'):
        break

    try:
        print("Attempting to connect")
        SER = serial.Serial(serial_port, baud_rate, timeout=0.02)
        print(SER)
        connected = True
        ser.append(SER)
    except:
        time.sleep(0.1)
        attempts += 1
        window.FindElement('attempts').Update(attempts)

```

Here is the working solution where I ask the user to press a connect button.

```
    connected = False
window = sg.Window('Arduino Connection').Layout(layout)
attempts = 0
while connected == False:
    print("In connection while loop")
    button, values = window.Read(timeout=300)
    if button in (None, 'Exit'):
        break
    if button == 'Ok':
        try:
            print("Attempting to connect")
            SER = serial.Serial(serial_port, baud_rate, timeout=0.02)
            print(SER)
            connected = True
            ser.append(SER)
        except:
            time.sleep(0.1)
            attempts += 1
            window.FindElement('attempts').Update(attempts)

```

# Answer
> 0 votes
On the Arduino side make your code non blocking:

```
 unsigned long timeStamp = 0;
 unsigned long timerDelay = 1000; // 1 second

 setup(){....}

void loop() {
// We just read the value on the analogPin
 if (millis() - timestamp > timerDelay ) {
     reading = analogRead(photoTran);
     Serial.print(reading); // instead of println which sends additional \r\n
     timeStamp =millis();  // reset timer instead of delay(100);
 }
}

```

On the Phyton side try to implement a routine waiting for the first char and then start reading from the next message on. The 1 second between sends on Arduino should suffice to ensure its working. The garbagge chars could be an init sequence from the port driver - this can not come from your code,

---
Tags: arduino-uno, sensors, python
---


title: Using the LED pin for input

text:
# Question
Title: Using the LED pin for input
I have an Arduino-like device with few GPIO pins (DigiSpark clone). It is based on an 8-pin AtTiny85 IC so there are Power, Ground and six other pins, two of those six are being used for USB keyboard simulation which leaves 4 GPIO which I want to connect 4 buttons to with minimal circuitry. The normal way to do this is to enable the internal pullups and have the buttons connect the pin to ground. This works well for most pins.

The problem is the equivalent to Pin 13 (Pin 1 in this case) which is connected via a resistor and LED to ground. The internal pullup is too weak to raise the voltage enough. Consequently that pin always appears to be in a "button pressed" state.

One solution is to cut the tracks connecting the LED, but the board is so tiny and crowded that I doubt I have the eyesight and steadiness of hand to do this.

Problematic resistor + LED are at bottom right of AtTiny85 IC

It occurs to me I could either

1. Add an external pullup to this input,
2. Change the button wiring so when pressed, it connects the pin to 5v. Change the code to look for high, not low.

Are there any problems with either of these approaches?

# Answer
In the end, stimulated by Majenko's advice to desolder the LED, I instead carefully studied the PCB layout online, checked that it corresponded to my PCB, checked the location of nearby traces I didn't want to cut and then used multiple magnifying glasses and a fresh blade in my smallest utility knife and carefully cut the track leading from the LED to the IC. All was well.
> 0 votes

---
Tags: led, pins, input, pull-up
---


# Question
Title: Why can the Xbox360 not detect the Arduino Leonardo as keyboard?
Arduino Leonardo as keyboard in the computer works! But not with the Xbox360. The Teensy works perfectly on the PC but how to emulate a keyboard device for the Xbox360.

I know the Xbox360 has security IC, but a simple USB keyboard works!

What is the diference ?

How i can emulate an usb keyboard for the Xbox360?

# Answer
Like Juraj and Majenko said. Arduino Keyboard library does emulate "Boot Keyboard".

I use NicoHood HID library and now it works.
> 3 votes

---
Tags: arduino-leonardo, teensy, keyboard, hid
---


title: How to use USB-in on an arduino?

text:
# Question
Title: How to use USB-in on an arduino?
I'm trying to use an arduino as a controller adapter. How would I get USB-in to get the signal from a usb video game controller?

# Answer
It makes actually no sense to plug an USB-Controller via an Arduino to a PC. The direct way and using an autofire/macro /custom key programmer app is more efficient.

* The Arduino UNO (with 32u4) can either replace an USB controller as demostrated in NicoHood HID library or
* additionally act as an interface for controller with strange vendor specific plugs demostrated in UNOJOY and you can build your own Controller/interface out of nearly every old non usb controller by cutting the hardware specific plug (e.g. old Xbox) and attach to an UNO who acts as "interface" to the PC. Another example is a C64-Joystick to the PC
* The other option for using an Arduino is interfacing with "old video game systems" . For some there are already more or less succesfull projects. When connecting the USB controller via an USB shield you have normally a high lag time due to the USB shield library, so the better approach is to cut the USB plug and directly interface with the Arduino.

Project with USB Host-shield:

Project old Joystick to USB-PC:

Project Arduino as controller for NES/SNES:

Info on the pinout/protocol cn be found in this page
> 0 votes

---
Tags: usb
---


title: How to use this 3-pin slide-switch?

text:
# Question
Title: How to use this 3-pin slide-switch?
I purchased these slide switches recently because I want to use them in my project:

But I don't know what to connect up the three pins to and I can't find any information about them online. Nor can I find sample code. Can someone show me how to wire them up and provide sample code please? I just want to be able to check their state and save it as a boolean variable.

# Answer
As others have said, this is a SPDT (Single Pole Double Throw) switch. The center pin is common. When the switch is slid one way, it connects the center pin to the outer pin on that side. When you slide the switch the other way, it connects the center pin to the opposite outer pin.

See the link about SPDT switches Edgar provided in his comment: http://www.learningaboutelectronics.com/Articles/What-is-a-single-pole-double-throw-switch-SPDT

That explains these switches pretty clearly.

Connect the center pin of the switch to a digital pin on your Arduino. Connect one of the outer pins to ground.

Set the digital pin on the Arduino to `INPUT_PULLUP` mode.

Then, when you read the digital state of the pin, if it is LOW, the switch is closed. (Slid to the side of the pin you attached to ground.)
> 5 votes

# Answer
Since it has two possible positions, and three pins, you have a connection between pin 1 and 2 when position 1 is selected, and between pin 1 and 3 when position 2 is selected. As BSF comment below, the middle pin is common. This means it will be connected to the outside pins depending on where the switch is moved towards.

However, you always can verify this, in the following way:

To find out which is pin 1, pin 2 and pin 3, use a multimeter. Set it to continuity mode, or if you don't have that mode, to resistance mode, and put the red/black probes to two random pins. Check if the resistance is 0, in that case you know those two pins will be connected when position 1 is selected. If there is resistance, try other pins with the probes, until you know which are connected.

Than switch the position, and do it again.

Instead of a multimeter you also can 'hardwire' it to e.g. 5V -\> pin 1, pin 2 -\> resistor of 220 ohm -\> LED -\> GND And change pin 1 and pin 2 until you found which pins connect for which positions.

To use it for you Arduino, check for a normal simple switch example, but these are two in one, one for each position.
> 3 votes

# Answer
These switches are actually a lot more simple than you would think. You have two positions, but you really only care about one of them, since if it's not in that position it must be in the other.

The central pin is the common, and when slid to one side it connects that central pin to the corresponding outside pin.

So you just use the central pin and *one* of the outside pins as if it were any other on-off switch or pushbutton. Treat it *exactly* the same (pullup resistor, which may be internal to the AVR chip, and connect the IO pin to ground through the switch).

If it's "on" (reads LOW) then the switch is in one position. If it's "off" (reads HIGH) then it's in the other position.

The only times you'd want to use both outer pins is if you were wanting to direct a signal to one of two different places, or select between two different incoming signals, or if the switch were a "3 position on-off-on" switch where it can be in either outer position or *neither* position (centre off), in which case you treat it as two separate switches, but with a common central pin that connects both to ground.
> 1 votes

---
Tags: switch
---


# Question
Title: Error 'exec: "python": executable file not found in $PATH Error compiling for board AI Thinker ESP32-CAM.' in Arduino IDE 1.8.12
I am trying to upload a sketch to the ESP32-CAM board using Arduino IDE 1.8.12 and I get an error message:

```
exec: "python": executable file not found in $PATH
Error compiling for board AI Thinker ESP32-CAM.

```

My OS is Ubuntu 18.04.4.LTS.

When I type python in the console, it does open python:

```
$ python
Python 2.7.17 (default, Nov  7 2019, 10:07:09)
[GCC 7.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
KeyboardInterrupt
>>>

```

Also python is in one of the directories referenced by PATH:

```
$ which python
/usr/bin/python
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

```

I added an additional URL referring to the ESP32 boards on the Espressif website:

```
Arduino IDE > File > Preferences > Settings > Additional Boards Manager URLs: > https://dl.espressif.com/dl/package_esp32_index.json

```

Then I added the libraries for all ESP32 boards:

```
Arduino IDE > Tools > Board > Boards Manager > esp32 version 1.0.4

```

(I tried with version 1.0.3 and it didn't change anything...)

I selected my board in the interface:

```
Arduino IDE > Tools > Board > AI Tinker ESP32-CAM

```

I granted all permissions to the USB port:

```
sudo chmod a+rwx /dev/ttyUSB0
ls -la /dev/ttyUSB0
crwxrwxrwx 1 root dialout 188, 0 Mar  4 21:25 /dev/ttyUSB0

```

My sketch is really simple:

```
void setup() {
}

void loop() {
}

```

I get the same error for any example sketch and for any ESP32 board.

Any idea how this could be fixed ?

# Answer
> 1 votes
All right so I was able to fix the problem. The Arduino IDE I was using had been installed from the Ubuntu Software Center. I uninstalled it.

Then I reinstalled the Arduino IDE by downloading it from the www.arduino.cc website and doing a manual install in /opt. Now it works awesome.

# Answer
> 1 votes
This was an issue with the old Arduino IDE snap on Ubuntu. You can easily fix this by installing the new arduino snap:

```
snap install arduino

```

Then add your user to the `dailout` group:

```
sudo usermod -a -G dialout $USER

```

After this, **reboot your device** and open Arduino IDE.

## Installing additional libraries

The Arduino IDE snap runs inside of a sandbox for security and stability reasons. This means it cannot access the Python libraries on your device. The snap bundles Python 3 and the `serial` library. If you need any other Python dependencies, you can install them inside of the sandbox using the `arduino.pip` command.

```
arduino.pip install <package-name>

```

*Note: do not use `sudo` for this command*

---
Tags: esp32, python, ubuntu
---


title: Parola library and DS3231 clock

text:
# Question
Title: Parola library and DS3231 clock
EDIT2: Well, this is the "new" code and it just displays random dots on the matrices:

```
#include "RTClib.h"

#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

// Define the number of devices we have in the chain and the hardware interface
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 16
#define NUM_ZONES 4

#define CLK_PIN   13
#define DATA_PIN  11
#define CS_PIN    10

// Hardware SPI connection
MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
// Arbitrary output pins
// MD_Parola P = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

RTC_DS3231 rtc;
#define SPEED_TIME  25
#define PAUSE_TIME  1000

uint8_t lastUpdateMin = 0;
uint8_t lastUpdateHour = 0;

// Global variable
const char  *pc[NUM_ZONES] =
{
  "TIME",
  "ROOM", //0
  "SUBJECT", //1
  "GRADE",//2
  };

void setup(void)
{

  P.begin();
    if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

 if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
//     If the RTC have lost power it will set the RTC to the date & time this sketch was compiled in the following line
   rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
 }

 P.begin(4);
  P.setZone(0, 0, 3); // Modules 0-3 in zone 0
  P.setZone(1, 4, 7); // Modules 4-7 in zone 1
  P.setZone(2, 8, 11); // Modules 8-11 in zone 2
  P.setZone(3, 12, 15); // Modules 12-15 in zone 3
}

void loop(void)
{

 DateTime now = rtc.now();
 if(lastUpdateMin != now.minute()){  // change every minute
     lastUpdateMin = now.minute();
 char buffer[] = "hh:mm";  // hours and minutes
P.displayZoneText(0,now.toString(buffer), PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);

    if(lastUpdateHour != now.hour()){     // change every hour
     lastUpdateHour = now.hour();
   P.displayZoneText(1, pc[1], PA_RIGHT, 0, 0, PA_PRINT, PA_NO_EFFECT);
   P.displayZoneText(2, pc[2], PA_LEFT, 0, 0, PA_PRINT, PA_NO_EFFECT);  // display
   P.displayZoneText(3, pc[3], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
   }
  }
   P.displayAnimate();
}

```

If I do just this:

```
void loop(void)
{

 DateTime now = rtc.now();
 if(lastUpdateMin != now.minute()){  // change every minute
     lastUpdateMin = now.minute();
 char buffer[] = "hh:mm";  // hours and minutes
P.displayZoneText(0,now.toString(buffer), PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
 }
     if(lastUpdateHour != now.hour()){     // change every hour
     lastUpdateHour = now.hour();

     }

   P.displayAnimate();
}

```

it displays the hour:minutes. the problem is it doesn't display the time and the other text at the same time

EDIT: If I execute this code below it will display text on the first row, but my question will be how do I manage to display simultaneously the hour:minutes from the clock and some text of my choice?

```
void setup(void)
{

  P.begin();
    if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

 if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
//     If the RTC have lost power it will set the RTC to the date & time this sketch was compiled in the following line
   rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
 }

 P.begin(4);
  P.setZone(0, 0, 3); // Modules 0-3 in zone 0
  P.setZone(1, 4, 7); // Modules 4-7 in zone 1
  P.setZone(2, 8, 11); // Modules 8-11 in zone 2
  P.setZone(3, 12, 15); // Modules 12-15 in zone 3

for (uint8_t i=0; i<NUM_ZONES; i++)
    P.displayZoneText(0, pc[0], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);

}

void loop(void)
{

 DateTime now = rtc.now();
 char buffer[] = "hh:mm";  // hours and minutes

// P.displayZoneText(0,now.toString(buffer), PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);  // display
//if(now.hour()==12){
//  P.displayZoneText(0, pc[0], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
//}
//else{
 // P.displayZoneText(1, pc[1], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);  // display
//}
   P.displayAnimate();
}

```

I have multiple FC-16 modules based on MAX7219 led matrices and I want to use them and a real time clock, DS3231, to build a classroom timetable.

I want the led modules to operate on the concept of zones. I want to create a zone for each row of text (a zone is a contiguous block of modules forming a kind of sub-display) as I did here: `P.begin(4); // We will have 4 zones
P.setZone(0, 0, 3); // Modules 0-3 in zone 0
P.setZone(1, 4, 7); // Modules 4-7 in zone 1
P.setZone(2, 8, 11); // Modules 8-11 in zone 2
P.setZone(3, 12, 15); // Modules 12-15 in zone 3`

I want this in order to be able to change the text in a row without modifying other rows.

Then, I need to use the hour and minutes from the DS3231 clock module and to display it on the first row of the display and on the other 3 rows I need to display the number of the room, the subject and the class.

```
const char  *pc[NUM_ZONES] =
{
  "ROOM",
  "SUBJECT",
  "CLASS",};

```

And when the hour on the first row changes, the text from the other 3 rows should change simultaneously.It's a pretty simple concept but I can't seem to know how to manage this. This is all the code I gathered up until now:

```
#include "RTClib.h"

#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

// Define the number of devices we have in the chain and the hardware interface
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 16
#define NUM_ZONES 4

#define CLK_PIN   13
#define DATA_PIN  11
#define CS_PIN    10

// Hardware SPI connection
MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
// Arbitrary output pins
// MD_Parola P = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);
RTC_DS3231 rtc;
#define SPEED_TIME  25
#define PAUSE_TIME  1000

// Global variables
uint8_t  curText;
const char  *pc[NUM_ZONES] =
{
  "ROOM",
  "SUBJECT",
  "CLASS",

};

void setup(void)
{

  P.begin();
    if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

 if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
//     If the RTC have lost power it will set the RTC to the date & time this sketch was compiled in the following line
   rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
 }

 P.begin(4);
  P.setZone(0, 0, 3); // Modules 0-3 in zone 0
  P.setZone(1, 4, 7); // Modules 4-7 in zone 1
  P.setZone(2, 8, 11); // Modules 8-11 in zone 2
  P.setZone(3, 12, 15); // Modules 12-15 in zone 3

}

void loop(void)
{

 DateTime now = rtc.now();
 char buffer[] = "hh:mm";  // hours and minutes

   for (uint8_t i=0; i<NUM_ZONES; i++)
    P.displayZoneText(i-1, now.toString(buffer), PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);

P.displayAnimate();
}

```

I dont't know how to display the hour:minutes and my text simultaneously so that I can do the rest then:

<pre><code>{

 DateTime now = rtc.now();
 char buffer[] = "hh:mm";  // hours and minutes

   for (uint8_t i=0; i<NUM_ZONES; i++)
    P.displayZoneText(i-3, now.toString(buffer), PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT); //here I want to display the hour:minutes on the first row

P.displayAnimate();
}```
</code></pre>

# Answer
> 1 votes
Your first problem is the definition of the text array:

```
const char  *pc[NUM_ZONES] =
{ "TIME",      // This will be replaced by real time its only for logic of rows here
  "ROOM",
  "SUBJECT",
  "CLASS"
};

```

then we need a timer, as you only show minutes we only have to change time in that interval to prevent flicker and other unwanted effects and hour for changing texts lateron:

```
uint8_t lastUpdateMin = 0;
uint8_t lastUpdateHour = 0;

```

Then the loop looks like

```
void loop() {
   DateTime now = rtc.now();
   if(lastUpdateMin != now.minute()){  // change every minute
     lastUpdateMin = now.minute();
     char buffer[] = "hh:mm";  // hours and minutes
     P.displayZoneText(0, now.toString(buffer), PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT); // 1st row
    }
  if(lastUpdateHour != now.hour()){     // change every hour
     lastUpdateHour = now.hour();
     P.displayZoneText(1, pc[1], PA_RIGHT, 0, 0, PA_PRINT, PA_NO_EFFECT);  // 2nd row
     P.displayZoneText(2, pc[2], PA_LEFT, 0, 0, PA_PRINT, PA_NO_EFFECT);   // 3rd row
     P.displayZoneText(3, pc[3], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT); // 4th row
    }
P.displayAnimate();
}

```

Things to do - define a two dimensional char table with all the texts needed for the different hours

```
#define NUM_LECTUREHOURS 7       // seven hour lectures
const char *pc[NUM_LECTUREHOURS][NUM_ZONES] = {
  { "TIME", "ROOM_0", "SUBJECT_0", "CLASS_0"},
  { "TIME", "ROOM_1", "SUBJECT_1", "CLASS_1"},
  { "TIME", "ROOM_2", "SUBJECT_2", "CLASS_2"},
  ...
  { "TIME", "ROOM_Last", "SUBJECT_Last", "CLASS_Last"}  // _Last in this example = 6
};

```

and display with a variable based on the hour so if your classes start at 9:00 you would use

```
uint8_t lectureHour= now.hour() - 9; // as arrays start with 0

```

and your different texts would be called like

```
  P.displayZoneText(1, pc[lectureHour][1], PA_RIGHT, 0, 0, PA_PRINT, PA_NO_EFFECT); // 2nd row

```

If your char array gets to large - depending on the texts - you will have to use PROGMEM which is an issue on its own. Hope this gets you started

**EDIT** If you want to change every two hours you do

if(lastUpdateHour != now.hour() && lastUpdateHour +1 != now.hour() ){ // change every two hours

or shorter for a variable timespan (e.g. every three hours)

```
 if( now.hour() - lastUpdateHour > 3 ){     // change every three hours

```

---
Tags: arduino-nano, time, oscillator-clock, max7219, ds3231-alarms
---


title: Arduino Timer Precision

text:
# Question
Title: Arduino Timer Precision
I am using the ATMega32u4 to generate multiple pulses at 2.5 kHz. I am using Timer 3, which is a 16-bit timer and using a prescaler of 1, so I have a 0.0625uS resolution. I want to generate pulses with pretty high accuracy and consistency. I have my previous post here, which gave me accuracy. But when I look at the pulse with my oscilloscope it has some jitter. Youtube Video of Jitter.

My final goal is to create a pulse on multiple different pins in this configuration.

What I am **assuming** is that the reason there is jitter is that there are other interrupts going on in the background, that could be shifting when the pulse stops and starts by a few microseconds. Looking through the datasheet, I found this, which seems to show interrupt priority.

It seems that my TIMER3 COMPA and COMPB are very low down the list of priorities, is there a way to change this priority list? Or is there something else that is causing the jitter?

I have posted my code below:

<pre><code>#define pin2 12
#define pin3 6
#define pin4 8

#define REFRESH 6400

int PULSEIndex;

class Pulse {
  public:
    int pulseLength;
    void Begin(byte GPIO_PIN) {
      pinMode(GPIO_PIN, OUTPUT);
    }
    void writeMicro(double pulse) {
      pulseLength = (pulse * 16);
    }
};

Pulse PULSE1;
Pulse PULSE2;
Pulse PULSE3;
Pulse PULSE4;

void setup() {
  PULSE1.Begin(pin1);
  PULSE2.Begin(pin2);
  PULSE3.Begin(pin3);
  PULSE4.Begin(pin4);

  // Reset Timer 3 Control Register to 0
  TCCR3A = 0;
  TCCR3B = 0;

  // Set CTC Mode
  TCCR3B &= ~(1 << WGM33); //0
  TCCR3B |= (1 << WGM32);  //1

  // Set prescaler to 1
  TCCR3B &= ~(1 << CS32); //0
  TCCR3B &= ~(1 << CS31); //0
  TCCR3B |= (1 << CS30);  //1

  //Reset Timer 3 and set compare value
  TCNT3 = 0;

  // Enable Timer 3 compare interrupt A and B
  TIMSK3 |= (1 << OCIE3B);
  TIMSK3 |= (1 << OCIE3A);

  //Enable global interrupts
  sei();

  //Set Refresh Rate
  OCR3A = REFRESH;
  OCR3B = 1000;
}

void loop() {
  PULSE1.writeMicro(40);
  PULSE2.writeMicro(40);
  PULSE3.writeMicro(40);
  PULSE4.writeMicro(40);
  delay(2);
}

ISR(TIMER3_COMPA_vect) {
  digitalWrite(pin1, HIGH);
  OCR3B = PULSE1.pulseLength;
}

ISR(TIMER3_COMPB_vect) {

  if (PULSEIndex == 1) {
    digitalWrite(pin1, LOW);
    digitalWrite(pin2, HIGH);
    OCR3B += PULSE2.pulseLength;
  }

  if (PULSEIndex == 2) {
    digitalWrite(pin2, LOW);
    digitalWrite(pin3, HIGH);
    OCR3B += PULSE3.pulseLength;
  }

  if (PULSEIndex == 3) {
    digitalWrite(pin3, LOW);
    digitalWrite(pin4, HIGH);
    OCR3B += PULSE4.pulseLength;
  }

  if (PULSEIndex == 4) {
    digitalWrite(pin4, LOW);
  }

  PULSEIndex++;
  if (PULSEIndex > 4) PULSEIndex = 1;
} ```

</code></pre>

# Answer
> 2 votes
> What I am **assuming** is that the reason there is jitter is that there are other interrupts going on in the background

This seems like a reasonable assumption. Since you are not doing serial communication, the Timer 0 interrupt is likely the only one triggering in the background. You can disable it with:

```
TIMSK0 = 0;

```

but then all the Arduino timing functions will stop working. You will have to `#include <util/delay.h>` and replace `delay()` with `_delay_ms()`. Note that this avr-libc function only works with compile-time constant delays. On the other hand, it is cycle-accurate and accepts floating point delays.

> is there a way to change this priority list?

There is not, and even if this was possible, it would not be that useful. Interrupts in the Arduino are not interruptible: if a low-priority interrupt is running when a high-priority one triggers, the high-priority interrupt has to wait for the currently running one to terminate. Priorities are only relevant when the processor is about to serve an interrupt request but has to decide which one, among several pending requests, it will serve first.

Now, a small remark about this:

```
void loop() {
  PULSE1.writeMicro(40);
  PULSE2.writeMicro(40);
  PULSE3.writeMicro(40);
  PULSE4.writeMicro(40);
  delay(2);
}

```

There is no point in rewriting those values over and over again. If you plan to change the code in order to make those widths non-constant, then you have to take care to:

1. make the `pulseLength` properties (or the whole `Pulse` objects) volatile
2. within `writeMicro()`, disable interrupts while changing `pulseLength`.

---
Tags: timers
---


title: ATTiny84 fuses reading as 0

text:
# Question
Title: ATTiny84 fuses reading as 0
I was programming my ATTiny84 when it randomly stopped being able to be programmed. I have an external 32768 Hz crystal connected to it, and I have been using my Arduino UNO with the ArduinoISP sketch to program it. The following command was working at least once before, but isn't anymore:

```
C:\Users\Anubhav\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\Anubhav\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -pattiny84 -cstk500v1 -PCOM3 -b19200 -Uflash:w:C:\Users\Anubhav\AppData\Local\Temp\arduino_build_256583/watch.ino.hex:i -U lfuse:w:0xe6:m -U hfuse:w:0xdf:m -U efuse:w:0xff:m

```

I tried with `-B 5` as well but that didn't seem to help either. The problems seems to be that it's always reading the fuses as 0x000000. This is my output:

```
avrdude.exe: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\Anubhav\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : COM3
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
             AVR Part                      : ATtiny84
             Chip Erase delay              : 4500 us
             PAGEL                         : P00
             BS2                           : P00
             RESET disposition             : possible i/o
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65     6     4    0 no        512    4      0  4000  4500 0xff 0xff
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               flash         65     6    32    0 yes      8192   64    128  4500  4500 0xff 0xff
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

             Programmer Type : STK500
             Description     : Atmel STK500 Version 1.x firmware
             Hardware Version: 2
             Firmware Version: 1.18
             Topcard         : Unknown
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

avrdude.exe: PAGEL and BS2 signals not defined in the configuration file for part ATtiny84, using dummy values
avrdude.exe: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.05s

avrdude.exe: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.04s

avrdude.exe: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.04s

avrdude.exe: Device signature = 0x000000
avrdude.exe: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

avrdude.exe done.  Thank you.

```

How do I fix the `Yikes! Invalid device signature.` error and why is it occurring?

# Answer
> 3 votes
As noted in question, the 32kHz crystal is used as a clock source and also at least the first programming was working.

The ArduinoISP sketch has hardcoded ISP clock speed and ISP clock has to be at most 1/4 of MCU speed. So the ArduinoISP sketch `SPI_CLOCK` has to be set to the much lower value than default 166kHz, which is way too fast for 32kHz MCU clock. The safe value is about `5000` (5kHz)

```
#define SPI_CLOCK 5000   // (1000000/6)

```

There is also baud\_rate settings for the avrdude, but it's just communication speed between computer and ArduinoISP programmer and changing it won't change `SPI_CLOCK` (which is ISP clock).

---
Tags: arduino-uno, attiny, avrdude
---


# Question
Title: What are the best GPIO pins to use for my project?
I'm working on a home automation project to control my Sommer Base+ garage door opener through Home Assistant.

The project consists of a WeMos D1 Mini with two reed switches (to detect door open/closed) and a 5V relay to control the door opener.

When the door is open the 'top / open' switch is triggered, giving a status of open. Likewise when the door is closed, the 'bottom / closed' switch is triggered, giving a status of closed. When neither switch is triggered (i.e. when the door is in motion), the status is either opening or closing, depending on the previous status.

This works fine unless the WeMos is powered up while either reed switch is closed (so if the door is open or closed).

I know this is because `D3` and `D8` GPIO pins for the open/close sensors and those can put the device into boot mode (I think that's what it's called).

What I want to know is which pins are the best to use for this project.

Is it possible for me to just change to pins `??` and `??` without needing to update my code? Is it possible that the WeMos D1 Mini isn't a good fit for what I want?

# Answer
> 4 votes
**NodeMCU and "Wemos D1 R2 and Mini" esp8266 (esp-12) pins and io overview**

---

**Serial**

RX io3 RX0

TX io1 TX0

---

**boot config pins** with pullup or pulldown on board

D3 io0 PULLUP (LOW for boot to flashing mode)

D4 io2 TX1 PULLUP (Serial1 TX. no RX for Serial1)

D8 io15 PULLDOWN (SS pin if esp8266 is SPI slave); TX if Serial.swap()

---

**untroubled GPIOs** with optional function for I2C or SPI bus:

D1 io5 default pin for I2C SCL

D2 io4 default pin for I2C SCA

D5 io14 SPI CLK

D6 io12 SPI MISO

D7 io13 SPI MOSI; RX if Serial.swap()

---

**RTC pin** for timed deep sleep wake-up (if connected to reset pin)

D0 io16 - optional internal pulldown, internal pullup not available

---

**not useable**: on NodeMcu S*x* pins io 6 to io 11 connect QIO SPI flash memory (in a very special setup the SPI bus can be used with other SPI device) (in other very special setup the QIO pins can be used as gpio)

*note: most digital IO start as INPUT\_PULLUP*

---
Tags: esp8266, pins, home-automation
---


# Question
Title: Setting up 433 MHz Transmitter and Receiver in the same Arduino sketch using Radiohead
I have set up a 433 MHz transmitter and receiver pair on one Arduino Uno board. Using the RCSwitch library, I could successfully send and receive signals. Using the Radiohead library however, I could only send and got no reception. I am curious why and grateful for any help.

Here is the sketch. Both receiver and transmitter draw power from Arduino 5V and GND. The DATA pin of transmitter is attached to pin 12 of Arduino. The DATA pin of receiver is attached to pin 11. These appear to be "hard-coded" in the Radiohead library. My reciever has an additional chip select (CS) pin which I have wired to pin 10.

Using the serial monitor, it looks like transmitter and receiver are initialized without problem and message is sent. I have used the RCSwitch library with transmitter and receiver on the same board and that worked, (i.e. messages sent were received correctly) so I am curious why the issue with Radiohead.

```
// Include RadioHead Amplitude Shift Keying Library
#include <RH_ASK.h>
// Include dependent SPI Library
#include <SPI.h>

// Create Amplitude Shift Keying Object
RH_ASK rf_receiver;
RH_ASK rf_transmitter;

void setup()
{
    // Initialize ASK Object
    if (!rf_receiver.init())
        Serial.println("Failed to initialize receiver.");
    if (!rf_transmitter.init())
        Serial.println("Failed to initialize transmitter.");

    Serial.begin(9600);

    digitalWrite(10, HIGH);   // enable CS on some receiver devices
}

void loop()
{
    const char *msg = "Hello world!";
    rf_transmitter.send((uint8_t *)msg, strlen(msg));
    rf_transmitter.waitPacketSent();
    Serial.print("Message sent: ");
    Serial.println((char*)msg);

    uint8_t buf[12];
    uint8_t buflen = sizeof(buf);

    if (rf_receiver.recv(buf, &buflen))
    {
      Serial.print("Message received: ");
      Serial.println((char*)buf);
    }
    else
    {
      Serial.print("No message rec'd: ");
      Serial.println(*&buflen);
      Serial.println((char*)buf);
    }

    delay(1000);
}

```

# Answer
The answer can be found in the source code 0f RH\_ASK.h (you should read the well made documentation before using this library):

> At present only one instance of RH\_ASK per sketch is supported.

So you will have to write such an extension yourself, use two Arduinos or use another lib for testing.
> 1 votes

---
Tags: arduino-uno, rf
---


title: MPU-9250 compass always returns to zero

text:
# Question
Title: MPU-9250 compass always returns to zero
I am trying to build a 9-DOF IMU using the MPU-9250 chip which contains a gyro, accelerometer and compass. I have successfully realized 6-DOF sensor fusion using the DMP chip and Sparkfun's library, but I still have some yaw drift which is why I want to use its onboard compass for 9-DOF.

The DMP unfortunately can't do that so I tried kriswiner's work on 9-DOF sensor fusion which seemed to work but after I rotate the PCB, the yaw moves in the correct direction but it then slowly returns back to where it started, without me moving the PCB any more. This happens with many different sensor fusion libs, some more some less severe.

I have also tried just reading the raw `mx` and `my` values and reading the heading using `atan2(my, mx)` which made things a little better but still a 360° real-life rotation did not correspond at all to a 360° rotation on the chip.

Is this a known problem with the MPU-9250 and I am missing something completely obvious, or what could be wrong here?

Thank you for any help!

# Answer
Ok, I have finally found the issue, and I am feeling very, very stupid.

1. I needed to calibrate the magnetometer with the figure-8 movement
2. I put a gigantic solid-metal 18650 Li-ion cell right next to the magnetometer chip...

EDIT: after replacing the 18650 with a polymer battery that is far away from the chip, things got a little better but both sensors in both devices still return garbage values.
> 1 votes

---
Tags: esp8266, magnetometer, imu
---


# Question
Title: Uno Wifi rev2 - after long time it disconnects
Given an Arduino Uno Wifi Rev2 with this small U-blox NINA wifi module.

All work great however after a long time (I can't be more exact but we talk here about weeks if not months), it suddenly disconnects.

This board is unattended, and the only way to recover is to reset the Arduino.

Here is my code:

```
WiFiServer server(PORT);

void setup() {
  connectToWifi();
  server.begin();
}

void connectToWifi() {
  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    if (status == WL_CONNECTED) break;

    // wait 10 seconds for connection:
    delay(10000);
  }
}

void loop() {
  // check WiFi status
  if (WL_CONNECTED != WiFi.status()) connectToWifi();

  WiFiClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        ... (other wifi-unrelated code)

        // close the connection:
        client.stop();
      }
    }
  }
}

```

When it disconnects from wifi, the router's dhcp manager console shows it with "waiting" status.

Note: I'm the only client, and only one character is sent to the Arduino at once, then the socket is closed. It is very unlikely, that a client hangs, and the board is stuck in the while loop.

Is this a known problem, or I have to dig myself more into this?

Thank you!

# Answer
> 1 votes
As you have not given the details there are some things to check

* is your Nina-Firmware \> 1.2.4
* If not update to the latest 1.3.0 via the WiFi101-FirmwareUpdater-Plugin 0.10.10 is included in the ArduinoIDE 1.8.12 or greater
* Disconnect before you reconnect (in case of router drop-outs) and
* Close any connection before sending/receiving. This will free the socket on the Nina module. Stop the client after doing the stuff needed with `client.stop();`
* If there is any server connection code in setup this should be run in a reconnect routine (as you did not include setup) just as a hint
* Make sure that after a certain period the `while (status != WL_CONNECTED)` and `while (client.connected())` are broken and error testing takes place e.g.
`if (status==WL_DISCONNECTED || status==WL_CONNECTION_LOST){.. do something to change that ..}`
* If all fails implement a routine that checks the signal and restarts the sketch if the router has dropped out (for whatever reason).

Disconnect code:

```
void connectToWifi() {
    // This new line is required to disconnect the previous connection otherwise
    // it will try to use the old connection and never reconnect if the connection fails
    status = WiFi.disconnect();

    // attempt to connect to Wifi network:
    while (status != WL_CONNECTED) {
    .... REST of your code ...
    }
}

```

Hint (as you did not show setup) if you have something like

```
client.connect(server, 80);

```

move it to the reconnection routine in the form of

```
if (client.connect(server, 80)) {
    Serial.println("connecting...");
.... REST of reconnect ...
}

```

Restart code if wifi signal is lost

```
void(* resetFunc) (void) = 0; // Declare reset function at address 0

void loop() {
  if (WiFi.RSSI() == 0) // Checks if Wifi signal lost.
  { resetFunc(); // Calls Reset
  }
// Rest of code goes here.
}

```

This should altogether ensure a long and stable running client

---
Tags: arduino-uno-wifi
---