title: Strange Output from DS1307 RTC

text:
# Question
Title: Strange Output from DS1307 RTC
I'm using a DS1307 RTC (https://www.adafruit.com/product/3296) and an Arduino mega microcontroller trying to simply set and read the time of the RTC. However, whenever I try to output anything to the Serial Monitor, I get stuff like this:

The code and the wiring is fairly straightforward which is why I'm confused. I'm just directly attaching the Vcc, GRND, SCL and SDA pins of the clock to the Arduino and using a slightly modified version of the example code as a part of the RTC library Adafruit supplied.

```
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;

void setup () {
  while (!Serial); // for Leonardo/Micro/Zero

  Serial.begin(57600);
  rtc.begin();

  rtc.adjust(DateTime(2017, 11, 17, 20, 33, 0));

}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.println();
    delay(1000);
}

```

So I know I'm doing something wrong but I'm not sure what. Any help would be hugely appreciated.

# Answer
Change the baud rate to 57600, it specifies at: Serial.begin(57600);
> -1 votes

---
Tags: rtc
---


# Question
Title: Is DateTime from RTClib giving garbage dates/times?
The RTC is working fine, but I'm having trouble with the `DateTime` class. Based on the following test, it seems like its math is wrong.

```
#include <RTRlib.h>
void loop()
{
    auto ts = TimeSpan(0, 8, 0, 0); // 8 hours
    auto zero = DateTime(0, 0, 0, 0, 0, 0);
    auto alarm = zero + ts;
    Serial.println(String("Zero date: ")+zero.year()+" "+zero.month()+" "+zero.day()+" "+ zero.hour()+":"+zero.minute()+" "+zero.second());
    Serial.println(String("Alarm as timespan: ")+ts.days()+"d "+ ts.hours()+":"+ts.minutes()+" "+ts.seconds());
    Serial.println(String("Alarm date: ")+alarm.year()+" "+alarm.month()+" "+alarm.day()+" "+ alarm.hour()+":"+alarm.minute()+" "+alarm.second());
}

```

My output is (repeating):

```
Zero date: 2000 0 0 0:0 0
Alarm as timespan: 0d 8:0 0
Alarm date: 2043 4 30 1:31 44

```

Also, when creating `DateTime(0)`, I would expect the hours, minutes, and seconds to be zero. That's not the case. What's up with this library, and how did it get to be so popular if it doesn't work?

# Answer
> 2 votes
You are experiencing the consequences of code that doesn't do sanity checking. The library allows for dates that do not make sense (in addition to giving us all a **new** reverse-Y2K bug of assuming only dates later than year 2000.

When you create `DateTime(0, 0, 0, 0, 0, 0);`, you are saying to use Month 0 and Day 0. Those have no meaning in date calculations, which always assume that the first month is 1 and the first day is 1.

The rest of the library's code assumes valid dates, so when you give it invalid dates, unexpected behavior is to be expected!

Of you only modify your `zero` assignment to `DateTime(0, 1, 1, 0, 0, 0);` you will see behavior that is more expected.

---
Tags: library, rtc
---


# Question
Title: How do I detect the Computer's operating system?
I'm working on an emoji keyboard and it requires different input depending on the OS it's connected to. I've written the relevant methods using Arudion's default Keyboard library and can manually set which one is used. I'm wondering if there is a method or library for Arduino (currently using a Adafruit Feather 32u4 Bluefruit LE) that allows me to detect the OS.

If not, I'll set up a switch, but that'll cost me pins.

# Answer
> 3 votes
If you can't get the OS from the USB port, why not use the existing keys/inputs to set the mode on startup? That is, if you tell the user to press different combinations of 2 buttons on startup, you have 4 (2 bits =\> 4 values) different paths on startup:

```
00 => Normal startup, don't change mode
01 => OS 1
10 => OS 2
11 => OS 3

```

---
Tags: usb
---


title: DHT11 returning incorrect values

text:
# Question
Title: DHT11 returning incorrect values
I am trying to use DHT11 sensor with Arduino. But unfortunately it is returning following values:

Temperature = 1.00 Humidity = 2.00

My code is as follows:

```
#include <dht.h>
dht DHT;
#define DHT11_PIN 7

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

void loop()
{
    int chk = DHT.read11(DHT11_PIN);
    Serial.print("Temperature = ");
    Serial.println(DHT.temperature);
    Serial.print("Humidity = ");
    Serial.println(DHT.humidity);
    delay(1000);
}

```

Link to the library I am using is here

I have connected +ve to 3.3 V I have connected -ve to Ground I have connected out to digital pin # 7

# Answer
> 3 votes
You have to call the **functions**:

```
#include <DHT.h>
#define DHT11_PIN 7
DHT dht(DHT11_PIN, DHT11);

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

void loop() {

    float humidity = dht.readHumidity();
    float temperature = dht.readTemperature();

   if (isnan(humidity) || isnan(temperature)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }

    Serial.print("Temperature = ");
    Serial.println(temperature);
    Serial.print("Humidity = ");
    Serial.println(humidity);

    delay(1000);
}

```

**Edit**

# Answer
> 2 votes
This is not a DHT11, DHT11 is blue, DHT21 is black, and DHT 22 is white. It must be a DHT22 hence the wrong values.

EDIT : on your pictures the white case says AM2302, it's definitely a DHT22 the code must be adapted accordingly.

---
Tags: sensors, temperature-sensor
---


title: How to rebuild Arduino core for ESP8266

text:
# Question
Title: How to rebuild Arduino core for ESP8266
I'm experimenting adding DHCP option 160 to dhcpserver.c in the Arduino core for ESP8266 and therefor need to rebuild the relevant parts.

I made an initial guess that I might be able to make the change by installing using git according to the instructions in the readme and just restarting the IDE. I wasn't surprised to learn that this didn't help. The modifications to dhcpserver.c did not make it to the device following restart of the IDE and a new upload.

From another forum I saw a suggestion that the following commands could be used to rebuild from source:

```
$ cd esp8266/tools/sdk/lwip/src
$ make install

```

Again the changes didn't make it to the device after restarting and uploading the sketch again.

Does anyone have any clearer instructions for how to build a new Arduino core for esp8266?

# Answer
> 2 votes
There are four variants of LwIP bundled with the ESP8266 core:

* V1.4 (Compile from source)
* V1.4 (Precompiled)
* V2 Lower Memory
* V2 Higher Bandwidth

By default (for most boards) one of the V2 variants is selected. You need to change that to the V1.4 (Compile from source) for it to use the version that you have modified.

---
Tags: esp8266, build
---


# Question
Title: How can I send and receive data from an Arduino Uno to Arduino Mega using I2C?
I am trying to send data as a string from an Arduino Uno to another Arduino Mega. I have read about the I2C connection where we connect the RX to TX oppositely.

How to start and send and receive data between them? I have no idea how the code can be written.

# Answer
At instructables there is a good post.

In short the code is

Master code:

```
// Include the required Wire library for I2C
#include <Wire.h>
int x = 0;
void setup() {
  // Start the I2C Bus as Master
  Wire.begin();
}
void loop() {
  Wire.beginTransmission(9); // transmit to device #9
  Wire.write(x);              // sends x
  Wire.endTransmission();    // stop transmitting
  x++; // Increment x
  if (x > 5) x = 0; // `reset x once it gets 6
  delay(500);
}

```

Slave code

```
// Include the required Wire library for I2C
#include <Wire.h>
int LED = 13;
int x = 0;
void setup() {
  // Define the LED pin as Output
  pinMode (LED, OUTPUT);
  // Start the I2C Bus as Slave on address 9
  Wire.begin(9);
  // Attach a function to trigger when something is received.
  Wire.onReceive(receiveEvent);
}
void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
}
void loop() {
  //If value received is 0 blink LED for 200 ms
  if (x == '0') {
    digitalWrite(LED, HIGH);
    delay(200);
    digitalWrite(LED, LOW);
    delay(200);
  }
  //If value received is 3 blink LED for 400 ms
  if (x == '3') {
    digitalWrite(LED, HIGH);
    delay(400);
    digitalWrite(LED, LOW);
    delay(400);
  }
}

```

In the instructables post a lot more explanation is shown.
> 0 votes

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


# Question
Title: Formula to calculate energy required to power an Arduino board
Given an Arduino board with the following specs:

**ATmega328 Arduino Nano AVR® ATmega MCU 8-Bit AVR Embedded Evaluation Board** (link)

What is the mathematical formula to calculate how much energy/power would be required to keep the Arduino board on (meaning in "standby" mode, therefore not consuming any energy but the one required to keep it "alive")?

Please note I am new to all things electronics, Arduino but most importantly physics and maths. Thank you.

# Answer
In the datasheet you can read how much every mode uses (normal mode, sleep mode etc). However, it also depends on which peripherals inside the CPU are active and all electronics around it. So make sure you read the datasheet of the entire development board, and not from the CPU itself.

The mathematical formula is reasonably simple: the total power is the sum of each component's Amperage * component's Voltage. But practicially this is hard to calculate.

The easiest way (but not mathematically) is probably just to measure the amperage in the development board, and the voltage and multipley them together.
> 2 votes

---
Tags: electronics, mathematics
---


# Question
Title: Why can't I use just the digital pins and a ground to use a potentiometer?
First of all I am a newbie. So please excuse.

After doing the first basic project, in which I had hooked up the positive of a LED to a digital input of the Arduino and the negative to the ground of the board, I am assuming that the digital pins in Arduino are positive (are they 5v?).

So why can't the potentiometer be connected in the same way?

Thank you.

# Answer
A potentiometer is an analog device, meaning it communicates its position by varying the voltage rather than sending discrete ones and zeros.

If a linear potentiometer is turned half way then the output of the pot will be at half the voltage of the input. If it is turned all the way then the output will equal the input voltage and if it is not turned at all then the output will be 0V.

In order to make sense of the potentiometer you must connect the output to the analog pins and it will give you a 10 bit number, the higher this number the closer the output voltage of the potentiometer is to 5v (or whatever you set the Analog Reference voltage to be, but don't worry about the AREF pin for now).

Digital pins are either on or off, there is no in between, so they do not work for this application

This page has an excellent potentiometer user guide: https://www.arduino.cc/en/Tutorial/Potentiometer
> 6 votes

# Answer
> I had hooked up the positive of led to a digital input of the arduino and negative to the ground of the board.

You shouldn't have done that. It damages both the LED and the Arduino.

The care and feeding of LEDs

> So I am assuming that the digital pins in arduino are positive (are they 5v?).

Yes and yes (assuming a 5V Arduino).

> So why cant the pot be connected in the same way?

The pot has 3 terminals, so I'm not sure what you mean by that. You are going to connect them to ground, a digital pin, and **what else**?

---

Normally you connect one end of the pot to ground, the other end to +5V, and the middle terminal to one of the analog inputs. Then when you turn the pot, the voltage at the analog input changes to be somewhere between 0V and 5V.

---

A potentiometer is a form of voltage divider \- I suggest you read those links to understand more about them.
> 3 votes

# Answer
> I am assuming that the digital pins in Arduino are positive (are they 5v?).

On a 5V Arduino, when a GPIO pin is set to OUTPUT and switched HIGH then yes, it is (almost) 5V. When switch LOW it is (almost) 0V or GND. When it is set to INPUT it is neither - it is "high impedance" and senses the voltage on the pin using a set of *thresholds*.

When the voltage being applied to the pin is above the *high* threshold (known as *VIH*) the pin sees it as a logic HIGH and `digitalRead()` reports it as such. When the voltage being applied is *below* the *low* threshold (known as *VIL*) the pin sees it as a logic LOW and `digitalRead()` reports it as such.

> So why can't the potentiometer be connected in the same way?

So yes, you can connect a potentiometer up to to a digital pin in the same way as you can to an analog pin (one pin to +5V, one pin to ground, and the middle "wiper" pin to the digital input):

When you turn it, instead of reading a value between 0 and 1023 as you would on an analog pin, you will either get a HIGH or a LOW depending on how far you have turned the knob and in which direction. In the region in the middle you will read "who knows?" - that is, maybe HIGH, maybe LOW, depending on the weather and the pin itself.

Note that connecting a potentiometer up like this on a pin set to OUTPUT is dangerous (not to you, to the Arduino) and has the potential to damage the GPIO pin's internal circuitry when the pot is turned all the way one way or the other, since it creates a dead short circuit to either ground or +5V, and the GPIO pin itself, when in OUTPUT mode, is also connected internally to either ground or +5V.

Some pins on microcontrollers (not sure about the Arduino off hand) have *Schmitt Trigger* inputs. These avoide the "who knows?" region by toggling the input HIGH or LOW depending on when the voltage passes a threshold. For the pin to change from reporting a LOW to a HIGH the voltage has to pass above the high threshold. To then switch to reporting a LOW again it has to drop all the way down to the low threshold. Any voltage in between the two thresholds is ignored completely and the previous state is retained.
> 2 votes

# Answer
For connect a LED you need use a little resistor to limit the current, so you can use the potenciometer with your LED and see the bright ajust.

> I had hooked up the positive of a LED to a digital input

A Arduino digital PIN as cofigurable how input or output, if you use it as input you need use this pin for read a digital value (0 or 1), example a button. When you configure the pin to output you can set the value high (~5v) or low (0v).
> 1 votes

# Answer
It depends on what you are trying to accomplish. If you set the pin as output and turn it on, then can use it as 5v power source. This is done frequently when you want the software to be able to turn some part of your system on/off. If this is what you want, you can put a pot or any other component downstream as long as it doesn't try to draw too much power. See this post for details on that

If you are trying to read the "value" of the pot, it would work as an on/off switch because this is a digital pin. Digital means 0 or 1. When there is enough voltage, it will register as 1, once the voltage gets low enough, it will register as a zero. If you want to read a full range of values from the pot, you would have to use an analog pin.
> 1 votes

# Answer
Analog pot on digital pin will give, 0:from min to half way and 1: from half way to end position You can use it if this suits your program logic.
> 1 votes

---
Tags: potentiometer
---


title: Arduino IDE libraries search

text:
# Question
Title: Arduino IDE libraries search
Where I can do search libraries on WEB, that similar search in IDE? I did not find search page on `arduino.cc`

# Answer
> 0 votes
The online analog of the Arduino IDE's Library Manager search feature is located here:

https://www.arduinolibraries.info/

That website is generated from the same index file Library Manager uses:

http://downloads.arduino.cc/libraries/library\_index.json

# Answer
> 3 votes
You get widest search with Google. Write "arduino" and then the device or topic name.

Most of the libraries have a GitHub repository. You can use a search field on GitHub.

A list of selected libraries sorted by topic is on Arduino playground.

# Answer
> 2 votes
You can search the PlatformIO Library Database. It covers libraries for many architectures and platforms, but if you add `framework:arduino` to the start of your search it narrows it down to just Arduino libraries.

From there you can go to the homepage or repository for a library you want.

It doesn't have all libraries, only the ones that have been set up for PlatformIO support, but that is quite a lot of libraries now.

---
Tags: arduino-ide
---


title: Action while button is pressed

text:
# Question
Title: Action while button is pressed
**My issue is that I can't rotate the motors continuously. If I press any button, motor.step will be executed and then it stops, even though I didn't release the button.**
This is my project so far.
Code:

```
#include <AFMotor.h>

//define steppers
AF_Stepper motor1(48, 1);
AF_Stepper motor2(48, 2);

char data;

void setup()
{

  motor1.setSpeed(200);  // 10 rpm
  motor2.setSpeed(200);  // 10 rpm
  Serial.begin(9600);
}

void loop()
{
  Serial.println(data);
  if (Serial.available())
  {
    data = Serial.read();
    if (data == 'A')
    {
      motor1.step(200, FORWARD, DOUBLE);
    }
    if (data == 'B')
    {
      motor1.step(200, BACKWARD, DOUBLE);
    }
    if (data == 'C')
    {
      motor2.step(200, FORWARD, SINGLE);
    }
    if (data == 'D')
    {
      motor2.step(200, BACKWARD, SINGLE);
    }
    if (data == 'E')
    {
    delay(50);
    }
  }
}

```

App Inventor blocks:

# Answer
> 0 votes
This statement: `data = Serial.read();` consumes the data sent over the serial port, so to get continual movement, you will have to constantly feed in `A` or `B`, etc. from whatever is generating that data.

Alternately, you could define a 2nd set of single-character commands to accompany the start-rotation parts so that send one command to turn on the motor, and a different command to turn off the motor. You would need to add a variable to hold the current state (started or stopped) of each motor, and turn on or off those states depending on what commands come in from the user.

(untested code)

```
#include <AFMotor.h>

//define steppers
AF_Stepper motor1(48, 1);
AF_Stepper motor2(48, 2);

char data;
int8_t motor1state=0;  // 0=> Stopped, -1=>Reverse, 1=>Forward
int8_t motor2state=0;

void setup()
{
  motor1.setSpeed(200);  // 10 rpm
  motor2.setSpeed(200);  // 10 rpm
  Serial.begin(9600);
}

void loop()
{
  Serial.println(data);
  if (Serial.available())
  {
    data = Serial.read();
    if (data == 'A')
    {
      motor1state = 1;
    }
    if (data == 'B')
    {
      motor1state = -1;
    }
    if (data == 'C')
    {
      motor2state = 1;
    }
    if (data == 'D')
    {
      motor2state = -1;
    }
    if (data == 'F')
    {
      motor1state = 0;
    }
    if (data == 'G')
    {
      motor2state = 0;
    }
    if (data == 'E')
    {
    delay(50);
    }
  }

  if (motor1state>0)
  {
    // Step forward
    motor1.step(200, FORWARD, DOUBLE);
  }
  else if (motor1state<0)
  {
    // Step backward
    motor1.step(200, BACKWARD, DOUBLE);
  }
  else
  {
    // Do nothing
  }

  if (motor2state>0)
  {
    // Step forward
    motor2.step(200, FORWARD, SINGLE);
  }
  else if (motor2state<0)
  {
    // Step backward
    motor2.step(200, BACKWARD, SINGLE);
  }
  else
  {
    // Do nothing
  }
}

```

# Answer
> 0 votes
Serial isn't a keyboard. When you send 'A' you send 'A'. Whatever that source is - if you send a single A you send a single A, and you receive a single A.

You will have to come up with some other protocol and write some special software on your computer that monitors the keys directly, and sends something along the lines of "I Pressed A" and "I Released A".

---
Tags: arduino-uno, bluetooth, stepper
---


# Question
Title: Can only write 5V or 0V, not something in between
I'm working on a bigger project, and needs to give out a voltages between 0 and 5V. I've written this code:

```
int ledPin = 12;      // LED connected to digital pin

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

void loop(){
analogWrite(ledPin, 255);
delay(2000);
analogWrite(ledPin, 0);
delay(2000);
analogWrite(ledPin, 127);
delay(2000);
analogWrite(ledPin, 128);
delay(2000);
}

```

If I've understood it right, this should first give about 5V, then 0V, then 2.5V and againg 2.5V. However my voltmeter only reads 5V and 0V, 2 seconds at each. I've attached my voltmeter to pin 12 and ground. The arduino board is also grounded.

# Answer
The PWM pins output a square wave from 0 to 5V. If you want something more like a DC level, then run the signal thru a Resistor-Capacitor (RC) Lowpass filter. 1K and 10uF should work well to smooth the squarewave. http://sim.okawa-denshi.jp/en/CRtool.php

On an Uno, pins 3,5,6,9,10,11 are the PWM pins and output at a frequency of ~ 490 Hz or 980 Hz, with a duty cycle from 1 to 254. 0 is full off, 255 full on.
> 3 votes

# Answer
Most Arduino boards do not have true analog output that can produce voltage range. To check if a particular board has true analog output check the specs and look for pins labeled DAC or Digital-to-analog converter. Be aware that the supported voltage range will vary depending on the board.

The analogWrite() function uses Pulse Width Modulation to simulate analog output.

If you need true analog output you will need to attach a Digital to Analog Converter(DAC) to the arduino. e.g. https://learn.adafruit.com/mcp4725-12-bit-dac-tutorial

UPDATE: If your goal is to drive a motor with a SN754410 you should be able to use the PWM analog output to drive it at varying speeds. Here is an example: http://web.ics.purdue.edu/~fwinkler/616/sn754410\_Arduino.pdf
> 3 votes

---
Tags: analogwrite
---


# Question
Title: How do I get a nonzero output from my HX711 and load cell?
I am trying to set up a load cell using the HX711 amplifier. Whenever I upload my sketch, my serial monitor only will read zeros regardless of load applied to the sensor (no signal appears to be sending from my load cell).

Here is my wiring, with the Arduino Uno connected to a COM port. I am using an Arduino Uno, HX711, and Sparkfun's TAL220 Straight Bar 10kg load cell.

Here is the calibration sketch I am using (from the HX711 hookup guide):

```
#include <HX711.h>

#define DOUT 9
#define CLK 8

HX711 scale(DOUT, CLK);

float calibration_factor = 282650; //-7050 worked for my 440lb max scale setup

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");

  scale.set_scale();
  scale.tare(); //Reset the scale to 0

  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}

void loop() {

  scale.set_scale(calibration_factor); //Adjust to this calibration factor

  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1);
  Serial.print(" kgs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
  Serial.print(" calibration_factor: ");
  Serial.print(calibration_factor);
  Serial.println();

  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if(temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
}

```

And here is a typical output from the serial monitor (I previously had this load cell functioning correctly, which is why my calibration factor is so different).

Observations:

* Whenever I upload the sketch and open the serial monitor, the TX LED on my Arduino Uno will light up flashing, but the RX LED stays off.
* Removing the scale.tare() step will output a constant nonzero value, but the load cell is unaffected by any loading:

* I have tried adding an external power supply to the hookup assembly (I don't know if this is even necessary, but I know the load cell requires excitation to function, so I thought I'd give it a try). So far it has not changed the output in any way.
* I have also tried adjusting the calibration factor, which only offsets the constant value outputted.
* I have re-soldered the connecting wires to the load cell and replaced the remaining wires, as well as tried multiple Uno Boards and a new USB cord. I have also gone over my wiring and had my labmate check it too (though I will definitely not rule out it being some small wiring/hardware mistake on my part, as I am still very new to Arduino).

Thank you for any suggestions!

# Answer
The zero factor 8388607 showed up in a similar question on another forum and is associated with the range of the HX711 amplifier. This indicated that my amplifier was broken; I have since replaced it and am now receiving a signal from the load cell.
> 1 votes

---
Tags: arduino-uno, serial, sensors, pins, serial-data
---


# Question
Title: ArduCAM OV2640 and microSD card module -- SPI problems
So what I'm trying to do is use the ArduCAM OV2640 (2MP Mini) to take a timelapse. Of course the first thing I have to do it to get it to take a picture and write it to an SD card. The thing is, the camera works fine by itself, however when I hook up the SD card something happens where the SPI no longer works (I have a general understanding of how SPI works -- not a highly technical understanding though).

So my main question is if it's possible for a device using SPI to 'use up' the entire SPI bus so that other peripheral devices can't interact with the microcontroller?

And if so, is there any software or way to visualize this? Like something that monitors the SPI bus?

And as for how to actually fix the problem, would it be practical to use a shield with a built in SD card module? Or use a logic gate to determine which device to allow access?

I really don't have the greatest understanding of this, so any help would be appreciated.

EDIT:

I'm using this camera module with this sd card module. As for my wireup, the camera follows as below:

The common pins between the SD card module and camera are VCC,GND,MISO (pin 12) , MOSI (pin 11), and SCK (pin 13). I have an individual CS pin for each.

# Answer
In this case, I don't think that a device is "*using SPI to 'use up' the entire SPI bus so that other peripheral devices can't interact with the microcontroller*". I think that your problem probably lies with how your SD card is connecting via the SPI bus.

The problem is that a lot of Serial Peripheral Interface (SPI) devices, particularly the cheaper ones, don't properly put the MISO pin into high-impedance when SS is pulled high.

I had almost exactly this situation with one of my projects. I eventually resolved it by placing a tri-state buffer in the MISO line for each of the SPI devices.

In that case, I used a 74HC125 (4-channel tri-state buffer).

This is the page on Better SPI Bus Design in 3 steps that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).
> 3 votes

---
Tags: arduino-uno, spi, sd-card
---


title: Get IR Signal and its strength

text:
# Question
Title: Get IR Signal and its strength
Using an IR sensor, how can I get and decode signals from other IR devices? I've seen the IRRemote library and its forks, but it doesn't fulfill my second requirement which is that I need to be able to tell the signal strength of the IR signal.

In addition, do I have to use a higher-end TSOP module? Or could I just use one of these?

Thank you!

# Answer
An IR signal is modulated. To understand the data you need to demodulate the signal. The simplest way is with an IR receiver module. However they condition the signal into a digital signal - it's impossible (on the majority of modules) to get the signal strength.

The devices you link to are IR Photodiodes. They form the optical receiver portion of the IR modules. You need to couple them with some form of demodulating system - either in hardware or, if your MCU is powerful enough, in software. However, you can get at the raw analog voltages that the photodiode generates to get a signal strength value.

So you have either an easy time of it but no signal strength, or signal strength but a very hard job of interfacing.

So why not take the best bits of both? Use an IR module to demodulate the signal and give you the data, and next to it use a photodiode and op-amp (to boost the tiny signal) to give you the raw optical intensity? Yes, it would cost you more, and the circuitry would be more complex, but it's really the only way that you can do it without using specialist modules.

But of course, it begs the question: why do you really want to get this kind of information? Of what use can it be? The "signal strength" is of little benefit since there are so many factors that influence it - incidence angle, distance, transmitter battery voltage, etc.
> 1 votes

---
Tags: esp8266, ir, signal-processing
---


# Question
Title: How to receive more than 64 bytes on Arduino?
I am receiving about 90 bytes on the serial port. But Arduino has a serial buffer of 64 bytes only. Because of this limitation I am unable to receive further bytes.

```
char c;

void read_response() {
  while(Serial.available > 0) {
    c=Serial.read();
    Serial.print(c,HEX);
    Serial.print(",");
  }
}

```

I tried using the above function to read the serial data, but it is able to read only 64 bytes.

Another approach I tried as follows:

```
char rxdata[]={};

void read_response() {
  while(Serial.available > 0) {
    int len= Serial.readBytes(rxdata, 90)
  }
}

```

With this approach too, I was receiving only 64 bytes.

`Serial.flush()` also doesn't work as it waits for current transmission to finish. And I do not have control on transmission. The transmitter is sending 90 bytes continuously.

Please give me some suggestions.

# Answer
> But Arduino has a serial buffer of 64 bytes only. Because of this limitation I am unable to receive further bytes.

This assertion is nonsense. Certainly there is a buffer, but that lets you receive up to 64 bytes (put there by the serial interrupt service routine) before you retrieve a single one.

All you need to do is expeditiously retrieve the data (that is, do a `Serial.read()`) fast enough that you remove the data from the buffer and store it into memory.

You need to post a Minimal, Complete, and Verifiable Example (MCVE) that demonstrates your problem. For example, are you doing `delay(1000)` before attempting to read serial data?

See my post about receiving serial data without blocking and also Async (Serial) peripheral interface - for Arduino.
> 3 votes

# Answer
You will need to adjust your concept of serial communication so that you don't rely on the complete 90 bytes of data to be transferred to the serial input buffer before you read it into RAM.

Instead you need to continually empty the hardware buffer into RAM as often as you run through `loop()`, and avoid using `delay()`, which will stop your program from being able to drain the buffer.

To know when you have reached the end of the transmission, you should either ensure that the incoming serial stream has a marker at the end (such as a `'\n'` character) or is always a fixed length (such as always exactly 90 bytes.)

As an example, here is a program that looks for `'\n'` as the end-of-data marker:

```
#DEFINE MAX_INPUT 90

char inputBuffer[MAX_INPUT+1]; // Handles up to 90 bytes in a c-style string, with a null character termination.

void setup()
{
  Serial.begin(115200); // initialization
  inputBuffer[0] = '\0'; //Initialize string to emtpy.
  Serial.println("Begin:");
}

void loop() {

  if (Serial.available()>0)
  {
    char input = Serial.read();
    static int s_len; // static variables default to 0
    if (s_len>=MAX_INPUT) {
      // Have received already the maximum number of characters
      // Ignore all new input until line termination occurs
    } else if (input != '\n' && input != '\r') {
      inputBuffer[s_len++] = input;
    } else {
      // Have received a LF or CR character

      // INSERT YOUR CODE HERE TO PROCESS THE RECEIVED DATA //
      // YOU COULD COPY TO A NEW VARIABLE WITH strncpy() OR //
      // SET A FLAG TO SAY TO START SOME OTHER TASK         //
      Serial.print("RECEIVED MSG: ");
      Serial.println(inputBuffer);

      memset(inputBuffer, 0, sizeof(inputBuffer));
      s_len = 0;             // Reset input buffer here if you
                             // have already copied the data.
                             // If you don't reset here, then
                             // you can't start receiving more
                             // serial port data. This is your
                             // 'software' serial buffer, contrast
                             // with the hardware serial buffer.
    }
  }
}

```
> 1 votes

---
Tags: serial, arduino-nano
---


title: Question about Variables

text:
# Question
Title: Question about Variables
is there a way to use a previous assigned value to variable to adjust the step motor? what i mean is:

example: Sensor reads 100 degrees so

Adjust the step motor to 100 degrees and hold, then after 10 min

the sensor reads 110 degrees so

Adjust the step motor (110 - 100) by extra 10 degrees

and so on..

I'm really new to this and i'm sorry if that's a stupid question :\<

# Answer
Based on your description, the program needs to know only the new target setting and the current position. That means you need two variables. Algorithmically, it would look as follows (written in C-like pseudo-code):

```
// initialize global variables (might need float instead of int)
int target_pos = 0;
int current_pos = 0;

void setup() {
    // add code to set up pin IO mode, prepare communication with the sensor...
}

// function to read the sensor
int ReadSensorFunc(void) {
    int reading = 0;   // local variable to store sensor reading
    reading = ...;     // add code to read sensor
    return reading;
}

// function to adjust the motor position
void AdjustStepMotorFunc(void) {
     // add code to to adjust the stepper to (target_pos-current_pos);
}

void loop() {  // repeat forever
    target = ReadSensorFunction()   // call sensor read function
    AdjustStepMotorFunc()           // call position adjustment function
    current_pos = target_pos        // update current position
    // add code to delay for 10 minutes
}

```

This code initializes the position as zero. In case it's not zero when the controller is turned on, you'll need additional code in `setup()` to assign `current_pos` the correct value based on user input.
> 2 votes

# Answer
Initially you read the value of sensor to some variable, like:

```
previous = readSensor();

```

Every ten minutes you have to call a function ( logic using timer interrupt / RTC /millis() ) which reads the current value from sensor and compares it with previous value to get the offset. Then you pass it to the function which adjusts motor speed. Update 'previous' variable

```
offset = readSensor()-previous;
previous = readSensor();
adjustSpeed(offset);

```
> 1 votes

---
Tags: arduino-uno, stepper, variables
---


# Question
Title: Communication between 2 Bluetooth modules
I successfully connected two Bluetooth modules, HC-05 and HC-06 like on this website:

http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link/

I have an Arduino Nano that's the slave (HC-06) and an Arduino Mega that is the master (HC - 05) and there's is the code for both of them:

**Reveiver - Master**

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX | TX
String Data = "";
void setup() {
    Serial.begin(9600);
    mySerial.begin(9600);
}

void loop(){
    while (mySerial.available()){
        Serial.println(mySerial.read())
    }
}

```

**Sender - Slave**

```
#include <SoftwareSerial.h>
SoftwareSerial BTserial(11, 10); // RX | TX

int c = 100;

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

void loop(){
     BTserial.println(c);
}

```

I tried

```
BTserial.write(c)

```

and doesn't work either, I receive numbers like 245,255. And when I change the data that I'm sending the numbers are different, so I know that they are communicating, I think it's a variable problem, but I tried a bunch of codes of the internet that supposedly work, but it doesn't seem to work for this case.

# Answer
> 1 votes
println prints the int variable c as string "100" with /r/n at the end. And you read it as bytes with read and print the bytes as numbers with new line at the end. So you get ascii values of 1, 0, 0, \r and \n.

use write() to write a byte to Bluetooth and to Serial Monitor

---
Tags: arduino-mega, arduino-nano, bluetooth
---


# Question
Title: Why does Serial.print print only a value for 0-84 for a 100 integer array?
```
int a[100],i;
void setup() {
  Serial.begin(9600);
}

void loop() {
  for(i=0; i<100; i++) {
    a[i] = i;
    Serial.println(a[i]);
  }
  exit(0);
}

```

# Answer
> 27 votes
It's because you're using `exit(0)`. That turns off interrupts and goes into an infinite loop. However, serial printing is first placed into a buffer, and each character is then removed from that buffer in turn and sent out through the serial port.

That's all fine, up until the end when you use `exit(0);`, and what is left in the serial buffer to send never gets sent because interrupts are disabled.

There is never really any cause to use `exit()` on a microcontroller - after all, where can it "exit" to? There's no OS to exit to. So it does the next best thing which is as close to doing nothing as reasonably possible.

Instead, if you want to "stop" your program you should use a simple `while(1);` which will allow interrupts to still trigger.

Alternatively, if you really want to use `exit()`, you should `flush` the serial first:

```
Serial.flush();

```

That function will block until the transmit buffer has been fully emptied by the interrupt and the last byte has left the UART's TX shift register.

---
Tags: array
---


# Question
Title: How to stop a loop when using attachInterrupt to catch the change of a button
This what the program does:

> There is 1 button to start/stop the engine, when the motor is running the green LED will go on, when stopped the red LED is on. The second button is used to change the direction of the DC-motor. When the temperature is above 20° the motor will stop and the servo motor will go to the position of the red LED. Otherwise the servo motor is in a neutral position. When the engine is running there a music playing that should sound as a car.

So what my problem is if I pressed the button to stop the DC-motor but the music is still playing it won't stop. I read something about a break. Can you combine this with the `attachInterrupt()`? I also found something called `interrupts()` and `noInterrupts()`. What do I need to so when I pressed the button the DC-Motor directly stops and the led turns red?

The init

```
#include <Servo.h>
#include "notebook.h";
#include "themes.h";

const int input1OfTheDCMotor = 9;
const int input2OfTheDCMotor = 10;
const int pwmInputOfTheDCMotor = 6;
const int buttonToStartStopTheDcMotor = 2;
const int buttonToShowToChangeTheDirectionOfTheDCMotor = 3;
const int greenLed = 12;
const int redLed = 8;
const int tempSensor = A0;
const int servoPin = 11;
Servo servo;

volatile byte stateOfTheButtonToStartStopTheDCMotor = LOW;
bool isRunning = LOW;
bool changeDirection = LOW;
bool isEngineSoundsPlaying = HIGH;

```

The `setup()`

```
void setup() {
  //Leds setup
  pinMode(greenLed, OUTPUT);
  pinMode(redLed, OUTPUT);
  digitalWrite(redLed, HIGH);
  //buttons
  pinMode(buttonToStartStopTheDcMotor, INPUT);
  pinMode(buttonToShowToChangeTheDirectionOfTheDCMotor, INPUT);
  //DC motor
  pinMode(input1OfTheDCMotor, OUTPUT);
  pinMode(input2OfTheDCMotor, OUTPUT);
  digitalWrite(input1OfTheDCMotor, LOW);
  digitalWrite(input2OfTheDCMotor, HIGH);
  //pwm signal
  pinMode(pwmInputOfTheDCMotor, OUTPUT);
  //Servo
  servo.attach(servoPin);
  //interrupts
  attachInterrupt(digitalPinToInterrupt(buttonToStartStopTheDcMotor), readTheChangeToStartStop, RISING );
  attachInterrupt(digitalPinToInterrupt(buttonToShowToChangeTheDirectionOfTheDCMotor), readTheChangeToChangeDirection, RISING );
}

```

The `loop()`

```
void loop() {
  int valueOfTheSensor = analogRead(tempSensor);
  float voltage = (valueOfTheSensor / 1024.0) * 5.0;
  float temp = (voltage -0.5) * 100;
  if (temp >= 20.00)
    isRunning = LOW;
  }
  changeTheStateOfTheLights(isRunning);
  startTheDCMotorAndStopIt(isRunning);
  changeTheDirectionOfTheDCMotor(changeDirection);
}

```

The function `readTheChangeToStartStop()`:

```
void readTheChangeToStartStop () {
  isRunning  = !isRunning;
  changeTheStatusOfTheEnginePlaying();
}

```

The function `readTheChangeToChangeDirection()`:

```
void readTheChangeToChangeDirection () {
  changeDirection = !changeDirection;
}

```

The function `changeTheStatusOfTheEnginePlaying()`:

```
void changeTheStatusOfTheEnginePlaying (){
  if (isRunning == HIGH){
    isEngineSoundsPlaying = HIGH;
  } else {
    isEngineSoundsPlaying = LOW;
  }
}

```

The function `changeTheStateOfTheLights()`:

```
void changeTheStateOfTheLights(bool stateOfLight) {
  digitalWrite(greenLed, stateOfLight);
  digitalWrite(redLed, !stateOfLight);
}

```

The function `startTheDCMotorAndStopIt()`:

```
void startTheDCMotorAndStopIt(bool isRunning){
  if (isRunning == HIGH) {
    digitalWrite(pwmInputOfTheDCMotor, HIGH);
    playCarMusicStart();
    changeToNeutral();
  } else {
    digitalWrite(pwmInputOfTheDCMotor, LOW);
    changeToRedLight();
  }
}

```

The function `changeTheDirectionOfTheDCMotor()`:

```
void changeTheDirectionOfTheDCMotor(bool changeDirection) {
  digitalWrite(input1OfTheDCMotor, changeDirection);
  digitalWrite(input2OfTheDCMotor, !changeDirection);
}

```

The function `changeToRedLight()`:

```
void changeToRedLight() {
  servo.write(0);
  delay(15);
}

```

The function `changeToNeutral()`:

```
void changeToNeutral() {
  servo.write(40);
  delay(15);
}

```

The function `playCarMusicStart()`:

```
void playCarMusicStart(){
  if (isEngineSoundsPlaying == HIGH) {
    for (int thisNote = 0; thisNote < (sizeof(carSounds_note)/sizeof(int)); thisNote++) {
      int noteDuration = 1000 / carsounds_duration[thisNote];
      tone(4, carSounds_note[thisNote], noteDuration);
      int pauseBetweenNotes = noteDuration * 2.70;
      delay(pauseBetweenNotes);
      noTone(4);
      isEngineSoundsPlaying = LOW;
    }
  }
}

```

# Solution

## A big thanks to @ratchet freak

I need to change my `loop()` to this:

```
void loop() {
  int valueOfTheSensor = analogRead(tempSensor);
  float voltage = (valueOfTheSensor / 1024.0) * 5.0;
  float temp = (voltage -0.5) * 100;
  if (temp >= 20.00) {
    isRunning = LOW;
  }
  changeTheStateOfTheLights(isRunning);
  startTheDCMotorAndStopIt(isRunning);
  changeTheDirectionOfTheDCMotor(changeDirection);

  playCarMusicStart();
}

```

I also needed to change the `PlayCarMusicStart()`:

```
void playCarMusicStart(){
  if (isEngineSoundsPlaying == HIGH && currentNote < (sizeof(carSounds_note)/sizeof(int))) {
      int noteDuration = 1000 / carsounds_duration[currentNote];
      tone(4, carSounds_note[currentNote], noteDuration);
      int pauseBetweenNotes = noteDuration * 2.70;
      delay(pauseBetweenNotes);
      noTone(4);
      currentNote++;
   } else {
      currentNote = 0;
   }
}

```

And the least is to set the `isEngineSoundsPlaying` equal to `HIGH`, I changed the function `startTheDCMotorAndStopIt()` for:

```
void startTheDCMotorAndStopIt(bool isRunning){
  if (isRunning == HIGH) {
    isEngineSoundsPlaying = HIGH;
    digitalWrite(pwmInputOfTheDCMotor, HIGH);
    changeToNeutral();
  } else {
    isEngineSoundsPlaying = LOW;
    digitalWrite(pwmInputOfTheDCMotor, LOW);
    changeToRedLight();
  }
}

```

# Answer
> 2 votes
The key will be to split up `playCarMusicStart` and instead create a `playCarMusicStep` that will do just one iteration of the loop and returns. Call it every time in `loop()` akin to blinkWithoutDelay.

In playCarMusicStart you then setup the playing state so it starts playing correctly.

And when you need to stop it you then stop the music by setting the correct variable.

---
Tags: arduino-uno, motor, interrupt, piezo, loop
---


# Question
Title: Arduino Mega not recognized by device manager
My lab partner and I are working on a project for school and we are using an Arduino Mega 2560 for prototyping. The board was working just fine until, out of nowhere, the board was not being recognized at all. I tried reinstalling the IDE but still it does not work. I checked to see if the Arduino driver was installed, but the board does not show up in the device manager. Also, the L LED on the board does not light up at all. Attached are photos to help understand the problem.

If someone could help, it would be much appreciated. Thanks.

# Answer
hey i had the same problem, i am thinking because i installed atmel studio and then this started happening, I then downloaded arduino from the microsoft store,(no change) then i restarted the pc, now its compiling and uploaded normally but still does not show the name of the board that is connected just shows lets say just COM22 with out saying what board
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Comparing button presses to correct sequence
I am creating a memory game with the Arduino. It has four buttons, each for a different colored led. The leds will blink in a random sequence and either fail or add another light in the next sequence if the user presses the correct buttons. I have also attached an lcd screen to late implement a score tally.

Right now, the welcome lights display and the sound is working fine, but when the sequence starts, it will act as though I am pressing a button and proceed through the fail light method. I think the last method is causing this issue where I am comparing the button pressed to the sequence.

I would appreciate any help!

This is essentially my wiring just with different pins chosen:

# Answer
I found that I did not need the pull down resistors for each button since I had declared the pinMode for each button to be INPUT\_PULLUP. So instead of the schematic above, I took out the resistors for the buttons and instead wired one side of the buttons to ground.
> 1 votes

# Answer
The problem might be that you do not debounce the buttons. When you press a button, there is somehwere between fully pressed and not pressed (or backwards) a state there it 'bounces', e.g. you get lots of state transitions, resulting in seeing a button pressed twice or many times instead of once.

Check the debounce example in the default Arduino Tutorial
> 0 votes

---
Tags: arduino-uno, led, button
---


# Question
Title: STM32 VGA Output - don't understand why lines are jagged
I am using "blue-pill" STM32F103C8 (http://wiki.stm32duino.com/index.php?title=Blue\_Pill) to create VGA output. I am connecting PB6 to VSync, PB0 to HSync, and PA0 to red using 278 Ohm resistor.

I don't understand why the lines are "jagged", like in the picture:

I would appreciate any input.

By the way, my real code is more complex and can display 256x192 with 64 colors. Since this board has 20K memory, I am using separate areas for pixels and colors, like Sinclair ZX (https://en.wikipedia.org/wiki/ZX\_Spectrum\_graphic\_modes).

This is my code:

```
// interrupt handlers
void EndVBackPorch();
void ShockAbsorber();

volatile uint8 *GPIO_ODR;
volatile int vflag = 0; /* When 1, can draw on the screen */

void setup()
{
  pinMode(PB6, PWM); // VSync
  pinMode(PB0, PWM); // HSync

  // PA0..PA5 set to OUTPUT with max speed 50 MHz
  GPIOA->regs->CRL = 0x88333333;
  GPIO_ODR = (volatile uint8_t *)&GPIOA->regs->ODR;

  // 640 x 480 @ 60 Hz (Standard, pixel clock frequency 25.17 MHz)
  //InitHSync(false, 2287, 275, 400);
  //InitVSync(false, 525, 2, 35 + 48);

  // 640 x 480 @ 60 Hz (non-standard, pixel clock frequency 24.0 MHz)
  InitHSync(true, 2376, 264, 370);
  InitVSync(true, 505, 5, 10 + 74);
}

void loop()
{
    // Everything happens in the interrupts
}

void InitVSync(
  bool isNegative,
  int wholeFrame,
  int syncPulse,
  int startDraw)
{
  HardwareTimer timerVSync(4);

  timerVSync.pause();
  timerVSync.setPrescaleFactor(1);
  timerVSync.setOverflow(wholeFrame); /* Vertical lines */

  // VSync on pin PB6
  timer_oc_set_mode(timerVSync.c_dev(), TIMER_CH1,
            isNegative ? TIMER_OC_MODE_PWM_2 : TIMER_OC_MODE_PWM_1, TIMER_OC_PE);
  timerVSync.setCompare(TIMER_CH1, syncPulse);

  timerVSync.setChannelMode(TIMER_CH4, TIMER_OUTPUT_COMPARE);
  timerVSync.setCompare(TIMER_CH4, startDraw);
  timerVSync.attachInterrupt(TIMER_CH4, EndVBackPorch);

  // Slave mode Gated, triggered by TIM3
  timerVSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_SMS);
  timerVSync.c_dev()->regs.adv->SMCR |= ((uint16_t)TIMER_SMCR_SMS_GATED);
  timerVSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_TS);
  timerVSync.c_dev()->regs.adv->SMCR |= (uint16_t)TIMER_SMCR_TS_ITR2;

  //nvic_irq_set_priority(NVIC_TIMER4, 1);

  timerVSync.refresh();
  timerVSync.resume();
}

void InitHSync(
  bool isNegative,
  int wholeLine,
  int syncPulse,
  int startDraw)
{
  HardwareTimer timerShockAbsorber(2);
  timerShockAbsorber.pause();
  timerShockAbsorber.setPrescaleFactor(1);
  timerShockAbsorber.setOverflow(wholeLine);

  timerShockAbsorber.setChannelMode(TIMER_CH1, TIMER_OUTPUT_COMPARE);
  timerShockAbsorber.setCompare(TIMER_CH1, 0);

  timerShockAbsorber.setChannelMode(TIMER_CH2, TIMER_OUTPUT_COMPARE);
  timerShockAbsorber.setCompare(TIMER_CH2, startDraw - 12);
  timerShockAbsorber.attachInterrupt(TIMER_CH2, ShockAbsorber);

  // Master mode, TIM_TRGOSource_Enable
  bitSet(timerShockAbsorber.c_dev()->regs.adv->SMCR, TIMER_SMCR_MSM_BIT);
  timerShockAbsorber.setMasterModeTrGo(TIMER_CR2_MMS_ENABLE);

  timerShockAbsorber.refresh();

  HardwareTimer timerHSync(3);
  timerHSync.pause();
  timerHSync.setPrescaleFactor(1);
  timerHSync.setOverflow(wholeLine);

  // HSYNC on pin PB0
  timer_oc_set_mode(timerHSync.c_dev(), TIMER_CH3,
            isNegative ? TIMER_OC_MODE_PWM_2 : TIMER_OC_MODE_PWM_1, TIMER_OC_PE);
  timerHSync.setCompare(TIMER_CH3, syncPulse);

  timerHSync.setChannelMode(TIMER_CH4, TIMER_OUTPUT_COMPARE);
  timerHSync.setCompare(TIMER_CH4, startDraw);
  timerHSync.attachInterrupt(TIMER_CH4, Draw);

  // Slave mode Trigger, triggered by TIM2
  timerHSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_SMS);
  timerHSync.c_dev()->regs.adv->SMCR |= ((uint16_t)TIMER_SMCR_SMS_TRIGGER);
  timerHSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_TS);
  timerHSync.c_dev()->regs.adv->SMCR |= (uint16_t)TIMER_SMCR_TS_ITR1;

  // Master mode, TIM_TRGOSource_Update
  bitSet(timerHSync.c_dev()->regs.adv->SMCR, TIMER_SMCR_MSM_BIT);
  timerHSync.setMasterModeTrGo(TIMER_CR2_MMS_UPDATE);

  nvic_irq_set_priority(NVIC_TIMER3, 0);

  timerHSync.refresh();

  // Starts timerHSync as well
  timerShockAbsorber.resume();
}

void EndVBackPorch()
{
  vflag = 1;
}

void ShockAbsorber()
{
  // Wait for interrupt
  __asm__ volatile("wfi \n\t" :::);
}

void Draw()
{
  if (!vflag)
  {
    return;
  }

  noInterrupts();

  __asm__ volatile(

    "  mov r0, #3        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #0        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #3        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #0        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #3        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #0        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"

    :
    : [odr] "r"(GPIO_ODR)
    : "r0");

  interrupts();
}

```

# Answer
I found a similar issue when I developed code to display on a VGA monitor.

The reason for the slight jitter is that when an interrupt fires, it can't stop in the middle of an instruction. So there are potentially one or two extra clock cycles before the interrupt is processed.

Those clock cycles would account for the slight jaggedness on the right. The way to avoid that is to go to sleep between horizontal lines (idle sleep mode). This wakes up instantly, but the important thing is it wakes up at the start of an instruction cycle, so you don't get a one or two cycle delay.

I can't see any sleeping in your code, and I'm not sure if your STM32F103C8 would compensate for that, but certainly it is worth trying.

I can't see a "main" loop, presumably it doesn't do much until an interrupt fires.

My main loop is this:

```
void loop()
  {
  // sleep to ensure we start up in a predictable way
  sleep_mode ();
  doOneScanLine ();
 }  // end of loop

```

Note the sleep which ensures that it starts the drawing at the same time each time (of course the interrupt will take time, but at least it takes the same time every scan line).
> 3 votes

---
Tags: pwm
---


title: Arduino JSON foreach loop

text:
# Question
Title: Arduino JSON foreach loop
I'm trying to extract values using ArduinoJson. The values aren't fixed, therefore I need to use the foreach loop.

I'm trying this, but I can't seem to use the values like I could with.

```
root["0"]["value"].as<const char*>();

```

Here is my code.

```
void loop(){
  int httpCode = http.GET();
  if(httpCode > 0) {
    // if Get request has processed
    if(httpCode == HTTP_CODE_OK) {
      payload = http.getString();
    }
    if(payload.length() > 0) {
      Serial.println(payload);
      JsonObject& root = jsonBuffer.parseObject(payload);
      if (!root.success()) {
        Serial.println("parseObject() failed");
        jsonBuffer.clear();
      } else {
        Serial.println("Data Fetched");
        for(JsonPair& node : root) {
          Serial.print("0 State: ");
          Serial.println(*node);
        }
        http.end();
      }
    } else {
      Serial.println("Payload Empty");
    }
  }
}

```

Please avoid any missing brackets. Thanks in advance.

```
[{"state": true, "value": 10}, {"state": false, "value": 8}, {"state": false, "value": 5}, {"state": false, "value": 13}]

```

# Answer
I found another way around the solution.

Idk if this is helpful to anyone but the problem was that I had an unknown number of nodes I wanted to loop through, Example of the json format above.

```
void loop(){
int httpCode = http.GET();
  if(httpCode > 0) {
    // if Get request has processed
    if(httpCode == HTTP_CODE_OK) {
          payload = http.getString();
      }
      if(payload.length() > 0){
          JsonArray& nodes = jsonBuffer.parseArray(payload);
          if (!nodes.success()) {
            Serial.println("parseObject() failed");
            jsonBuffer.clear();
          }else{
            int node_length = nodes.size();
            for(int i=0; i<node_length;i++){
              Serial.printf("node-%i\nValue : ",i );
              String value = nodes[i]["value"].as<const char*>();
              String state = nodes[i]["state"].as<const char*>();
              Serial.println(value);
              Serial.print("State : ");
              Serial.println(state);
            }
            http.end();
        }
    }else{
      Serial.println("Payload Empty");
    }
  }

  jsonBuffer.clear();
  delay(8000);
}

```
> 2 votes

---
Tags: arduino-ide, nodemcu, json
---


# Question
Title: JSN-SR04T-2.0 with NodeMCU not starts after reset or reconnect usb power
I have bought a NodeMCU (1.0) and a JSN-SR04T waterproof ultrasonic sensor compatible with HC-SR04.

If I upload my program to NodeMCU it works but sometimes it measures a wrong distance - it is an another question, but it may connect to this question.

If I press the reset button my application not starts or if it is unplugged and plugged in to usb power it not starts.

If I unplug the ultrasonic sensor 3.3V and ground it starts.

It starts with the following code:

```
const int trigPin = D4;
const int echoPin = D3;

void flashLed() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(400);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(100);
}

void setup() {

  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  flashLed();
  Serial.begin(115200);
  flashLed();
  delay(10);

  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
  }
  Serial.println("");
  Serial.println("WiFi connected");

  server.begin();

  Serial.println("Web server running. Waiting for the ESP IP...");
  delay(10000);

  Serial.println(WiFi.localIP());

  digitalWrite(LED_BUILTIN, HIGH);

}

```

I have uploaded the full source code to github project:

https://github.com/kisdaniel/nodemcu-wif-http-HC-SR04/blob/master/HomeDashboardUltrasonicHttp.ino

Why it not starts?

**UPDATE:**

I have make a minimal version of code to reproduce the problem:

```
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(2000);
}

```

Wiring:

```
Node MCU 3.3V -  Vcc (ultrasonic sensor)
Node MCU GND  -  GND (ultrasonic sensor)
Node MCU D4   -  Trigger (ultrasonic sensor)
Node MCU D3   -  Echo (ultrasonic sensor)

```

# Answer
> To enable ESP8266 firmware flashing GPIO0 pin must be pulled low before the device is reset. Conversely, for a normal boot, GPIO0 must be pulled high or floating.

The D3 pin is equivalent GPIO0. For a normal boot, GPIO0 must be pulled high or floating while powering up or resetting the module. After that (normal boot), you can use the output for other purposes.

You can use a different output or try to use a pull-up resistor for the D3.
> 3 votes

# Answer
I had the same problem. Eventually I worked out what was going wrong with the information at "Startup Guide for ESP8266 NodeMCU WeMos"

It explains - "Using GPIO0 (D3), GPIO2 (D4) and GPIO15 (D8) can be bit tricky. There are certain reasons, for example, GPIO0 (D3) and GPIO2 (D4) are pulled HIGH (PULL-UP Resistor) for normal start up of ESP8266 while GPIO15 (D8) is pulled LOW (PULL-DOWN Resistor). It is recommended to not use these pins as INPUT."

The problem happens when one of the NodeMCU pins that goes HIGH in startup - D3 and D4 - is connected to the "ECHO" pin of the JSN-SR04T sensor while the supply and ground pins are connected. The "ECHO" pin has low impedance and reduces the voltage on either D3 or D4 to about 1 Volt. This prevents the NodeMCU from rebooting.

The problem doesn't happen if the D3 or D4 pin is connected to the "TRIGGER" pin of the JSN-SR04T sensor because it has high impedance and doesn't reduce the voltage on the NodeMCU pin connected to it.

This matches what the article I found recommended: using D3, D4 and D8 for OUTPUT is OK, but it is recommended to not use them for INPUT.
> 0 votes

---
Tags: nodemcu, hc-sr04
---


# Question
Title: Creating public instance of class in another class's initialization
I'm using several TM1637 displays to create timers, so I decided to make a Timer class. Every time I initialize an instance of the Timer class, I want it to create an instance of the TM1637Display class. So I started out with this, but the display object can't be accessed from within updateDisplay.

```
class Timer {
public:
    Timer(uint8_t CLK, uint8_t DIO) {
        TM1637Display display(CLK, DIO);
        ...
    }
    void updateDisplay() {
        ...
        display.setSegments(displayData);
    }
}

```

And if I do this I get the compile time error `In constructor 'Timer::Timer(uint8_t, uint8_t)': src\main.cpp:16:37: error: no matching function for call to 'TM1637Display::TM1637Display()'`

```
    TM1637Display display;
    Timer(uint8_t CLK, uint8_t DIO) {
        display(CLK, DIO);
        ...
    }

```

What should I try? Maybe make an empty pointer before the display instance is created with a public scope, assign the pointer to the display instance, then hand the updateDisplay function the pointer? That seems really convoluted.

# Answer
As it's now in the first example, it's local variable in Timer constructor.

In the second one you have to use member initializer list in constructor as there is no default constructor in your display class.

```
class Timer {
public:
    Timer(uint8_t CLK, uint8_t DIO)
    : display(CLK, DIO) // constructor's initializer list
    {
        ...
    }
    void updateDisplay() {
        ...
        display.setSegments(displayData);
    }

    // member variable:
    TM1637Display display;
}

```
> 4 votes

---
Tags: c++, object-oriented
---


# Question
Title: How to use use 2 or more HC-SR04 sensors as one single sensor?
I'm new to Arduino and this is my problem. I need to track an object in a room. For now I have placed 3 sensors on the edges of each axis (x, y, z), where the x axis will the line between the east and the west walls of the room, the y axis will be the north and south walls of the room, and the z axis will be the ceiling of the room.

I have written code to get the output as x, y, z coordinates. But since the HC-SR04 has no horizontal range it can only track objects in its line of sight. Due to this I'm not able to fulfil my requirements. So I thought if I could couple up an array of HC-SR04s together to work as one sensor I can get more horizontal range.

Is this possible using an Arduino Uno R3? If it's possible, please guide me through it.

# Answer
> 1 votes
You can try attaching your HC-SR04 sensor to a servo, then you will have a range of detecting an object in 180 degree span.

Of course you will have to make modifications to fit your purpose. Using three ultrasonic sensors with each of them having their own servo of 180 degree range will surely increase accuracy. To get started visit here. Hope this was what you were looking for.

(Image credits: Dejan Nedelkovski)

---
Tags: arduino-uno, arduino-ide
---


# Question
Title: Run python in Windows OS installed in micro SD card which is read by Arduino microcontroller board
I have a python code which runs in my computer with Windows operating system. The code reads some images as input, extends some cognitive services apis from Microsoft azure and finally give an audio output. I would like to run this code on an independent device, for which I am thinking to have a motherboard like Arduino (I can use raspberry pi, but it's a small project and I don't want to invest that much). However being an amateur in this genre, I have some questions and would really like if someone could help.

I want the system to have an independent processing power, with the operating system loaded in a micro SD card. I do not want to connect Arduino with my pc and run the code from there. It will not make any sense since the PC/laptop is already able to do the work, what would I need Arduino for?

Can someone please tell me if it is possible to have an operating system installed in a micro SD card (bootable) and have it inserted in the Arduino board so that I can run the python code within the SD card?

# Answer
With some Arduino boards, yes. You want a board like the Yun (unfortunately retired now, but there are probably others similar) which has a MIPS SoC on it that runs Linux (specifically OpenWRT). The OS is installed into the SoC, but there is an SD card slot that will allow you to read your code.

An alternative is a Yun shield (available from third parties, such as the Dragino Yun Shield). This turns any Uno-like Arduino into a Yun. Of course, you can run it without any Arduino attached if you so wish to wire it manually.

However, with all these, you're getting into the price bracket of a Raspberry Pi, so you may as well do it properly and just get a Raspberry.
> 2 votes

---
Tags: arduino-uno, sd-card, python, windows
---


title: MQ135 Gas Sensor Calibration

text:
# Question
Title: MQ135 Gas Sensor Calibration
I have bought a MQ135 gas sensor. I have read online from multiple sources that a calibration/warm-up period of between 12-24hrs is required for the sensor to give its most accurate readings. I currently have it attached to one of my UNO's just spitting out Analog readings to the Serial monitor and seems (just after an hour!) to have settled at a reading of 50 which it has stayed at now for a period of around 20 minutes. My questions surrounding this process really are:

1. What is the point in doing this process if when a project that uses this sensor is powered off for some number of hours? Will you have to let it warm-up/calibrate again before having faith in the readings?
2. How do I actually identify PPM for a gas such as C02? Is there some form of constant that I should be comparing the reading obtained to or something similar?

# Answer
> 0 votes
By my opinion, it is impossible to calibrate these solid electrolyte based sensors. I achieved best results when I measured the CO2 level in 5 minute intervals, by heating the sensor for 100 seconds. I cant remember these times precisely, but by heating and allowing it to cool down I was able to get quite reliable results. But then I realized that the sensor is getting some offset. If you want to do a two-point calibration, you can put it to fresh air, it should read about 0.04%, or you can breathe directly to the sensor for a short while and it shoud read 4%. But I highly recommend using NDIR CO2 sensor, those are used in home air monitoring devices.

---
Tags: arduino-uno, sensors, calibration
---


title: Check if servo is connected to arduino

text:
# Question
Title: Check if servo is connected to arduino
```
#include <Servo.h>

Servo esc;

void setup(void) {
  esc.attach(7, 1000, 2000);

  if (esc.attached()) {
    // this always runs
    // even if there's no servo connected to pin 7
  }
}

```

I've written code kind of like the above.

The problem is that after using `Servo.attach` the method `Servo.attached` always returns true, even if there's nothing in the pin that I've attached to.

How can I check if the pin, in this case `7`, actually has a wire in it?

# Answer
> 1 votes
You cannot check, if a servo or a wire is physically connected to the pin, without extra effort. The Servo library uses Timer interrupts to create a PWM signal for the servo on the used pin. For this the pin is configured as OUTPUT and cannot measure anything except of the value, that was written to it. In most servo motors the PWM input is high impedance, so that the current draw from the PWM pin is very low.

To solve your problem you have 2 possibilities:

1. Use a special connector, that has 2 extra pins with a mechanical switch, which gets closed, when the connector is put together. (The same principle as in SD card holders)
2. Measure the current, that the servo uses through it's power supply pins, with a suitable circuit.

---
Tags: arduino-uno, servo
---


# Question
Title: This error is shown continuosly after first time it compiles successfully
I got this error:

Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"

```
Multiple libraries were found for "LiquidCrystal.h"  Used: C:\Program
Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal
Not used:
C:\Users\siddh\OneDrive\Documents\Arduino\libraries\libraries readlink
C:\Users\siddh\OneDrive\Documents\Arduino\libraries\SimpleDHT\SimpleDHT.cpp:
The system cannot find the file specified. Error compiling for board
Arduino/Genuino Uno.

This report would have more information with "Show verbose output
during compilation" option enabled in File -> Preferences.

```

This is the code i use:

```
//We'll start by adding our libraries

 #include <LiquidCrystal.h>

 #include <SimpleDHT.h>

//Declaring digital pin no 6 as the dht11 data pin

int pinDHT11 = 6;
SimpleDHT11 dht11;

//Declaring the lcd pins

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
// Don't forget to choose 9600 at the port screen

  Serial.begin(9600);

//Telling our lcd to start up

  lcd.begin(16, 2);

}

void loop() {

  //These serial codes are for getting readings on the port screen aswell as the LCD display, since they'll offer us a more detailed interface

  Serial.println("=================================");
  Serial.println("DHT11 readings...");
  delay(2000);

  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;

  //This bit will tell our Arduino what to do if there is some sort of an error at getting readings from our sensor
  if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("No reading , err="); Serial.println(err);delay(1000);
    return;
  }

  Serial.print("temp: ");
  Serial.print((int)temperature); Serial.print(" Celcius, ");
  Serial.print("humidity:");
  Serial.print((int)humidity); Serial.println(" %");

  //Telling our lcd to refresh itself every 0.75 seconds
  lcd.clear();

 //Choosing the first line and row

 lcd.setCursor(0,0);

//Typing Temp: to the first line starting from the first row
  lcd.print("Temp: ");

//Typing the temperature readings after "Temp: "
  lcd.print((int)temperature);

//Choosing the second line and first row
  lcd.setCursor(0,1);

//Typing Humidity(%): to the second line starting from the first row
  lcd.print("Humidity(%): ");

//Typing the humidity readings after "Humidity(%): "
  lcd.print((int)humidity);

  delay(750);
}

```

# Answer
There is a bug that causes this error when you use the Arduino IDE with files located under OneDrive.

The simplest solution is to move any files that will be used with the Arduino IDE out of OneDrive to any other convenient location on your computer. It looks like you have your sketchbook folder located in the OneDrive so you will want to change that via the Arduino IDE's **File \> Preferences \> Sketchbook location**. The Arduino IDE does not automatically move the files from the previous sketchbook folder to the new folder so you will need to either move any files to the new sketchbook folder or else reinstall them.

There are some possible workarounds if you want to to continue using the Arduino IDE with OneDrive listed in the issue report: https://github.com/arduino/arduino-builder/issues/254
> 2 votes

# Answer
I have had this problem as well and I concur with per1234 that the solution (for now) is that you have to move your sketches out of the OneDrive folder.

You used to be able to have your sketches within OneDrive (I did for many years). Since release 1.6.6 things have changed and you can no longer compile files that you once used to be able to compile inside a OneDrive folder.

In addition to per1234's great answer (ie move the sketches outside of the Ondrive folder) there are 2 other options. Firstly you could download and install version 1.6.5 which was before the Arduino Builder was incorporated. The other option is to use the Beta V1.9.0 avalable from the Beta Channel.

---

**UPDATE:**

The issue with OneDrive folders has been resolved as of version 1.8.6.

https://www.arduino.cc/en/Main/ReleaseNotes

> ARDUINO 1.8.6 2018.08.23
>
> \[ide\]
>
> * Updated arduino-builder to 1.4.0:
>     + parallel build (improve compile speed)
>     + better reuse of already compiled files
>     + **Windows: fixed build for sketch stored under OneDrive cloud folders**

Simply update to a newer version of the Arduino IDE and you will be able to compile and upload your sketch.
> 1 votes

---
Tags: arduino-uno
---


title: Arduino 16x2 LCD Black Boxes

text:
# Question
Title: Arduino 16x2 LCD Black Boxes
I hooked up a 16x2 Arduino compatible LCD yesterday and made sure all the connections were according to the program and the schematics provided all over the web. My contrast is adjusted perfectly but the problem is that there are black boxes on the top line while the lower one is empty.

I know this question has been asked many times but no one has answered the question other than saying, "Check your contrast pin". I'm using the default sample code provided in the Arduino IDE. HELP!

Regards.

# Answer
> 3 votes
I have done some Googling across the web and it turns out that this can be caused by a couple of things:

* Incorrect wiring.
* Wiring of LCD backwards (ie 1 to 16 and 16 to 1).
* Faulty wiring (ie broken cables & dry joints).
* Incorrect initialization of the LCD.
* Buggy software.
* Damaged screen.

The LCD screen that you have is a based on the Hitachi HD44780 chipset. It is the most common interface for text-based LCDs. It can be identified by the 16-pin interface. I2C is the next most common interface and is distinguishable as it has a 4-pin (sometimes 5-pin) interface.

Lets assume that your screen isn't damaged. From the details in your question, it sounds like your contrast is working just fine. The list above can be shrunk to just 2 things: bad wiring and/or bad code. Lets eliminate both of those by using known working software and known working circuit.

Arduino has an LCD library with example programs. Details for this library, including a **wiring diagram**, can be found over at the Arduino site in the Reference section. I use these example sketches to test my wiring connections before I write my own program. I recommend using the Autoscroll example.

Schematic:  These diagrams are from the Arduino Autoscroll page. **I highly suggest that you read this page thoroughly.**

The code can be easily uploaded into your Arduino, through the IDE, by going into `File` \> `Examples` \> `LiquidCrystal` \> `AutoScroll`, then `Sketch` \> `Upload`.
You should see the sketch print the characters 0 to 9 on the top line (with autoscroll off), then moves the cursor to the bottom right (turns autoscroll on,) and prints the characters 0 to 9 on the bottom line, but as it prints each character the display should move one to the left.

If you get this example program to work then you know that you have a working LCD and also that your wiring is OK as well.

# Answer
> 2 votes
Are you using an LCD driver board that has 4 connections between it and the arruino, or do you have the LCD directly connected?

If using a driver board, download Liquid Crupystal Library here

Ten make sure to have the library running in that startup code.

# Answer
> 1 votes
Connect your RW pin to Ground.

# Answer
> 1 votes
Alright guys thanks for everything! I've found the solution. It was a bad solder.

# Answer
> 0 votes
Your contrast is just fine. The black boxes indicate that your LCD isn't correctly initialized. Poor connections and / or bad code is to blame. So focus your debugging there.

---
Tags: lcd
---


# Question
Title: Arduino Uno with Kubuntu 16.04: Unable to enumerate device
I try to connect my arduino uno R1 in order to program the atmega8u2 but I am not able to do so. When I run `sudo dfu-programmer atmega8u2 erase` I get the following results:

```
dfu-programmer: no device present.

```

So in order to diagnose it i run `dmeesg` with the following results:

```
 [ 1395.921051] usb 2-3: new full-speed USB device number 30 using
 xhci_hcd [ 1396.041175] usb 2-3: device descriptor read/64, error -71
 [ 1396.269135] usb 2-3: device descriptor read/64, error -71 [
 1396.497109] usb 2-3: new full-speed USB device number 31 using xhci_hcd [ 1396.617169] usb 2-3: device descriptor read/64, error -71
 [ 1396.845177] usb 2-3: device descriptor read/64, error -71 [
 1397.073163] usb 2-3: new full-speed USB device number 32 using xhci_hcd [ 1397.073371] usb 2-3: Device not responding to setup
 address. [ 1397.281311] usb 2-3: Device not responding to setup
 address. [ 1397.489086] usb 2-3: device not accepting address 32,
 error -71 [ 1397.609173] usb 2-3: new full-speed USB device number 33
 using xhci_hcd [ 1397.609382] usb 2-3: Device not responding to setup
 address. [ 1397.817200] usb 2-3: Device not responding to setup
 address. [ 1398.025176] usb 2-3: device not accepting address 33,
 error -71 [ 1398.025235] usb usb2-port3: unable to enumerate USB
 device

```

Do you know fellows how to make my arduino connect back into my computer?

Furthermore II forgot to mention my user is in `dialout` group as `groups` gnu/linux command mentions:

```
pcmagas adm dialout cdrom sudo dip plugdev lpadmin sambashare libvirtd docker wireshark

```

PS: That thing happened after soldering the resistor into the board so it is a new problem.

# Answer
You should solder the resistor (in case you do not have the skills I reccomend doing into a proffessional, a professional close to me managed to solder it with a cost about 5 euros) and then hardware reset the atmega8u2 the documentation mentions. For quick reference just look over in this image:

In the `dmesg` you will see similar the same or message:

```
[ 1544.679504] usb 1-6: new full-speed USB device number 42 using xhci_hcd
[ 1544.808341] usb 1-6: New USB device found, idVendor=03eb, idProduct=2ff7
[ 1544.808350] usb 1-6: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[ 1544.808356] usb 1-6: Product: Arduino Uno DFU

```

Then look on the similar question for R1 boards or in case you have a newer board then follow the instructions mentiones to the documentation.
> 1 votes

---
Tags: arduino-uno, linux, ubuntu
---


# Question
Title: How does Peggy2 drive rows with 74HC154 Decoder?
Trying to program Evil Mad Scientist's Peggy 2 board without their Library. The board drives a LED Matrix with

* Source 74HC154 Decoder
* Sink STP16CPSO5 LED Sink Driver

Schematic

What has me confused is the 74HC154 Outputs can only have one output set to Low at at time. See table below. This means all but one row is "on". Isn't this backwards? Shouldn't all outputs be low except one that is high? Selecting what row you want on, rather than selecting what row you want off. It looks more like the 74HC154 is a Sink. Thanks.

# Answer
> 1 votes
If you look into the datasheet of 74HC154, you can see that each output has an Active Low State. Also in the schematic, the leds row part use a pnp transistor (see page two). As so, they will be active if the input is low.

> This means all but one row is "on". Isn't this backwards?

Since they are PNP, the only active row is the one with Low value and the current of that row is sink through the selected column(s) in the STP16CPS05

---
Tags: arduino-uno, led, shift-register, multiplexer
---


title: Arduino Uno board with male header pins

text:
# Question
Title: Arduino Uno board with male header pins
I am currently working on a project that would greatly benefit from an arduino uno board with male headers soldered on instead of the female connectors. My question is hence extremely simple, yet I was not able to find an answer myself. Are there uno formfactor boards out there, with male header pins. I have found versions without headers for other boards, but not for the uno. Since I have already designed and 3d printed an enclosure that fits the uno and want to lower the overall height this seems like the easiest way to achieve this.

# Answer
I often unsolder the female connectors to solder wires directly. I would simply unsolder then and solder male headers in their place.
> 2 votes

---
Tags: arduino-uno
---


title: don't save on tab

text:
# Question
Title: don't save on tab
Ok, I made some changes to the code and I wish they would see it.

At the moment the program has a bug, it is not saving the contents of the txt file to the table, can someone give some lights?

```
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
int x = 1;
String files, memo, memo1;
int sizef = 0;
int sizef1 = 0;
int sizef2 = 0;
int y=0;
int z=1;
int d=0;
int u=0;
int r=0;
int l=0;
int indice_objetos=0;

struct objeto_celeste_s {
  char nome[20];
  float ar;
  float dec;
  };
typedef struct objeto_celeste_s objeto_celeste;

void rightfunction (int rate){
 char cmd[] = {'P',2,16,36,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);

}

void leftfunction (int rate){
 char cmd[] = {'P',2,16,37,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);

}

void upfunction (int rate){
 char cmd[] = {'P',2,17,36,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);
}

void downfunction (int rate){
 char cmd[] = {'P',2,17,37,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);
}

File file;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

char * list[]={"1.Modo Normal    ","2.Modo Teste    "};

// read the buttons
int read_LCD_buttons()
{

adc_key_in = analogRead(0);
if (adc_key_in > 1000) return btnNONE;
if (adc_key_in < 50)   return btnRIGHT;
if (adc_key_in < 250)  return btnUP;
if (adc_key_in < 400)  return btnDOWN;
if (adc_key_in < 450)  return btnLEFT;
if (adc_key_in < 650)  return btnSELECT;

return btnNONE;  // when all others fail, return this...
}

void setup() {

 Serial.begin(9600);
 Serial1.begin(9600);
 while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
 }
 Serial.println ("Welcome!");
 Serial.println ("Efectue o alinhamento do telescópio, depois carregue no botão UP.");
 lcd.begin (16,2);
 lcd.setCursor (0,0);
 lcd.print ("Efectue alinham.");
 lcd.setCursor (0,1);
 lcd.print ("E carregue UP");
 delay (1000);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
}

void loop() {

lcd_key = read_LCD_buttons();  // read the buttons

 switch (lcd_key)  // depending on which button was pushed, we perform an action
 {
   case btnRIGHT:
     if (z==0){
      rightfunction (9);
      Serial.println ("Andar para a direita a uma velocidade de 9.");
      z=1;
      r=1;
      break;
     }

     if (r==1){
      rightfunction (0);
      Serial.println ("Parar de andar para a direita.");
      z=0;
      r==0;
      break;
     }

   case btnLEFT:
     if (z==0){
      leftfunction (9);
      Serial.println ("Andar para a esquerda a uma velocidade de 9");
      z=1;
      l=1;
      break;
     }

     if (l==1){
      leftfunction (0);
      Serial.println ("Parar de andar para a esquerda.");
      z=0;
      l=0;
      break;
     }

   case btnUP:
      if (z==0){
       upfunction (9);
       Serial.println ("Andar para cima a uma velocidade de 9");
       z=1;
       u=1;
       break;
     }

      if (u==1){
       upfunction (0);
       Serial.println ("Parar de andar para cima.");
       z=0;
       u=0;
       break;
     }

      if(x==1){
        x--;
        lcd.clear ();
        lcd.setCursor(0,0);
        lcd.print(">");
        lcd.println(list[0]);
        lcd.setCursor(0,1);
        lcd.print (" ");
        lcd.println(list[1]);
        break;
      }
   case btnDOWN:
      if (z==0){
       downfunction (9);
       Serial.println ("Andar para baixo a uma velocidade de 9.");
       z=1;
       d=1;
       break;
      }

      if (d==1){
       downfunction (0);
       Serial.println ("Parar de andar para baixo.");
       z=0;
       d=0;
       break;
      }

      if(x==0){
        x++;
        lcd.clear ();
        lcd.setCursor(0,0);
        lcd.print(">");
        lcd.println(list[1]);
        lcd.setCursor(0,1);
        lcd.println("                ");
        break;
      }

   case btnSELECT:
    if (x==2){
      Serial.println ("Bem-vindo ao Modo Manual.");
      lcd.clear ();
      lcd.print ("Modo Manual");
      lcd.setCursor (0,1);
      lcd.print ("Reset p/mod GoTo");
      Serial.println ("Pressione os botões UP, DOWN, RIGHT ou LEFT no arduíno para controlar o telescópio.");
      z=0;
      break;
    }

    if (x==0){
    lcd.clear ();
    lcd.print ("Modo Normal");
    Serial.println ("Selecionou o modo normal!");
    delay (1000);
    if (SD.exists("objectos.txt")) {
    Serial.println("O ficheiro 'objetos' foi encontrado!");
    lcd.clear ();
    lcd.setCursor (0,0);
    lcd.print ("Modo Normal");
    delay (1000);

    file = SD.open("objectos.txt", FILE_READ);
    if (file) {
    while (file.available()) {
     String line = file.readStringUntil('\n');
     sizef++;
    }
    } else {//se houver erro a abrir o ficheiro
     Serial.println("Erro a abrir o ficheiro 'objectos.txt'.");
    }
     Serial.print ("Contados ");
     Serial.print (sizef);
     Serial.println (" objetos no ficheiro objectos.txt.");

     objeto_celeste *tab =(objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));

     if (tab==NULL){
      lcd.clear ();
      lcd.print ("Erro a alocar memoria");
      Serial.println ("Erro a alocar memória");
      while (1){ };

     }else{

      Serial.print ("Memória alocada para ");
      Serial.print (sizef);
      Serial.println (" objectos.");
      lcd.setCursor (0,1);
      lcd.print ("Alocados ");
      lcd.print (sizef);
      lcd.print (" obj");
      }

      file.close();

    char * line1 =(char*) malloc(sizeof(String));

    file = SD.open("objectos.txt", FILE_READ);

    if (file) {
     Serial.println ("Carregando informação para a memória:");

     while (file.available()) {

     char c = file.read ();

     if (c=='\n'){

     char * justafun = strtok (line1," "); //divide em tokens

     while (justafun !=NULL){

      switch (indice_objetos) {
          case 1:
            tab[sizef2].ar = atof(justafun); //to float

            indice_objetos++;
            break;
          case 2:
            tab[sizef2].dec = atof(justafun);

            sizef2++;
            indice_objetos=0;
            break;
          case 0:
            strcpy(tab[sizef2].nome, justafun); //this one is a string
            indice_objetos++;
            break;
      }
      justafun = strtok (NULL, " ");
      }

      if (line1==NULL){
      Serial.print ("Falhou na linha ");
      Serial.println (sizef2);

     }else{
       line1="";
    }
   }else{
     sprintf(line1, "%s%c", line1, char(c));
     }
    }
   }
  file.close ();

  delay (1500);

  if (Serial1.available()) {
   int inByte = 'V';
   Serial1.write (inByte);
   int inByte1 = 'e';
   Serial1.write (inByte1);
  }

delay (1000);

Serial.println ("Tabela ordenada alfabeticamente:");

 x=2;
 delay (1000);
 lcd.clear ();
 Serial.println ("Modo GoTo. Para entrar em Modo Manual pressione o botão select.");
 lcd.print ("Modo GoTo");
 lcd.setCursor (0,1);
 lcd.print ("Slct p/Modo Man.");

 }else {

    Serial.println ("O ficheiro 'objetos' não existe.");
    lcd.clear ();
    lcd.print ("Erro nao encontrado");
    delay (2000);
    while(1) { };
  }
 }

    if (x==1){
      lcd.clear ();
      lcd.print ("Modo Teste");
      Serial.println ("Selecionou o modo teste!");
      delay (2000);

      if (SD.exists("teste.txt")) {
      Serial.println("O ficheiro 'teste.txt' foi encontrado!");
      lcd.clear ();
      lcd.setCursor (0,0);
      lcd.print ("Modo Teste");
      lcd.setCursor (0,1);
      lcd.print ("Ficheiro encontrado");
      delay (2000);

      file = SD.open("teste.txt", FILE_READ);

      if (file) {
      while (file.available()) {//ler o ficheiro
      String line = file.readStringUntil('\n');
      sizef++;
     }

      files = "Contados " + String (sizef) + " objetos no ficheiro teste.txt.";
      Serial.println (files);
      objeto_celeste *tab = (objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));
      memo = "Alocados " + String (sizef) + " obj  ";
      memo1= "Memória alocada para " + String (sizef) + " objetos.";

      if (tab==NULL){
        lcd.clear ();
        lcd.print ("Erro alocar memoria");
        Serial.println ("Erro a alocar memória");
        while (1){ };

      }else{

        Serial.println (memo1);
        lcd.setCursor (0,1);
        lcd.print (memo);
      }

      file.close();

     } else {//se houver erro a abrir o ficheiro
      Serial.println("Erro a abrir o ficheiro 'teste.txt'.");
     }

    }else {
      Serial.println ("O ficheiro 'teste.txt' não foi encontrado.");
      lcd.clear ();
      lcd.print ("Erro nao encontrado");
      delay (2000);
      while(1) { };
    }
   }
     break;

   case btnNONE:
      break;
 }
 delay (200);
}

```

This is the content of txt.

P.S. I know the "Ar" section is wrong, it's just for test purposes.

```
Syrius 6.45 -16.42
Deneb 20.41 +45.16
Capella 5.16 +45.59
Rigel 5.14 -8.12
Vega 18.36 +38.47
Alnitak 05.40 -01.56

```

# Answer
> 1 votes
Maybe I have found your problem:

Before reading the file you are allocating memory with `malloc()` and creating a pointer `line1` to it. `malloc()` takes the number of bytes to allocate as a parameter. Here you use `sizeof(String)`, which would give you the size of a new String object. But the point of the String object is, that is dynamically allocates the memory for the string of characters. So the created buffer `line1` is most likely to small for your text. You have to allocate the buffer with the maximum number of characters of all lines.

But you should consider, that using `malloc()` or any other dynamic memory allocation is dangerous on microcontrollers, which don't have much RAM. If you are doing it to often you get heap fragmentation, essentially making swiss cheese of your heap. If possible you should use a statically declared array or at least allocate memory only once during the lifecycle of your program.

---
Tags: debugging
---