title: RTC resets when power is off

text:
# Question
Title: RTC resets when power is off
I have a few RTC modules with a batteries. All of them have this same issue with my project.

They work fine when connected via USB. But if I disconnect the power then reconnect they reset to Jan 1 2000.

I've read several posts about similar problems. But, none seem to apply.

Here is my code:

```
#include <SFE_MicroOLED.h>  // Include the SFE_MicroOLED library
#include <SPI.h>
#include <SD.h>
#include "Wire.h"
#include <RTClib.h>
RTC_DS1307 RTC;
#define BUTTON_PIN       0 // Button
#define LONGPRESS_LEN    25  // Min nr of loops for a long press
#define DELAY            20  // Delay per loop in ms

enum { EV_NONE=0, EV_SHORTPRESS, EV_LONGPRESS };

boolean button_was_pressed; // previous state
int button_pressed_counter; // press running duration

byte zero = 0x00; //workaround for issue #527

char* modes[]={"Walk", "Bike", "Subway", "Train", "Bus", "X-Bus", "Waiting", "Other"};
byte mode=0;
int modeRead;

// Chip Select for SD
#define chipSelect 10

//MicroOLED oled(PIN_RESET, PIN_DC, PIN_CS);
MicroOLED oled(9, 8, 5); // SPI declaration

void setup()
{
    pinMode(BUTTON_PIN, INPUT);
    digitalWrite(BUTTON_PIN, HIGH); // pull-up
    Serial.begin(9600);
    button_was_pressed = false;
    button_pressed_counter = 0;

    SD.begin(chipSelect);

    Wire.begin();
    RTC.begin();
    //RTC.adjust(DateTime(__DATE__, __TIME__));

    oled.begin();    // Initialize the OLED
    oled.clear(PAGE);     // Clear the screen
    oled.setFontType(1);  // Set font to type 0
    oled.setCursor(0, 0); // Set cursor to top-left
    oled.println(F("co'mute"));
    oled.display();  // Display what's in the buffer
}

int handle_button()
{
    int event;
    int button_now_pressed = !digitalRead(BUTTON_PIN); // pin low -> pressed

    if (!button_now_pressed && button_was_pressed) {
        if (button_pressed_counter < LONGPRESS_LEN)
            event = EV_SHORTPRESS;
        else
            event = EV_LONGPRESS;
    }
    else
        event = EV_NONE;

    if (button_now_pressed)
        ++button_pressed_counter;
    else
        button_pressed_counter = 0;

    button_was_pressed = button_now_pressed;
    return event;
}

void printDate ()
{
    oled.clear(PAGE);     // Clear the screen
    oled.setFontType(0);  // Set font to type 0
    oled.setCursor(0, 0); // Set cursor to top-left

    DateTime now = RTC.now();

    oled.print(now.year(), DEC);
    oled.print('/');
    oled.print(now.month(), DEC);
    oled.print('/');
    oled.print(now.day(), DEC);
    oled.print(' ');
    oled.print(now.hour(), DEC);
    oled.print(':');
    if (now.minute()<10) {
        oled.print("0");
    }
    oled.print(now.minute(), DEC);
    oled.print(':');
    if (now.second()<10) {
        oled.print("0");
    }
    oled.print(now.second(), DEC);
    oled.println();
    oled.setFontType(1);  // Set font to type 0
    oled.println(modes[mode]);
    oled.display();   // Display what's in the buffer (splashscreen)
}

void writeFile()
{
    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    // If the file is available, write to it:
    if (dataFile) {
        DateTime now = RTC.now();
        //print the date EG   3/1/11 23:59:59
        dataFile.print(now.year(), DEC);
        dataFile.print('/');
        dataFile.print(now.month(), DEC);
        dataFile.print('/');
        dataFile.print(now.day(), DEC);

        printDate ();
        oled.print("*SAVED*");
        oled.display();
        delay(3000);
    }
}

void loop()          // run over and over again
{
    // handle button
    boolean event = handle_button();

    // do other things
    switch (event) {
        case EV_NONE:
        oled.print(".");
        break;

        case EV_SHORTPRESS:
        oled.print("S");
        //modeRead = analogRead(0);    // read the value from the sensor
        writeFile();
        break;

        case EV_LONGPRESS:
        oled.print("L");
        break;
    }

    static int counter = 0;
    if ((++counter & 0X016) == 0) {
        printDate ();
    }
    modeRead = analogRead(A0);    // read the value from the sensor
    delay(DELAY);

    int c=1020/(sizeof(modes)/sizeof(modes[0]));
    for (int i = 0; i < c; i++) {
        if (i*c < modeRead && (i+1)*c < modeRead) {
            mode = i;
        }
    }
}

```

In this diagram the "pressure sensor" is really a OLED that operates via MOSI and MISO.

# Answer
The RTC board has a battery holder and requires the button battery to be fitted in order to retain the time and date value. As shown in the Datasheet, this battery is for the RTC chip only.

The Adafruit board requires a CR1220 button battery.

The Adafruit webpage mentions the following:

> Note: This product does not come with a CR1220 coin cell battery.

(Providing that it works when the Arduino is powered up) It sounds as if the battery for the RTC is either:

* not present
* not connected (not inserted correctly or not making proper connection)
* inserted upside down
* a track on the PCB is broken or shorted
* the battery is flat

The battery should be inserted so that the flat + side is UP. I suggest that you use a DMM to measure the RTC battery voltage at the RTC IC. Place your +ve probe on pin 3 of the IC and the -ve probe on pin 4. It should read slightly above 3.0 Volts.

I also recommend that you disconnect all of the other periferals so that you just have the RCT connected to the Arduino. Then use a known working program such as the one in the Adafruit tutorial to verify that your RTC is working correctly. You should be able to disconnect the USB and then reconnect it and find that the RTC is still holding the correct time.

RTC DS1307 Datasheet
Adafruit RTC Product
Adafruit RTC Tutorial
> 1 votes

---
Tags: time, rtc
---


# Question
Title: How to Sort Elements of Array in Arduino Code?
/How Can i Sort this Array with Descending Order? I need Simplest syntax to use in iterative code.

```
lt[6]={35,15,80,2,40,110};

```

# Answer
As mentioned in the comments, `qsort` is a good option:

```
// qsort requires you to create a sort function
int sort_desc(const void *cmp1, const void *cmp2)
{
  // Need to cast the void * to int *
  int a = *((int *)cmp1);
  int b = *((int *)cmp2);
  // The comparison
  return a > b ? -1 : (a < b ? 1 : 0);
  // A simpler, probably faster way:
  //return b - a;
}

void setup() {
  // The array
  int lt[6] = {35, 15, 80, 2, 40, 110};
  // Number of items in the array
  int lt_length = sizeof(lt) / sizeof(lt[0]);
  // qsort - last parameter is a function pointer to the sort function
  qsort(lt, lt_length, sizeof(lt[0]), sort_desc);
  // lt is now sorted
}

void loop()
{
}

```
> 7 votes

---
Tags: arduino-uno, arduino-mega, arduino-ide, arduino-nano
---


title: ESP 8266-01 Library

text:
# Question
Title: ESP 8266-01 Library
I've just bought two of these wifi modules in the hope of setting up some sort of sensor network. Please could somebody recommend a good library for the arduino.

Cheers

# Answer
You don't need a library. At the most basic level you fire AT command to it via a serial connection, but that's like using a Ferrari to go grocery shopping once a week.

It has a 80/160MHz processor 10 digital and one analog port (although you got the version where only one digital port is exposed). You can program it through the Arduino IDE (You need to go to the board manager to download the BSP for it). Then like Majenko says, it should be talking to the Arduino (over I2C or SPI) and treating the Arduino is the GPIO expander.
> 2 votes

---
Tags: arduino-uno, esp8266, arduino-nano, library
---


# Question
Title: How to work with arduino softwareserial communication using HC-05?
This is my first project using bluetooth module HC-05.i am using two of this module.one is with arduino nano(slave) and another one is with arduino uno(master).I have paired them through AT commands . for testing,i was giving a pulse in pin 7 on nano.if there is a pulse,then slave will send character "1".if not then it will send "0".

in UNO there is an LED connected with pin 13.if master receives '1',then LED will on and if recieves '0',LED will remain off. here is my source code ----------

slave code=\>

master code=\>

the Arduino IDE isn't showing any bug,but code is not working at all.though,i am giving pulse in pin 7 on NANO, the LED in pin 13 on UNO is remaining off.i am at aloss now.please help me as soon as possible..

# Answer
Don't put pictures of you code in a post again, makes life very difficult!

The problem is the first line of the slaves loop

```
loop()
{
    if (slave.available()>0)  // Here is the bug
....

```

So If the "slave" serial port has data available to read then write data. The master never writes to the slave so the slave never has any data to write, so your slave never sends any data and your master never reads any data.

In short remove that line and it will work.
> 0 votes

---
Tags: arduino-uno, bluetooth, arduino-nano, softwareserial, hc-05
---


title: Array Addressing

text:
# Question
Title: Array Addressing
Is it possible to use a name instead of a number to address an array? I was reading about enum lists and thought it might be possible. ie int array\[3\] = {something, somethingElse, somethingMore\]

array\[second\] =\> somethingElse

I am asking as I have an array looking after flags for several functions and would like to be able to use the function name instead of a number to address the array.

```
bool flag[6] = {1, 1, 1, 1, 1, 0}; // Power, Jump 3, Jump 7, Fade 3, Fade 7, Pause active

```

# Answer
No, but you can use a `struct`:

```
struct flags {
    uint8_t power;
    uint8_t jump3;
    uint8_t jump7;
    .... etc ....
};

struct flags myFlags;

myFlags.power = 1;
if (myFlags.jump3) {
    .... stuff ....
}

```

Or you can continue to use a simple numeric array and assign names to the numbers, either with `#define`, `const` variables, or an `enum`.

```
enum flags {
    power, jump3, jump7, fade, fade7, pause
};

bool flag[6] = {1, 1, 1, 1, 1, 0};

flag[power] = 1;
if (flag[jump3]) {
    .... whatever ....
}

```
> 3 votes

---
Tags: arduino-ide, array, ide, code-optimization
---


# Question
Title: Controlling a LED array from Arduino NANO
I have a project Im currently busy with that I need a lot of help with.

What I want to do i create a flat 8x12 grid of LEDs and be able to control each individual LED independently from the others. I want to make "animations" for it (for now Im jut gona patch HIGH LOW through to the LEDs, but Im planning on making a full fledged program later on).

I saw guys on youtube creating LED cubes using the "column and row" technique, but Im not sure if that will work for me because I want to control each one independantly. Thats when my search led me to Shift Registers. Which will work best?

How would I manage the current for all the LEDs

Thank for taking the time to listen to a n00b like me :D

# Answer
> 1 votes
You can control a grid of 8x12 LEDs using 8+12 (20) GPIO pins if your chosen board has that many. If it doesn't you can use a 3-to-8 decoder (e.g., 74HC138 - active low outputs, ideal for driving a P-channel MOSFET for the anodes of each row) to reduce that to 3+12 (15). You could cascade two of them and rotate the arrangement so it's 8+4 (12), though that's harder to do (although you can get 4-to-16 decoders too which would be simpler).

For multiplexing you don't want to use shift registers, they're too slow for smooth updates. You also don't want to drive each LED individually when you're working with that quantity, it just gets unmanageable and the power consumption would be excessive.

If you wanted to use shift registers you could use one (or multiple cascaded) to clock a single bit along them to select each row in turn. You could then reduce the pin requirement to 8+3 (clock + data + reset) though that gets a little more complex to program.

And yes, before you ask, you can address individual LEDs in the grid with multiplexing. You select one individual row (or column, but I'll just say row from now on) at a time and tell it which LEDs to light on that row, then move to the next row. This is why using a 3-to-8 decoder is good because it can only activate one row at a time which is what you want when multiplexing.

# Answer
> 0 votes
There are a lot of ways to do what you want to do. Wiring them up individually would be one possibility those find a chip with that many pins can be a challenge

You can use shift registers, either statically or dynamically.

You can also use display drivers, like 7219 or the ht variants.

...

End of the day it will depend on your application and constraints it has to live under.

---
Tags: led, arduino-nano
---


# Question
Title: How to know positive and negative in breadboard
I have this breadboard, and there is no indication on it about what is positive/negative on it.

In comparison, this other breadboard (pic from the internet) DOES have indications:

Can anyone give me a hint ?

# Answer
> 10 votes
You decide which rails are positive and which are negative when you connect them to the + an - from your power supply or battery.

A breadboard isn't polarised *per se*. It's just a bunch of cross-connections inside a perforated plastic case. No active or passive components inside.

Some manufacturers may choose to paint indications regarding where to connect the positive and negative rails, but those are just a guideline. Ultimately it's your choice, you're free to connect + and - wherever you want in the breadboard rails.

# Answer
> 3 votes
As gre\_gor said. A simple breadboard contains of rows and columns of connections but sometimes for convenience manufacturer marks or prints Positive and Negative symbol along the row as they are usually used to power a circuit

# Answer
> 0 votes
Connections in the two strips along the edge running top to bottom in your image are connected (in the way you have the image placed) top to bottom. So, all pins are connected to each other in each of those rows. Within the inner secions, the connections are (in your image) across from one side to the other.

You decide how you want the power supply cable to be connected to your breadboard, just becasue there's no indicators means that they simply haven't drawn any coloured lines on the breadboard. You can draw red and black lines on however you wish.

---
Tags: power, android, prototype, voltage, breadboard
---


# Question
Title: unexpected primary-expression before ';' token
I'm new to the Arduino world and am working on a sketch to run a servo up and down with a spdt switch. My code is :

```
include #include<Servo.h>
int pos = 0;

Servo myservo;
void setup() {
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  myservo.attach(9);
}
void loop() {
  if (digitalRead(2) == HIGH && pos < 180) {
    pos++;
    servo.write(pos);
    delay(15);
  }
  if (digitalRead(3) == HIGH && pos > 0) {
    pos--;
    servo.write(pos);
    delay(15);
  }
}

```

When I compile I get the "unexpected primary-expression before ';' token" error with exit status 1.

What am I doing wrong???

# Answer
> 4 votes
**1)** You should be using:

```
myservo.write(pos);

```

instead of

```
servo.write(pos);

```

for all of your methods.

**2)** Change:

```
include #include<Servo.h>

```

to

```
#include <Servo.h>

```

**This code only verifies when it is run on certain boards\*, so make sure you are using one of those boards.Good luck and welcome to the Arduino world!:)**

\*Verify that your board will work, I know Mega, Uno and Nano will function properly.

P.s. Here is the whole code in correct format:

```
#include <Servo.h>

int pos = 0;

Servo myservo;
void setup() {
 pinMode(2, INPUT);
 pinMode(3, INPUT);
 myservo.attach(9);
}
void loop()
{
  if ( (digitalRead(2) == HIGH) && (pos < 180)) {
    pos++;
    myservo.write(pos);
    delay(15);
  }
  if ( (digitalRead(3) == HIGH) && (pos > 0)) {
    pos--;
    myservo.write(pos);
    delay(15);
  }
}

```

---
Tags: servo
---


# Question
Title: error: 'analogRead' was not declared in this scope
I am using Codeblocks with arduino IDE to simulate the control of a stepper motor, and the errors "'analogRead' was not declared in this scope" and "'A0' was not declared in this scope" keep popping. The code follows:

```
#include <Stepper.h>

const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0;  // number of steps the motor has taken

void setup() {
}

void loop()
{
    int sensorReading = analogRead(A0); //ERROR

    int motorSpeed = map(sensorReading, 0, 1023, 0, 100);

    if (motorSpeed > 0)
    {
        myStepper.setSpeed(motorSpeed);
        myStepper.step(stepsPerRevolution / 100);
    }
}

```

EDIT: Sorry I forgot to mention it clear, but I do not own a board, that's why I'm trying to simulate it on PC.

# Answer
// yours code looks Ok, but i think problem is with Arduio IDE setting. Go to the "Tool \> Boards...." in arduino IDE and make it sure that you have selected the right option of Arduino module. Mean it is same as you are using in hardware?
> -1 votes

---
Tags: analogread
---


# Question
Title: Uno - measure the voltage, NOT connecting GND
I'm trying to use an Arduino Uno, to measure the Voltage over a Resistor in a circuit. I guess the usual way would be to connect GND to one side of the Resistor and the AD0 Pin to the other end, and scale the (0..1023) to (0..5V).

The problem is however, that connecting the GND to one side of the Resistor affects the circuit. Since the GND of Arduino is also connected to a Servo Driver (and other stuff), Some of the power that was supposed to be consumed by my Resistor, is now consumed by the parallel circuits.

Is there any way to measure the Voltage over the resistor without using GND?

# Answer
If I understand the description correctly, neither side of the resistor is at ground potential. There's a wide gamut of methods of dealing with this, for example using a differential ADC unit, or using an instrumentation amplifier ahead of a single-ended ADC. But perhaps the simplest method is to use two ADC channels, one attached to each end of the resistor, with ADC ground connected to some common reference point. Measure both voltages and take their difference .
> 6 votes

# Answer
Why you are using AD0 pin for analog read? use A0-A7 for Arduino mega and A0- A5 for arduino uno case for reading of analog values. For more detail study the voltage devider and you will understand the problem more easily. As i understand there is no need to use ground.
> -1 votes

---
Tags: arduino-uno, analogread, adc
---


title: Variable was not declared in this scope

text:
# Question
Title: Variable was not declared in this scope
When I compile this code I get a error: 'currentState' was not declared in this scope.

The code:

```
enum state: int
 {
  NOTREADY,
  WAITSTARTUP,
  WAITSECRET,
  REVEALSECRET
 }

state currentState; <---- Error

const int BUTTONPIN = 4;
const int ROTARYPIN = A0;

void setup()
{
  //Open Serial Monitor for debugging purposes
  Serial.begin(9600);

  //Configure the pins
  pinMode(BUTTONPIN, INPUT);
  pinMode(ROTARYPIN, INPUT);

  //Initialise the LCD
  lcd.begin(16, 2);

  //Assume that the current state is wait for start up signal

  currentState=WAITSTARTUP;
}

```

# Answer
> 4 votes
You have missing semicolon after the enum:

```
enum state: int
 {
  NOTREADY,
  WAITSTARTUP,
  WAITSECRET,
  REVEALSECRET
 };  // <-- here

```

# Answer
> 0 votes
//go the Tools \> Boards and check that you have selected the right option of your hardware? your remaining code is almost ok. But remember to add semicolon ";" sign at end every coding line.

```
  enum state: int{NOTREADY,WAITSTARTUP,WAITSECRET,REVEALSECRET};
  state currentState; //<---- Error

  const int BUTTONPIN = 4;
  const int ROTARYPIN = A0;

  void setup()
  {
    //Open Serial Monitor for debugging purposes
    Serial.begin(9600);

    //Configure the pins
    pinMode(BUTTONPIN, INPUT);
    pinMode(ROTARYPIN, INPUT);

    //Initialise the LCD
    lcd.begin(16, 2);

    //Assume that the current state is wait for start up signal

    currentState=WAITSTARTUP;
  }

```

---
Tags: arduino-uno
---


title: ST7735 display with esp32

text:
# Question
Title: ST7735 display with esp32
I have edited the adafruit ST7735 library so that it supports esp-32.I made some edits in Adafruit\_ST7735.h file. which are as follows.

The code works fine but I had expected the screen to work faster with esp-32(due to higher processing power) but it does not do that.

I checked the time for fill screen operation for esp-32 and arduin mega. They come out to be almost the same. (around 0.12 seconds). Can anyone explain why this is happening and can I increase the speed?

# Answer
The ST7735 uses SPI to communicate. It will always be slow compared to parallel connected screens.

The fact that you appear to be using bitbanged SPI (manually toggling IO pins) makes it even slower.

The fastest you will be able to get with that screen will be to use hardware SPI instead (which most likely limits which pins you can use - I am not familiar with the ESP32 though) but that will still be somewhat slow.

If you want really high speed screen updates then you will need a parallel interface screen, ideally a 16-bit parallel interface screen. However, for that you need around 20 IO pins to drive it.
> 1 votes

---
Tags: adafruit, tft, esp32
---


# Question
Title: Understanding schematics: resistors attached to Attiny85 pins V-USB
I'm currently trying to create my own Attiny85 usb thumb(to mimic an joystick). I understand that I have to limit the voltage on the attiny's pins that are connected to the D+/- pins from the usb. In various schematics there are some pull-up resistors used with some zener diodes(that will drop the voltage that exceeds 3.3 V).(taken from insidegadgets)

# Question:

# #1

I am sure most computers these days have a voltage regulator built-in them(everyone can just plug the usb into the 220v socket...).Can then I just avoid an regulator?(as other schematics incorporate in them)

# #2

Why is there one pull-up resistor on pin2 only(pin2 from usb)? That is D- pin.

# #3

An resistor can already limit the voltage.Why need zener diodes?(eg.: attiny85 draws ~7mA at 16.5 MH and 5v. And we need a resistance that would drop the 5v from one pin-considered in HIGH state- to 3.3v...that is a 1.2v drop.So R=1.2/0.007=171 ohms.That resistor attached to the attiny **would** produce a 1.2 drop).

# #4

There are two zener diodes attached to D+/- pins. What's with the resistors?(R2/R1) They limit..the current(didn't know the pc is so sensitive..)?

# Answer
> I am sure most computers these days have a voltage regulator built-in them(everyone can just plug the usb into the 220v socket...).Can then I just avoid the regulator?

If you have a 5v supply, as in a USB connection, and you want to run off 5v, then you do not need any regulator.

> Why is there one pull-up resistor on pin2 only(pin2 from usb)? That is D- pin.

Because only that pin needs pulling up to indicate the presence of a device on the USB bus.

> An resistor can already limit the voltage.Why need zener diodes?(eg.: attiny85 draws ~7mA at 16.5 MH and 5v. And we need a resistance that would drop the 5v from one pin-considered in HIGH state- to 3.3v...that is a 1.2v drop.So R=1.2/0.7=1.71 ohms).

You can only use a resistor to drop a fixed voltage of you have a fixed current. The current you quote is the chip's supply current, not the GPIO current, which you cannot know or predict. Also, if you did use a resistor it would operate both ways and the 3.3V coming in would also be reduced so the MCU will not be able to read the data.

Even if you did know the current you would find it was very small so a huge resistor would be needed, which would induce intolerable amounts of noise. It would also violate the USB specifications.

> There are two zener diodes attached to D+/- pins. What's with the resistors?(R2/R1) They limit..the current(didn't know the pc is so sensitive..)?

They are to protect the ATTiny's IO pins. Without those the zener diodes will sink way too much current from the IO pins and damage them. They also act partially as termination resistors for the USB bus (which should be 20Ω).
> 0 votes

---
Tags: usb, attiny, voltage-level, resistor, voltage
---


title: How to Read Voltage Level?

text:
# Question
Title: How to Read Voltage Level?
I want to read voltage level by my Arduino board please help in this regard. I am using this syntax.

```
volts = analogRead(A3);    // read the input pin
Serial.println(volts)

```

# Answer
//use this syntax and add ; sign at end of each line and try to read voltage level via voltage divider circuit.

```
volts = analogRead(A3);    // read the input pin
Serial.println(volts);             // debug value

```
> 0 votes

# Answer
First off you need to convert your signal's units from analog -\> voltage. Do this by using the following equation. I've modified your code so you can copy and paste it into your IDE.

```
float volts = analogRead(A3) * ( 5.0 / 1024.0) ;

```

Hope this helps! Good luck!
> 1 votes

---
Tags: arduino-uno, arduino-mega, programming, analogread, digital-analog-conversion
---


# Question
Title: Can removing lines of code destroy a motor driver and make it catch fire?
I am making a pid line follower robot. So I was tinkering with code to optimize my line follower when i removed two lines of code unknowingly. As soon as I uploaded my code and started the line follower, 4 mosfets on my motor driver smoked and burst into blue flames. Bought a new one and same outcome. Interestingly, The ones corresponding to the left motor alone had this outcome as I removed " return Motorspeed1" and " return MotorSpeed2" from the function corresponding to the left motor. Heres the code :

```
signed int MotorSpeed = 70;
int MotorSpeed1, MotorSpeed2;
int MotorFunc(signed int a, signed int b){
   if(a >= -10 && a < 0)
   {
      b = -b;
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_dir_m1, HIGH);
      digitalWrite(_dir_m2, LOW);
      MotorSpeed1 = MotorSpeed + b;
      MotorSpeed2 = MotorSpeed + b;
      MotorSpeed1 = constrain(MotorSpeed1, 0, 255);
      MotorSpeed2 = constrain(MotorSpeed2, 0, 255);
      analogWrite(_pwm_m1, MotorSpeed1);
      analogWrite(_pwm_m1, MotorSpeed2);
      return MotorSpeed1;
      return MotorSpeed2;
   }
   if (a < 10 && a > 0)
   {
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_brk_m2, LOW);
      digitalWrite(_dir_m1, LOW);
      digitalWrite(_dir_m2, HIGH);
      MotorSpeed1 = MotorSpeed+ b;
      MotorSpeed2= MotorSpeed+ b;
      MotorSpeed1 = constrain( MotorSpeed1, 0, 255);
      MotorSpeed2= constrain( MotorSpeed2, 0, 255);
      analogWrite( _pwm_m1,  MotorSpeed1);
      analogWrite( _pwm_m2, MotorSpeed2);
      return MotorSpeed1;
      return MotorSpeed2;
   }

   else
   {
      digitalWrite(_brk_m1, LOW);
      digitalWrite(_brk_m2, LOW);
      digitalWrite(_dir_m1, HIGH);
      digitalWrite(_dir_m2, HIGH);
      MotorSpeed1 = MotorSpeed+ b;
      MotorSpeed2 = MotorSpeed - b;
      MotorSpeed1 = constrain(MotorSpeed1, 0, 255);
      MotorSpeed1 = constrain(MotorSpeed2, 0, 255);
      analogWrite( _pwm_m1, MotorSpeed1);
      analogWrite( _pwm_m2, MotorSpeed2);
      return MotorSpeed1;
      return MotorSpeed2;
   }

}

```

And i called this function in the code using :

```
    MotorFunc(a,b)

```

This code ran just fine, But when i removed the return functions from the first if condition, I destroyed 2 motordrivers, Is this possible? Edit: I am updating the whole code:

The main code tab :

```
     int _dir_m1 = 2;
     int _pwm_m1 = 3;
     int _brk_m1 = 4;
     int _brk_m2 = 5;
     int _pwm_m2 = 6;
     int _dir_m2 = 7;

     int sen1 = A4;
     int sen2 = A3;
     int sen3 = A2;
     int sen4 = A1;
     int sen5 = A0;
     signed int Error = 0;

     int Kp = 20;
     int Ki = 0;
     int Kd = 0;

     void setup() {
     pinMode(_dir_m1, OUTPUT);
     pinMode(_pwm_m1, OUTPUT);
     pinMode(_brk_m1, OUTPUT);
     pinMode(_dir_m2, OUTPUT);
     pinMode(_pwm_m2, OUTPUT);
     pinMode(_brk_m2, OUTPUT);

     pinMode(sen1, INPUT);
     pinMode(sen2, INPUT);
     pinMode(sen3, INPUT);
     pinMode(sen4, INPUT);
     pinMode(sen5, INPUT);

     }

     void loop(){

     signed int a = Sensors();
     signed int b = PID(a);
     MotorFunc(a,b);
       }

```

And pretty much it. I am leaving out PID as Its not required along with error selection.

The setup is - Arduino mega connected to 5 ir sensors 12v 9ah battery 500rpm 12v motors johnsons and the motor driver 20 amp 20v-30v

Motor driver link with specs

# Answer
It all depends on how the circuit works and how it is controlled. A basic H-bridge looks like this:

Normally you have one MOSFET from each side turned on and one turned off - so for example Q1 and Q4 on to make the motor turn one way, or Q2 and Q3 to make it turn the other. Turning on Q2 and Q4 for example would make the motor "brake".

However, if it is possible for your driver to turn on both Q1 and Q2 at the same time, or Q3 and Q4, then they will form an almost dead short circuit and massive amounts of current will try to flow. At that point things will start to get hot and the Magic Smoke™ will try and escape.
> 3 votes

# Answer
It isn't possible to say arbitrarily that removing the statements could or could not cause the drivers to burn out. What does the caller do with the value returned by your function? With the return statement removed, the value returned to the caller is unknown. Is there any value which, if returned to the caller, could set the conditions for driver burn-out?
> 0 votes

---
Tags: programming, motor, pid, mosfet, heat
---


title: Conversion of Arrays into Matrix?

text:
# Question
Title: Conversion of Arrays into Matrix?
I'm going through problem in Arduino code. I have three Arrays and want to convert them into a matrix. I have tried hard but couldn't solve issue.

```
float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float Loadbase,Loadshift;

void setup() {
    for (int i=0;i<24;i++){
        Loadbase={lb1[i],lb2[i],lb3[i]};
    }
}

void main() {
}

```

# Answer
Two dimensional arrays in C++ (directly):

```
float matrix[3][24] = {
    {1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730},
    {1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450},
    {500,500,600,600, 380.3005 ,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250}
};

```

Two dimensional array indirectly (array of pointers):

```
float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float * matrix[3] = {lb1, lb2, lb3};

```

If you want two dimensional array with copies of lb1/lb2/lb3:

```
float matrix[3][24];
for (int i = 0; i < 24; ++i) {
    matrix[0][i] = lb1[i];
    matrix[1][i] = lb2[i];
    matrix[2][i] = lb3[i];
}

```

Btw: you were saying something about "mistakes" if I split definition on more lines, but guess what: `float lb3[24]={500,500,600,600, 380.3005 ,3155`. This is a valid float number, but you have only 23 items then.

If you use at least space as a number separator, it can't be even compiled:

```
float lb3[24] = { 500, 500, 600, 600, 380. 3005, 3155, 530, 400,  400, 600, 350, 250, 250, 500, 500, 250, 1655, 1655, 3155, 2130, 250, 150, 250};

```
> 1 votes

# Answer
Check this code with slight amendments:

```
float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};

void setup() {
int loadbase[3][24] = {{lb1}, {lb2}, {lb3}};
void main()
{}

```
> 0 votes

---
Tags: arduino-uno, arduino-mega, arduino-ide, arduino-leonardo
---


title: Can't cast char to unsigned char?

text:
# Question
Title: Can't cast char to unsigned char?
```
byte RSV_Resp_test[3] = {'a', 'b', 0};
Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));

```

produces the error

```
error: invalid cast from type 'byte {aka unsigned char}' to type 'char'
Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));
                                                      ^

```

How can this be an ill-formed cast? I just need to print the value as a ascii character, not as a number.

# Answer
```
Serial.println(static_cast<char>(RSV_Resp_test[1]));

```

works. I still don't understand why the reinterpret\_cast errors out.
> 0 votes

---
Tags: serial
---


# Question
Title: Communicating between two arduino terminal using Xbee
I have 2 Arduinos, mounted with Xbee Shield and Xbee S1 module on each. One arduino is mounted on car chassis while another is connected with PC. Our AIM is to send signal from the arduino connected on PC and the motor will be controlled by the Arduino connected on car chassis. Here is the code of the arduino connected with PC:

```
char msg= "";
void setup(){
 Serial.begin(9600);}

void loop(){
 msg=Serial.read();
 serial.println(msg);
}

```

Here is the code of the Arduino on car chassis:

```
char msg = ' ';
int motorA1 = 2;
int motorA2 = 3;
int motorB1 = 4;
int motorB2 =5;

void setup() {
  pinMode(motorA1, OUTPUT);
  pinMode(motorA2, OUTPUT);
  pinMode(motorB1, OUTPUT);
  pinMode(motorB2, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  while(Serial.available()>0){
  msg=Serial.read();
  switch(msg){
   case 'f':Serial.println("Forward");break;
   case 'b':Serial.println("Backward");break;
   case 'r':Serial.println("Right");break;
   case 'l':Serial.println("Left");break;
   case 's':Serial.println("Stop");break;
 }
if(msg=='f'){
  digitalWrite(motorA1,HIGH);
  digitalWrite(motorA2, LOW);
  digitalWrite(motorB1,HIGH);
  digitalWrite(motorB2,LOW);
  Serial.println("Running Forward");
  }
if(msg=='b'){
  digitalWrite(motorA1,LOW);
  digitalWrite(motorA2,HIGH);
  digitalWrite(motorB1,LOW);
  digitalWrite(motorB2,HIGH);
  }
if(msg=='s'){
  digitalWrite(motorA1,LOW);
  digitalWrite(motorA2,LOW);
  digitalWrite(motorB1,LOW);
  digitalWrite(motorB2,LOW);
  }
if(msg=='r'){
  digitalWrite(motorA1,HIGH);
  digitalWrite(motorA2, LOW);
  digitalWrite(motorB1,LOW);
  digitalWrite(motorB2,LOW);
  }
if(msg=='l'){
  digitalWrite(motorA1,LOW);
  digitalWrite(motorA2,LOW);
  digitalWrite(motorB1,HIGH);
  digitalWrite(motorB2,LOW);
  }
}
}

```

Now our next AIM is to send back a feedback from car to the Arduino terminal of PC, e.g. if we are giving 'f' as a input and we get a reply 'Running Forward' on the next line. What line of code should we incorporate for that?

# Answer
//your code looks almost ok. The thing that i am feeling wrong is that arduino at the PC end. It should communicate with PC and 2nd arduino at the same time. So use arduino mega or "#include " library to avail extra Serial at this end if you are using arduin uno. Your code will be like this..

```
char msg= "";

void setup(){
Serial.begin(9600);
Serial1.begin(9600)//<----error
}

void loop(){
 msg=Serial.read();
 serial1.println(msg);//<- - -error
}

```
> 1 votes

---
Tags: motor, xbee, arduino-motor-shield
---


title: If Else Alternative

text:
# Question
Title: If Else Alternative
I've written a function that heavily relies on the If / Else statement but I feel it's a very beginner way to achieve functionality. Are there any better ways to achieve the same functionality?

Code:

```
void jumpThree() // Update from left then right
{
  if (effectCounter[0] < tiles) // Right, first tile
  {
    Serial << flag[6] << "\t";
    Serial << newRed[0] << " " << newGreen[0] << " " << newBlue[0] << "\t";

    if (flag[6] == 1)
    {
      oldRed[0]   = (tileBuffer[effectCounter[0]] & 0xff0000) >> 16;
      oldGreen[0] = (tileBuffer[effectCounter[0]] & 0x00ff00) >> 8;
      oldBlue[0]  = (tileBuffer[effectCounter[0]] & 0x0000ff);

      Serial << effectCounter[0] << "\t";
    }

    else if (flag[6] == 0)
    {
      oldRed[0]   = (tileBuffer[6 - effectCounter[0]] & 0xff0000) >> 16;
      oldGreen[0] = (tileBuffer[6 - effectCounter[0]] & 0x00ff00) >> 8;
      oldBlue[0]  = (tileBuffer[6 - effectCounter[0]] & 0x0000ff);

      Serial << (6 - effectCounter[0]) << "\t";
    }

    Serial << oldRed[0] << " " << oldGreen[0] << " " << oldBlue[0] << endl;

    if ((newRed[0] - oldRed[0] != 0) || (newGreen[0] - oldGreen[0] != 0) || (newBlue[0] - oldBlue[0] != 0))
    {
      // Red difference
      if (newRed[0] - oldRed[0] > 0) // Positive red change
      {
        oldRed[0] ++;
      }
      else if (newRed[0] - oldRed[0] < 0) // Negative red change
      {
        oldRed[0] --;
      }

      // Green difference
      if (newGreen[0] - oldGreen[0] > 0) // Positive green change
      {
        oldGreen[0] ++;
      }
      else if (newGreen[0] - oldGreen[0] < 0) // Negative green change
      {
        oldGreen[0] --;
      }

      // Blue difference
      if (newBlue[0] - oldBlue[0] > 0) // Positive blue change
      {
        oldBlue[0] ++;
      }
      else if (newBlue[0] - oldBlue[0] < 0) // Negative blue change
      {
        oldBlue[0] --;
      }

      if (flag[6] == 1)
      {
        tileBuffer[effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
      }

      else if (flag[6] == 0)
      {
        tileBuffer[6 - effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
      }

      // tileBuffer[effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
    }

    else if (((newRed[0] - oldRed[0]) == 0) && ((newRed[0] - oldRed[0]) == 0) && ((newRed[0] - oldRed[0]) == 0))
    {
      effectCounter[0] ++;  // Go to next tile
      //flag[1] = false;
    }
  }

  else
  {
    flag[1] = false;
    effectCounter[0] = 0;

    if (flag[6] == 1) // Flip flop between left and right updates
    {
      flag[6] = 0;
    }

    else if (flag[6] == 0)
    {
      flag[6] = 1;
    }
  }
  delay(wait);
}

```

# Answer
> 1 votes
For part of this you can use the switch case style
Which looks like

```
switch(flag[6]) {
    case 0  //your code here
             break;       // and exits the switch
    case 1 : cout << '2';
             break;
    default: //all other cases
}

```

There is also the ? syntax that can help

> condition ? result\_if\_true : result\_if\_false

If I "refactor" this type of code (really we all get there from time to time) I try to go back to "what I want". From What I understand your code would look like (no code validation this is a educational example)

```
int bufferoffset=0;
int bufferMultiplyer=1;

if(flag[6] == 0)
{
   bufferoffset=6;
   bufferMultiplyer=-1;
}
oldRed[0]   = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0xff0000) >> 16;
oldGreen[0] = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0x00ff00) >> 8;
oldBlue[0]  = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0x0000ff);

Serial << (bufferoffset+bufferMultiplyer*effectCounter[0]) << "\t";

Serial << oldRed[0] << " " << oldGreen[0] << " " << oldBlue[0] << endl;

int redDiff=newRed[0] - oldRed[0];
int greenDiff=newGreen[0] - oldGreen[0] ;
int blueDiff=newBlue[0] - oldBlue[0] ;
if(redDiff!= 0)
{
  redDiff > 0?         oldRed[0] ++:   oldRed[0] --;
 }
if(greenDiff!= 0)
{
  greenDiff> 0?         oldGreen[0] ++:   oldGreen[0] --;
 }
if(blueDiff!= 0)
{
  blueDiff> 0?         oldBlue[0] ++:   oldBlue[0] --;
 }

    tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
}

```

for more details on switch case see http://en.cppreference.com/w/cpp/language/switch for more detail on ? syntax https://stackoverflow.com/questions/795286/what-does-do-in-c

# Answer
> 0 votes
No, if-else is really the simplest way of dealing with that.

If you wanted to abstract it a little since you have repeated code just with separate variables, you could make a little function

```
// Note: set the right parameter variable types here
// to match your unspecified variables.
static inline int testUpDown(int a, int b) {
    if (a > b) return 1;
    if (a < b) return -1;
    return 0;
}

// Inside your flag tests:
oldRed[0] = testUpDown(newRed[0], oldRed[0]);
oldGreen[0] = testUpDown(newGreen[0], oldGreen[0]);
oldBlue[0] = testUpDown(newBlue[0], oldBlue[0]);

```

If you wanted an inline conditional variant you could do it with this:

```
oldRed[0] = ((newRed[0]-oldRed[0]) ? ((newRed[0]-oldRed[0])/abs(newRed[0]-oldRed[0])) : 0);

```

But who can understand that? You could always macro it:

```
#define UPDOWN(A,B) (((A)-(B)) ? (((A)-(B)) / abs((A)-(B))) : 0

oldRed[0] = UPDOWN(newRed[0], oldRed[0]);

```

# Answer
> 0 votes
you can shorten a lot of the vertical space with more compact conditionals, including ternaries to remove double conditionals where one result must follow from another.

For example, you can turn this:

```
  // Green difference
  if(newGreen[0] - oldGreen[0] > 0)  // Positive green change
  {
    oldGreen[0] ++;
  }
  else if(newGreen[0] - oldGreen[0] < 0) // Negative green change
  {
    oldGreen[0] --;
  }

```

into just this:

```
// Green difference
int gDiff = newGreen[0] - oldGreen[0];
if(gDiff) oldGreen[0]+= (gDiff > 0) ?  1 : -1;

```

# Answer
> 0 votes
//when there are multiple if/if-else/nested if/nested if condition then obviously it creates complexity in the code. I think switch is best option to use in such conditions. plz check switch condition if it is feasible in your program. Moreover i will check it in detail if it still not works. Try.........

---
Tags: c++, ide
---


# Question
Title: Program jumps alone from void loop() to another void
```
//simple alarm system
int RipSensor1 = 12;
int RmkeyA = 3;
int RmkeyB = 5;
int RmkeyC = 6;
//--------------------------------------------------------------------------

void setup()
 {
  Serial.begin(9600);
  pinMode(RipSensor1,INPUT);
  pinMode(RmkeyA,INPUT);
  pinMode(RmkeyB,INPUT);
  pinMode(RmkeyC,INPUT);
  pinMode(13,OUTPUT);
  Serial.println(F("System Is Up & Running")); }
  //----------------------------------------------------------------------

void loop()
 {
  Serial.println(F("Main Loop Start"));
  digitalWrite(13,LOW);   //for debugging
  if (digitalRead(RmkeyA) == HIGH)
   {
    Rip1Status();
   }
 }
//----------------------------------------------------------------------

void AlarmSMS1()
 {
  //send sms to admin1
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Rip1Status();   // return to this void (monitoring)
 }
//----------------------------------------------------------------------

void Rip1Status()
 {
  Serial.println(F("VOID Rip1 Start..."));
  while (digitalRead(RmkeyB) == LOW) //Arm mode
   {
    digitalWrite(13,HIGH);
    if (digitalRead(RipSensor1) == HIGH) //when Rip sensor sense motion
     {
      Serial.println(F("Movement ALARM --> PowerUP Relay 1 & 2"));
      long RipTimer1 = 0;
      long Rip01 = 0;
      int z = 0;
      int x = 0;
      while (digitalRead(RmkeyC) == LOW)
       {
        RipTimer1++;
        Serial.println(RipTimer1);   //for debugging
        if((z==0) && (RipTimer1 - Rip01 > 500))   //1st CheckPoint do something
         {
          z = 1;
          Serial.println(F("1st CheckPoint OK"));
         }
        else if((x==0) && (RipTimer1 - Rip01 > 3000))   //2nd CheckPoint go on other void
         {
          x = 1;
          AlarmSMS1();
         }
       }
      Serial.println(F("C Key Pressed --> False Alarm"));    //if button C pressed
      RipTimer1 = 0;
      z = 0;
      x = 0;
      Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
      break;
     }
    else Serial.println(F("Monitoring"));  //for debugging
   }
  Serial.println(F("B Key Pressed --> Disarming"));  //for debugging
  Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
  loop();
 }

```

I make this code & i have this problem:
Program start & wait for A key pressed to Arm mode. works ok
Press A key go to Arm mode (monitoring). works ok
When its on "monitoring", if i press B key, system disarming then go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, then alarm start and if i press C key then disarming as false alarm and go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, if i left alarm to complete, go to sms void send sms to admin and return to Rip void (monitoring).
But on this point if i press B button to disarm system this happen...

```
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
B Key Pressed --> Disarming
Monitoring Loop ends --> GoTo Main Loop
Main Loop Start
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012.............

```

Why this happen? What i am doing wrong?

# Answer
> 4 votes
`loop()` calls `Rip1Status()`, which calls `loop()`, which calls `Rip1Status()`, which calls `loop`(), which calls ....

That process will continue until the stack overflows (runs out of memory) or over-writes some necessary variable. If you just meant for `Rip1Status()` to return to the main loop, delete the `loop()` call at the end of the function. When Rip1Status()`exits, control will automatically return to`loop()`at the statement following the`Rip1Status()\` call.

---
Tags: programming
---


# Question
Title: Why is my Analog Input channel adding voltage to my signal?
*EDIT*: Here are the links to the sensor spec sheet (http://www.omega.com/temperature/pdf/HX71.pdf) and manual (http://www.omega.com/Manuals/manualpdf/M4543.pdf) for your reference.

I'm using a relative humidity (RH) sensor with an Arduino Mega. The RH sensor runs off of +/- 24V (which is being sourced by a power supply), and outputs a signal from 0-5VDC. Naturally, I am plugging this output signal into my A0 channel. There is a bare Earth Ground wire that is wired to the power supply's earth ground (possible error?) **Arduino's GND is connected to the power supply's EARTH GND, fyi**.

I compared the voltage reading in my Arduino Serial Monitor to a reliable Fluke multimeter, and **the analog input channel is adding ~.2 Volts!**

From some research, I have read about "high impedance" "source impedance" "internal wiring of Arduino" etc, but unfortunately I am failing to grasp the reason *why* this is happening. I'd like to know so then I could figure out a solution on my own.

Below is a schematic of what I'm dealing with so that it may better illustrate my issue (also my code). Thank you for your time, and I appreciate your help!

)

```
void setup()
{

Serial.begin(9600);

}

void loop()
 {

  float hs1 = ((( analogRead(A0) * ( 5.0 / 1024.0) ) )* 20.0 );

  Serial.print("RH%");
  Serial.print(":");
  Serial.print(hs1);
  Serial.print(";");
  Serial.println();
  delay(1000);

}

```

# Answer
Wow, you guys are gonna get a KICK out of this!

The analog input channel was **not** adding millivolts to my Analog Input signal. I stupidly was not supplying my Arduino Mega with 9V!! I had it running off of the USB port, which was affecting my 5V reference (thank you @majenko for pointing that out!).

I measured the 5V pin and it was fluctuating between 4.41-4.21 volts. My colleague made a comment and I reviewed the Arduino Mega datasheet. It must be supplied with 7-12 volts in order for the 5V to output correctly.

Once I hooked my Power Vin + GND to my power supply, set that at 9V/.08amps my analog input readings were accurate.

**Thank you everyone for your help!**
> 1 votes

---
Tags: arduino-mega, analogread, voltage
---


# Question
Title: More speed from ATMEGA328 Internal Clock
I have a board that is designed and produced. It was designed to use an Atmega328 with the internal clock. There is no space on the board to place an external clock. After completing these and testing them I have found that 8Mhz is too slow to complete my main loop actions seamlessly. The main loop involved shifting data out to 20 registers. Is there any way to speed this up without going back to the drawing board on the PCB design? Can another AVR be substituted as a drop in replacement with a faster internal clock? Can the internal clock be made to run faster or doubled to achieve 16Mhz?

The application is a matrix display that has 50 columns and 7 rows. The registers are the display buffers and represent the current state of the display. Because of the multiplexing in the matrix, only 1/5 of the pixels are illuminated at any given time. In order to trick the eyes into seeing all lit at the same time the speed needs to be faster. The display flickers with the interal clock. If I connect and UNO board instead of using the on board ATMEGA328 (QFP) it works good. So the difference between 8Mhz and 16Mhz is visible. If I can double the speed of the display loop than that is a solution. Below is the loop, for reference, latchPin = 8, clockPin = 12, dataPin = 11.

# Answer
`shiftOut()` relies on `digitalWrite()`, which is dead slow by AVR standards. You could probably get a factor 5, or even 10, by reimplementing `shiftOut()` using direct port access instead. Using SPI (as suggested in the comments) would be even faster, but you would need to clock out of pin 13.

**Edit**: here is an attempt at such implementation. Note that it is completely untested. Note also the small delay meant to avoid the thing being *too fast*. You may try to play with the delay value.

```
#include <util/delay.h>

/*
 * Especialized and faster shiftOut().
 * This assumes no one is touching PORTB at the same time.
 *
 * dataPin = 11 (PB3), clockPin = 12 (PB4), bitOrder = MSBFIRST.
 */
void myShiftOut(uint8_t val)
{
    for (uint8_t i = 0; i < 8; i++)  {
        // Send data bit.
        if (val & 0x80)
            PORTB |= _BV(PB3);
        else
            PORTB &= ~_BV(PB3);
        val <<= 1;

        // Toggle clock twice.
        PORTB |= _BV(PB4);
        _delay_us(0.5);
        PORTB &= ~_BV(PB4);
    }
}

```
> 4 votes

# Answer
It is 8MHz and not faster.
The only way to make it faster is to add an external crystal with two capacitors and change a fuse for external clock.

Many ATtiny chips can run at higher frequencies with the internal clock. Do you use a DIP package of the ATmega328(p) ?

Did you optimize the code ? The ATmega328(p) has highly optimized code to change an output pin. At what rate do you want to shift out data ?
> 0 votes

# Answer
I wrote the following earlier but the moderator deleted:

" A few things to try.

An external oscillator.

An external rc oscillator.

Optimized code: the code left a lot to be desired.

Optimized hardware: there is no reason you shift out the same value so many times. That's a waste of time. "

edit: just give you some sense on a 16MIPS ATmega:

1) your code executed in 2.54ms -\> a refresh rate of 400Hz;

2) your code software-optimized can be executed in 0.103ms -\> a refresh rate of 1Khz;

3) your code both software and hardware optimized can be executed in 0.054ms -\> a refresh rate of 2Khz.

what it tells you is that:

1) raising the clock isn't the only way to speed up execution;

2) there is a fundamental limit for this topology on how many shift registers you can drive before it starts to flicker;

3) to drive the most out of your design, you have to pay attention to both software and hardware. that's why embedded engineers get paid a lot of money to do;

BTW, the higher clock rate, the more likely you will run into timing issues in a long chain of shift registers. 20 - 25 shift registers are likely the limit in real life applications.
> 0 votes

---
Tags: avr
---


# Question
Title: How to write arduino code which reads the value of a flex sensor?
Since this is this the first time im doing Arduino, im really confused what the code is to:

write a code which reads the value(nae the value 'flexValue') of a flex sensor connected to analog input AN0.

The value should be a 10-bit integer number having value between 0-1023, inclusive.

# Answer
You should call the function `analogRead()`, and pass the value of `A0` into it because you want to read pin A0. For example:

```
flexVal = analogRead(A0);

```

The function `analogRead()` will return a value from 0-1023, just as you require.

When you call this function, the CPU configures the on-board ADC (analog-to-digital converter) to take a reading from pin A0. The ADC on the Arduino has 10-bit resolution, so it will return a value from 0-1023.
> 1 votes

---
Tags: input
---


title: Switching low current AC

text:
# Question
Title: Switching low current AC
What is the simplest way to switch ON/OFF a 60v and 5 mA of current ? I don't want the common relays for arduinos as they make click noise.

# Answer
> 1 votes
// Following devices could be helpful in you case.

1. Power BJT as a switch (check datasheets if it comes on your required range).
2. Solid state relay is obviously, but cast is little high in this case.

---
Tags: relay, switch
---


# Question
Title: Is it possible to connect NRF24L01 to localhost in laptop without wifi router?
I want to send data from arduino to my localhost port:8080(with ipython notebook) via modul NRF24L01 without WiFi router. Is it possible? If it possible, how to do that? Thank you...

# Answer
It is possible to have 2 NRF24L01 radios to talk to each other without a WIFI router.

However, is it possible to get your notebook to talk to a NRF24L01? Probably not unless you can write a device driver for it.

You could use two Arduinos each with a NRF24L01, and get one to receive the data and then send it via Serial to you laptop, but you would be better looking at an ESP8266, set that up as an access point, connect your laptop to that network and job done.

(By the way you won't be able to call you laptop localhost)
> 1 votes

---
Tags: wifi, nrf24l01+, python
---


title: Accessing two MPU-9250 DMP

text:
# Question
Title: Accessing two MPU-9250 DMP
I want to use both IMU at the same time using the Sparkfun Library on a SAMD21 mini breakout board. Can anyone help?

The begin function is :

```
inv_error_t MPU9250_DMP::begin(void) {
  inv_error_t result;
  struct int_param_s int_param;
  Wire.begin();
  result = mpu_init(&int_param);
  if (result)
    return result;
  mpu_set_bypass(1); // Place all slaves (including compass) on primary bus
  setSensors(INV_XYZ_GYRO | INV_XYZ_ACCEL | INV_XYZ_COMPASS);
  _gSense = getGyroSens();
  _aSense = getAccelSens();
  return result;
}

```

# Answer
Sorry, but I'm not 100% sure of what you are trying to do, I don't understand 'both imu the' in your question. I think you are trying to use two identical boards at the same time. (If not tell me so I can edit my answer)

You will need to modify the library so the `begin` function takes a parameter. That parameter for `MPU9250_DMP::begin` then identifies the address of the device, this will need passing to `Wire.begin()` I think (you'll need to check the Wire.begin() function, I can't).

That should let you create two different instances of the class.

```
MPU9250_DMP apple;
MPU9250_DMP banana;
apple.begin(0x68);
banana.begin(0x69);

```
> 1 votes

---
Tags: arduino-uno, accelerometer, mpu6050, gyroscope
---


# Question
Title: How to select which resistor is required for my curcuit to reduce voltage
I am trying to connect `arduino` and `esp8266` as like this

I know `arduino` runs at 5V and RX of ESP8266 should not have voltage more than 3.5V. If you see my diagram there voltage is large than need on RX of ESP8266. I know resistor can help me for this and ohm law.

```
V = R.I => R = V/I

```

So I want to understand how should I select what ohm resistor for this cuicuit ? Can anyone explain with some calculation using ohm law ?

# Answer
> 1 votes
A voltage divider made with a 4.7KOhm between your +5V and input and a 10Kohm between your input and ground will result in a 10/14.7 ratio, giving you 3.4V on your input.

If you use a 5.6KOhm to +5V instead, your voltage will be 3.2V which may be a bit easier on the ESP8266.

The trick here is not the specific value of any resistor, but the relationship between two resistors. You need to find a divider that will change 5 into 3.3 volts, a ratio of 0.66. Thus, any resistor values where the value of the bottom one in the diagram below divided by the value of both resistors is close to 0.66 will work. My suggestion would work equally well if you chose 1K Ohm and 470 Ohm.  Note that a voltage divider should only be used for signals and not for powering the ESP.

# Answer
> 5 votes
A resistor can only drop a certain voltage when there is a certain current - as you know from Ohm's Law. If you have resistance *R* and current *I* the voltage dropped is *R×I*.

So if the current changes the voltage changes - and if the voltage changes the current changes.

So what do we do? Well, we have *one* known fixed value, and that is the 5V from the GPIO pin. And since that is fixed (at least when HIGH) we could add a fixed resistance to it to give a fixed current, right?

So let's do that. Pick a random value. Experience teaches you that certain values are better than others, but the actual value doesn't matter too much, as long as:

1. It's not so small that too much current flows out of the GPIO pin, thus damaging it, and
2. It doesn't create too high an *output impedance*, which we will come on to later.

10kΩ is a good figure to start with. Not only does it keep the current low enough, but it's pretty much guaranteed that you'll have one in your bits box somewhere. And we connect it to the GPIO like this (we completely ignore the ESP8266 for the moment):

simulate this circuit – Schematic created using CircuitLab

When TX is HIGH it's at 5V. It's connected directly across a 10kΩ resistor, so therefore we can use Ohm's Law to calculate the current - I=V÷R = 5 ÷ 10,000 = 0.0005, or 0.5mA. (Another useful thing with 10kΩ resistors is it makes calculations nice and easy).

Now, what if we were to split that resistor in half, so it was two 5kΩ resistors in series? The circuit would look like this:

simulate this circuit

Resistors in series add together, so those two 5kΩ resistors are the same as one 10kΩ resistor. We know that 0.5mA flows through 10kΩ at 5V, so the same must run through 5+5kΩ at 5V. But now we have two fixed value resistors. Because of that we can now apply Ohm's Law to *each* one to find the voltage drop across it.

So with 0.5mA flowing through a 5kΩ resistor we get V=I×R = 0.0005 × 5000 = 2.5V. That's 2.5V across R1 and 2.5V across R2, since they are both the same. That's exactly 50% of the 5V across each one. At the point in the middle, point "A" on the schematic, you can see that the voltage has been cut in half. Once the current has gone through one resistor the voltage has halved (dropped by 2.5V), and when it goes through the other resistor it drops the rest to 0V, which is the other 2.5V.

If we were then to connect something to point A it would see a logic signal of 0V (LOW) and 2.5V (HIGH) from our 0V (LOW) and 5V (HIGH) signal.

But 2.5V is too low for the ESP8266 to read. Well, the answer is simple. We see that if we use two resistors we divide the voltage into two. The same applies for dividing it into three. For instance:

simulate this circuit

The sum is 10kΩ (well, 9.9kΩ but we'll call it 10kΩ for simplicity - a third each resistor, 3333.33Ω). 0.5mA through 3.3kΩ would be 0.0005 × 3333 = 1.66V. Funnily enough, 5 ÷ 3 = 1.66, so we have proved that it splits it into a third. That means at point A 1.66V of our 5V has been dropped (across R1), so 5V is now (5-1.66) 3.33V. Perfect for the ESP8266. Incidentally, point B would be 1.66V (3.33 - 1.66).

So now we have three resistors and the result we desire. However it's a little messy still. Remember that resistors in series add together? So why not add R2 and R3 together into a single resistor? That would be 6.6kΩ. Now I don't know of a 6.6kΩ resistor that's easily available, but 6.8kΩ ones are, though chances are you may not have one. If you did then a 3.3kΩ and a 6.8kΩ would net us near enough 3.3V to be usable.

But as I say you may not have one. So you pick resistor values that you *do* have. For instance you could use a 2.2kΩ and a 4.7kΩ, or a 10kΩ and a 22kΩ - anything that gives a *roughly* 1:2 ratio of value (the "upper" R1 resistor about half the value of the lower "R2" resistor).

Now - we get onto that mysterious phrase I mentioned earlier: *Output Impedance*. You recall we calculated the current that flows through the resistors - 0.5mA. The higher the value of resistors we use the lower the current. Well, that current not only flows through the resistors - a small amount also heads off into the ESP8266. The more that the ESP8266 wants for its RX pin the less there will be available for the R2 resistor. The result? Less current through the resistor = less voltage dropped across it.

*The current drawn by the pin attached to point A on our circuit affects the voltage dropped across the resistors*.

Too much current drawn and the voltage at point A will droop. Less will be dropped across the (current starved) R2, which means more must be dropped across R1. So point A is now a lower voltage. If that gets too low (too much current is drawn) then the RX pin can't read it properly.

Increasing the resistances decreases the current, but also decreasing the resistances increases the current. If the current is increased then the fraction of the current needed by the RX pin becomes reduced compared to what is available, so the output voltage drops less.

This *output impedance*, in case you're interested, is measured in Ohms, and is the same as the value of the two resistors in parallel - so (R1×R2)÷(R1+R2).

For instance, I tried connecting an ESP8266 the other day using 3 10kΩ resistors - R1 = 10K, R2 = 20K. It didn't work. You'd expect it to, given the ratios involved, however the output impedance (6.66kΩ) was too high for the ESP8266 I was using. Replacing them for 1kΩ resistors, so it was 666Ω output impedance, made it work straight away.

You can understand it easier if you think of the ESP8266 as just another resistor (it's actually more complex than that - it's also like a capacitor, so it forms a *low pass filter* which limits the frequency of, and deforms the shape of, the incoming digital waveform). For example:

simulate this circuit

I have deliberately shown the ESP8266 as a lower resistance that it would really be (you can expect MΩ) so as to illustrate the problem clearer.

Your R2 now has R(esp) in parallel with it. So the nice clean 20kΩ is now actually (20,000 × 100,000) ÷ (20,000 + 100,000) = 16.66kΩ. That gives us a total of 26.66kΩ, and at 5V that means a current of 0.188mA. Through the 10kΩ resistor we end up with (10,000 * 0.000188) 1.875V dropped. Take that from 5V and you can see that the ESP8266 would only be getting 3.125V.

By reducing the resistors in our network the difference that R(esp) makes to R2 reduces. For instance, reducing it to 1kΩ + 2kΩ gives us an R2 total of (2,000 * 100,000) ÷ (2,000 + 100,000) = 1.96kΩ - hardly any different from the 2kΩ we started with, so the voltage difference will be minimal (3.31 as opposed to the ideal 3.33).

The simple formula for calculating the output voltage from an input voltage and pair of resistors, so you don't have to go long-hand through Ohm's Law every time (though it is useful for understanding exactly what is happening) is:

*Vout = R2 ÷ (R1 + R2) × Vin*

I can never remember it, though, and usually use an online voltage divider calculator.

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


title: Alternative ways for read Serial Output

text:
# Question
Title: Alternative ways for read Serial Output
its possible to read serial ouput from ICSP or Tx Rx pin instead from USB port? If it's possible how? thanks for reply

# Answer
The TX and RX pins are connected directly to the USB to UART adaptor embedded in the board (an ATMega16U2 on the Uno R3, or a CH340G on a cheap Chinese clone). Anything that goes through the USB also goes through those pins.

You can also, if you must, use SoftwareSerial to get serial on any other pair of pins of your choice.
> 0 votes

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


# Question
Title: '[Class name]' does not name a type in C++ Error
```
    #include <Servo.h>
Servo tilt, pan;

// Arduino pin numbers
const int SW_pin = 2; // digital pin connected to switch output
const int X_pin = 0; // analog pin connected to X output
const int Y_pin = 1; // analog pin connected to Y output
int x, y;

// Second joystick pin numbers

const int SW_pinn = 4;
const int X_pinn = 3;
const int Y_pinn = 5;

void setup() {
  pinMode(SW_pin, INPUT);
  digitalWrite(SW_pin, HIGH);
  Serial.begin(115200); // setting serial baud rate tp 115200
  tilt.attach(7);
}

void loop() {
  x = X_pin; // defining the variable
  y = Y_pin;
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pin));
  Serial.print("\n");
  Serial.print("Y-axis: ");
  Serial.println(analogRead(Y_pin));
  Serial.print("\n\n");
  x = map(analogRead(X_pin), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec
  y = map(analogRead(Y_pin), 0, 1023, 900, 2100);
  tilt.write(x); // sets the servo position according to the scaled value
  pan.write(y);
  delay(5);

}

  x = X_pinn; // defining the variable
  y = Y_pinn;
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pinn));
  Serial.print("\n");
  Serial.print("Y-axis: ");
  Serial.println(analogRead(Y_pinn));
  Serial.print("\n\n");
  x = map(analogRead(X_pinn), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec
  y = map(analogRead(Y_pinn), 0, 1023, 900, 2100);
  tilt.write(x); // sets the servo position according to the scaled value
  pan.write(y);
  delay(5);
}

```

When I compile this code in the Arduino IDE it gives me the error

```
   arduino-builder/arduino-builder -compile -core-api-version 10611 -build-path /tmp/166416428 -hardware arduino-builder/hardware -hardware arduino-builder/packages/cores -tools arduino-builder/tools -tools arduino-builder/packages/tools -built-in-libraries arduino-builder/latest -libraries /tmp/358566849/pinned -libraries /tmp/358566849/custom -fqbn arduino:avr:uno -build-cache /tmp -verbose=false /tmp/358566849/sketch_may12a

Multiple libraries were found for "Servo.h"

Used: /home/admin/builder/arduino-builder/latest/Servo-1.1.2

Not used: /home/admin/builder/arduino-builder/latest/Printoo_Library-1.0.2

/tmp/358566849/sketch_may12a/sketch_may12a.ino:40:3: error: 'x' does not name a type

x = X_pinn; // defining the variable

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:41:3: error: 'y' does not name a type

y = Y_pinn;

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:42:3: error: 'Serial' does not name a type

Serial.print("X-axis: ");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:43:3: error: 'Serial' does not name a type

Serial.print(analogRead(X_pinn));

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:44:3: error: 'Serial' does not name a type

Serial.print("\n");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:45:3: error: 'Serial' does not name a type

Serial.print("Y-axis: ");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:46:3: error: 'Serial' does not name a type

Serial.println(analogRead(Y_pinn));

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:47:3: error: 'Serial' does not name a type

Serial.print("\n\n");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:48:3: error: 'x' does not name a type

x = map(analogRead(X_pinn), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:49:3: error: 'y' does not name a type

y = map(analogRead(Y_pinn), 0, 1023, 900, 2100);

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:50:3: error: 'tilt' does not name a type

tilt.write(x); // sets the servo position according to the scaled value

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:51:3: error: 'pan' does not name a type

pan.write(y);

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:52:8: error: expected constructor, destructor, or type conversion before '(' token

delay(5);

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:53:1: error: expected declaration before '}' token

}

^

exit status 1

```

In short, it saying that x does not name a type in this part of the code

```
x = X_pinn; // defining the variable
  y = Y_pinn;
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pinn));

```

Even though I defined it as a variable at the beginning... Any ideas?

# Answer
> 1 votes
If that is really your code then the errors are caused by one error. As Majenko says lines 58 through to 71 should not be there. It could be a cut and paste error when you wrote the post, but if it isn't that will cause a problem.

Some tips regarding your style that might help spot these faults in future.

1. Don't give variables a larger scope than they need. See x and y, these don't need to be global variables. You only use them within the `loop()` and you don't store the value between loops. In fact lines (42 and 43) aren't needed which means you could define them as `const int` values on line 50 and 51.
2. Braces {} - I know people like to write braces in the java style now, because it saves a line of text and all those 2 bytes will eventually add up, but If you had always put braces on line on there own you would have seen the error because line 57 doesn't have an opening brace.
3. Encapsulate related data - I appreciate its only a little scrap program, but I would have placed the pin information in a class. This would have let you have better variable names.

`const PinInfo joystick1 (2, 0, 1);`

`const PinInfo joystick2 (4, 3, 5);`

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


# Question
Title: Arduino DUE samples per second with the DAC
I want to know how many samples per second the arduino due DAC can generate, I need to generate an ultrasonic signal (40Khz), the arduino due is not going to do anything else that generate this signail for a very short period of time.

# Answer
According to the datasheet:

> * 2-channel 12-bit 1 msps DAC

So it's possible to generate 1 million samples per second. Of course that kind of speed would need DMA to drive it smoothly.

Assuming you want to generate a sinewave at 40KHz you have to first ask yourself what resolution (time-wise) you want from that sinewave, since that's the frequency that you need to generate samples for. For instance, if you want 100 samples in your sine wave you'd need to generate those at 4Msps, which you can't. At 10 samples per cycle you'd have 400Ksps which is more manageable, but the quality of the sinewave would be pretty poor.

Or, if you don't *need* a sinewave, if a square wave would do, just use a normal digital IO pin. You can generate MHz then.
> 1 votes

# Answer
With this code, the Arduino DUE was able to generate 250 samples per second approx. I tested it with a signal generator and an oscilloscope. I have found it on this web page http://www.electrosmash.com/pedalshield. All credit is for them.

Here is the code:

```
// Licensed under a Creative Commons Attribution 3.0 Unported License.
// Based on rcarduino.blogspot.com previous work.
// www.electrosmash.com/pedalshield

int in_ADC0, in_ADC1;  //variables for 2 ADCs values (ADC0, ADC1)
int POT0, POT1, POT2, out_DAC0, out_DAC1; //variables for 3 pots (ADC8, ADC9, ADC10)
int LED = 3;
int FOOTSWITCH = 7;
int TOGGLE = 2;

void setup()
{
  //ADC Configuration
  ADC->ADC_MR |= 0x80;   // DAC in free running mode.
  ADC->ADC_CR=2;         // Starts ADC conversion.
  ADC->ADC_CHER=0x1CC0;  // Enable ADC channels 0 and 1.

  //DAC Configuration
  analogWrite(DAC0,0);  // Enables DAC0
  //analogWrite(DAC1,0);  // Enables DAC0
}

void loop()
{
  //Read the ADCs
  while((ADC->ADC_ISR & 0x1CC0)!=0x1CC0);// wait for ADC 0, 1, 8, 9, 10 conversion complete.
  in_ADC0=ADC->ADC_CDR[7];               // read data from ADC0
  //in_ADC1=ADC->ADC_CDR[6];               // read data from ADC1
  //POT0=ADC->ADC_CDR[10];                 // read data from ADC8
  //POT1=ADC->ADC_CDR[11];                 // read data from ADC9
  //POT2=ADC->ADC_CDR[12];                 // read data from ADC10

  //Add volume feature with POT2
  //out_DAC0=map(in_ADC0,0,4095,1,POT2);
  //out_DAC1=map(in_ADC1,0,4095,1,POT2);

  //Write the DACs
  dacc_set_channel_selection(DACC_INTERFACE, 0);       //select DAC channel 0
  dacc_write_conversion_data(DACC_INTERFACE, in_ADC0); //write on DAC
  //dacc_set_channel_selection(DACC_INTERFACE, 1);       //select DAC channel 1
  //dacc_write_conversion_data(DACC_INTERFACE, out_DAC1);//write on DAC
}

```
> 1 votes

---
Tags: arduino-due
---


# Question
Title: Choosing the right mosfet to switch on-off a neopixel strip
I,m trying to find the right mosfet or transistor to switch on-off a neopixel strip to safe battery power on a Lipo 3.7v using a pro mini 3.3v.

My Animation-Setup and Power Comsumption with 35 Neopixels is :

* Sparkel : 20mA
* Knight Rider : 80mA
* Pulse : 600mA

So the maximum current for the ledstrip is 600mA @ 3.7v My first thought was to use the 2N 2222 - Transistor NPN TO-18 60V 0,8A 0,5W.

But then i realize the worst case: What happens if the all 35 Neopixels turn full white caused by a software glitch or a bug in the code. Full white means every neopixles consumes 60mA.

Total power comsumption: 35 X 60mA = 2.1A

Would be destroyed the 2N2222? Because it could handle only 800mA drain current?

How can I avoid this situation. So I read about Mosfet like this one FQP30N06L :

```
N channel power MOSFET
TO-220 Package
Vds = 30V max
Max current = 62A
Vgs = 2.35V max
Rds_on = as low as 8.7 milliohm - depending on Vgs

```

What do you think will it work to switch on/off the led if:

* the drain current is between 20mA - 600mA - 2.1A
* ledstrip Vcc is 3.7v
* pro mini out 3.3V at max 40mA

Or is there an other suitable Mosfet for this problem than the FQP30N06L with 62 Ampere for these hardware setup with only 2.1 Ampere Peak @ 3.7v ?

# Answer
You refer to a 2N2222 handling 800 mA. However, the 2N2222 datasheet shows 600 mA as its maximum rating for Collector Current – Continuous. Moreover, from the On Characteristics table, Collector – Emitter Saturation Voltage at 500 mA current could be as high as 1 V. In typical circuits with high base drive it usually is less, eg about 0.2 V typical with 50 mA base drive, which is more current than a typical AVR output is rated for. Anyhow, the Neopixels won't operate if your switch drops any significant voltage from the supply. Using a 2N2222 might work ok, or briefly, or intermittently, or not at all – depending on the quality of the 2N2222 and the amount of base drive.

You refer to a FQP30N06L handling 62 Amperes. However, the FQP30N06L datasheet shows 32 A as its rating for Drain Current - Continuous (vs 128 A for Drain Current - Pulsed, which is irrelevant here).

Using a FQP30N06L at its maximum 32 A continuous drain current would require careful heatsinking and perhaps 10 V of VGS drive to achieve low RDS(on), like 27 mΩ. With low VGS of say 3.3 V, RDS(on) might be twice as much. For example, if it were 45 mΩ, going above 4 or 5 A current would be problematic without careful heatsinking: 4 A → P = 4²·0.045 = 0.72 W, enough to heat up a not-heatsinked unit's junction by about 45℃ or 80℉.

But the FQP30N06L should work ok for your 600 mA typical-case scenario, and also should be ok with the 2 A worst-case as well.
> 1 votes

---
Tags: switch, mosfet
---


# Question
Title: ADS1262 and 2.2 SPI TFT (Two SPI Slave) with Arduino
I am interfacing two SPI slave module i.e. ADS1262 and 2.2 SPI TFT with the Arduino Ethernet board.

When I test each device on its own it works. Initially, I interfaced the TFT to the Arduino and it is working fine. Likewise, the example code of ADS1262 is working fine when I am running it alone.

So after successfully running the TFT alone, I then wire-up the ADS1262, add the corresponding code, however the ADS1262 doesn't seem to respond.

I think the issue may be related to the `ADS1262_CS` or `ADS1262_START` or `ADS1262_DRDY` pin sequence to access the ADS1262.

I have used the ProtoCentral\_ads1262 library from GitHub and have used the example code.

From Comments:
We have already reserved D10 for Ethernet Controller and D4 for SD Chip select. The issue is, how to communicate both of them, one by one. I can access one of them only when code is prepare for both devices.

---

```
// Portion of the code is given here

// https://github.com/adafruit/Adafruit_ILI9341 library used for TFT

// Code start from here

for(j=initvalue;j<=finalvalue;j+=x)
{

      dacvalue=((j*5)/65535);

      writeValue(j);

      tft.fillRect(30,150,70,28,ILI9341_BLACK);

      tft.setCursor(30,150);

      tft.println(dacvalue,3); // dac value is showing on TFT

      Serial.println(dacvalue,3);

// ADS1262 is need to communicate here as per https://github.com/Protocentral/ProtoCentral_ads1262 library

// Which pins are need to control here to communicate with ADS1262???

      volatile int p,data;

      if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data ready(DRDY pin)
     {
       SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes conversion register
       Responsebyte = true ;
     }

      if(Responsebyte == true)
      {
       for(p = 0; p <5; p++)
      {
        SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + p);
      }
      Responsebyte = false;
      }

       if(SPI_RX_Buff_Count >= 5)
      {
        ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
        ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
        ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
        ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

        uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)|((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
        sads1262Count = (signed long) (uads1262Count);      // get signed value
        Serial.println("sads1262Count:");
        Serial.println(sads1262Count);
        resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
        Serial.println(resolution,15);
        volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
        volt_mV   =   volt_V*1000;                           // voltage in mV
     tft.setCursor(166,150);
     tft.println(volt_mV,3); } //not printed on TFT

```

In above code, ADS1262 is not activated so not giving value on serial window or TFT.

How to activate the ADS1262 module.

# Answer
I would suggest that

1) you debug individual code and to make sure that they work separately before integrating them.

2) you put those code pieces in logical blocks. for example, you are likely going to read something from the adc and displaying it on the lcd. so your code flow should be something like this:

```
  vol_adc = ad1262_read(ADC1_CH); //read analog from ADC1_CH
  vol_mv = adc2mv(vol_adc); //convert the adc results to mv
  lcd_display(vol_mv);  //display vol_mv on the lcd

```

this approach allows for much easier programming and debugging for you and your readers.
> -1 votes

---
Tags: arduino-uno, communication, spi
---


# Question
Title: Is there a Serial write buffer limit and does the Arduino reset if it is hit?
I have an Arduino Mega 2560 that is resetting every 32 seconds if the serial monitor is not attached. Just before it resets, there is a flash of TX, then it goes. If ther serial monitor is attached it runs forever. Clearly I can't use the serial monitor to debug this so am clutching at straws as to what is happening.

**Update:**

Having eliminated *all* code and uploaded an empty sketch, no includes etc., the board still exhibits the reset. However, I have an Adafruit Ultimate GPS attached to the GND, 5V, TX1 and RX1 pins. When I remove it the resets stop. But with it attached and the serial monitor attached to the board, the resets also stop, even with an empty sketch. Spooky.

So, is it possible the GPS unit is filling a receive buffer, even if the serial port isn't set up to receive? I still have a problem that while I'm clearing and logging the GPS data, the resets are still at a regular 32 seconds, thus the reason I'm working on it still.

**Note:** The flash of TX no longer shows up with the empty sketch.

# Answer
> 0 votes
It turns out this problem had a very different cause, once I was able to eliminate the other variables. Having disconnected literally every component from the board and uploaded an empty sketch:

```
void setup() {}

void loop() {}

```

the board would still periodically reset itself.

I eliminated:

* flushing the receive buffers,
* eliminating all receives by disconnecting pins,
* speeding up/slowing down the serial port/s,
* speeding up/slowing down the GPS reporting rate,
* auxiliary hardware,
* code,
* includes,
* defines,
* laptop power supply noise,
* board revision in Arduino IDE,
* Arduino IDE version,
* USB port on laptop,
* trying this hack to prevent the RESET pin from going low,
* another Mega 2560 and a Due

None of the above influenced the issue.

The thing I did not think to check was whether the board would work with another power supply alone. This was a result of hunting for another power fault in service and with the laptop plugged in, finding a periodic, random reset.

Ultimately, I plugged the board into a monitor USB output, then a car charger power supply and finally found the issue was eliminated. Even plugging into another computer solved the issue. It appears that either the Arduino driver in Windows or the Arduino IDE software itself, would periodically poll the port, causing the board to reset. While the serial monitor was running, I assume the driver or IDE felt no need to poll the port, thereby leaving the board un-reset.

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


# Question
Title: Uno with LCD acting strangely - power issue?
I've got a Uno (Elegoo UNO R3) running with \- Ethernet shield (Kuman K15), \- 4 relay board (Elegoo 4 Channel DC 5V Relay Module with Optocoupler ) \- Matrix Orbital 2041 LCD connected via I2C (11mA typical, 90mA with backlight) \- A series of buttons connected

The Uno is currently running plugged in via USB to my macbook pro.

All of these devices are powered by the 5V pin on the Arduino.

The LCD goes wonky from time to time, and other times will work fine, it starts flashing the backlight, and just behaves oddly, sometimes even rebooting, when buttons are pushed (which activate the relays).

I'm wondering if this a power issue, perhaps the Uno isn't able to supply enough current to run everything.

My reading indicates that the USB port should be able to provide ~400mA, and when on an external supply I should able to draw 900 mA when using an external power adapter. However even with on an external supply (12v, 2A) I still have these issues.

Any thoughts would be much appreciated. Thanks

# Answer
System resets can be caused by power droop and by noise at the Reset pin, among other reasons. The problems mentioned could be due to power issues, or to electrical noise, or to wiring issues.

The total current draw apparently could approach or exceed the 400 mA mark mentioned in the question. With all four relays on, and coils drawing 50 mA each, that's 200 mA. LCD backlight and Arduino current make another 100, after which the ethernet shield could bring the total above 400 mA.

However, having the problems persist even with an external supply in use would suggest the root of the problems isn't power – if, of course, the external supply actually is supplying power directly to some of the peripherals, rather than via the regulator on the Uno.

When relays switch, they typically produce an electrical noise pulse. If this is the problem, it could be mitigated using ferrite beads, chokes, noise filters, etc. Using a separate power supply for +5 V to the board also should help.

Wiring issues include ground bounce and ground loops. If you are using a breadboard, there may be poor ground or power connections. Check that the grounds of peripheral devices and external supplies are solidly connected by decent wire and/or connected at a common point.
> 1 votes

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


title: Is applying 5 volts to LED dangerous?

text:
# Question
Title: Is applying 5 volts to LED dangerous?
The Arduino Uno manual (from the kit) instructs to connect a resistor to GND when lighting an LED on the breadboard with the 5V (socket?). The red, green, and yellow LEDs don't light up so brightly... actually they are barely bright enough to detect. Is it safe to apply all 5 volts by connecting the cathode to the ground with a *wire*? I tried it for a second and it worked... Just don't try it on the blue, I assume that beyond 5V it will explode, it burnt so bright..

Optional: Why does only the blue LED light visibly?

# Answer
Different color LEDs are not the same. The are made with different impurities. And some colors (blue) were really hard to figure out. So much so that the blue LED inventor was awarded the Nobel Prize!

Consequently, it should not be assume all LEDs operate at the same voltage and current. As such, when driving an LED with a constant voltage source, derive the proper series resistance for each case.

Example 1:

Given a red LED which may have 1.8 volt drop and may need 20mAmps to operate driven by a 5 volt source, we find the proper series resistor to be...

> V = I * R
>
> 5 - 1.8 = 20mA * R
>
> R = (5 - 1.8) / 0.020
>
> R = 160 ohms

Example 2:

Given a blue LED which may have a 3.3 volt drop and may need 20mAmps to operate driven by a 5 volt source, we find the proper series resistor to be...

> V = I * R
>
> 5 - 3.3 = 20mA * R
>
> R = (5 - 3.3) / 0.020
>
> R = 85 ohms

Your specific LEDs may have different specifications. The above are only examples.

Go here for more about calculating the proper LED series resistance.

In general, LEDs that are over driven will grow dimmer and not recover.
> 5 votes

# Answer
No, you cannot safely power an LED with 5V without a resistor. The resistor is absolutely 100% required.

The resistor isn't put there purely on a whim, it's required to set the current based on the supply voltage minus the LED forward voltage and the resistance of the resistor.
> 3 votes

# Answer
Ah. I found it. From the manual:

> Without the resistor, the LED would be brighter for a few moments, but quickly burn out.

Since 5V is HIGH on this thing, it looks like 5V would be too much for an LED.

Question 2: You were using the wrong resistor (too much resistance). But even with the incorrect resistor, the blue one shined! Strange.
> 0 votes

# Answer
Something else to take into consideration (as if this is not complex enough) is that if you're comparing LEDs visually you're not always going to be able to tell if your math is correct.

The human eye is about 3x more sensitive to blue light (and green light for that matter) than it is to red light.

So, presume that you had 3 absolutely identically manufactured LEDs: 1 Red spectrum, 1 Blue spectrum, and 1 White ("full spectrum"). If they are all hooked up with proper current, the Blue LED will appear to be approximately 3x the brightness of the Red LED (to your human eyeballs) and the White LED will appear to be some large factor brighter than the Red LED as well, and likely some factor brighter than the Blue even as it contains more 'spectrum'.

TL;DR: Check your layouts with a volt meter and math, not with your crummy eyeballs.
> 0 votes

---
Tags: arduino-uno, led, voltage-protection
---


title: How can I add a LED to this build?

text:
# Question
Title: How can I add a LED to this build?
I recreated this project from Fritzing in my circuits.io project then on the arduino itself, it all works fine just how I wanted it.

The concept behind it is:

1. You plug it in and the time is set to 00:00
2. You can adjust the time to the time now let's say 22:46
3. You can put in an alarm to wake up let's say an hour later at 23:46
4. The piezo beeps in stops, so not continious.

So now my question is, **how can I add a led that flickers on the same rhythm as the piezo** (when the alarm goes off)? Can someone help me in my circuits.io project?

An update/edit would be great! I'm relatively new to all of this.

Thanks a lot!

# Answer
* You need to add an LED and series resistor between a currently unused Arduino pin and ground.
* In your setup() function, set that pin's i/o mode to OUTPUT.
* Where the code turns the tone on, it should also make the LED pin HIGH.
* Where the code turns the tone off, it should also make the LED pin LOW.
> 1 votes

---
Tags: led
---


title: Current available SRAM?

text:
# Question
Title: Current available SRAM?
I've reached the limit on available SRAM memory. I need to "cut down" some variables, but I actually don't know how far I need to go with it.

Is there a way on measuring current available memory on program execution?

# Answer
> 2 votes
If you set "Show verbose output during compilation" in your IDE preferences, you'll see a message like the following in the IDE window's lower pane. The part I bolded is the amount of SRAM assigned:

> Sketch uses 2,148 bytes (6%) of program storage space. Maximum is 32,256 bytes.
> **Global variables use 204 bytes (9%) of dynamic memory**, leaving 1,844 bytes for local variables. Maximum is 2,048 bytes.

You can also include this function and print its result to get the same information on the terminal during run-time:

```
int freeRAM () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

```

---
Tags: variables, sram
---


# Question
Title: PWM water pump flow control - in percent
I want to control flow level on 12V water pump with PWM pin, I'm using IRF520N MOSFET for that (and dedicated 12V power supply).

I'm assuming, that setting PWM to full byte should give me about 100% or 12V. But how to set proper value on PWM pin so the flow equals to eg. 10%, 25% or 50%? Is it some logharitmic equation?

# Answer
> 3 votes
Expanding on dannyf's answer, if the pump datasheet does not feature a graph, then you will have to experiment. If a flowmeter is not readily available, an excellent approximation can be calculated by pumping water into a large, known receptacle (e.g. 10 litre bucket) and timing how long it takes. Do this for 20%, 40%, 60%, 80% and 100% Pulse Width Modulation modes, and you will have a plot of flow rate vs PWM that will help you interpolate the PWM required for a desired flow rate (e.g. 50% flow rate).

Below is an example of Rotations Per Minute of a 12V computer CPU cooler water pump for a given PWM input. It is assumed that this would be under load (of pumping water), but not stated explicitly.

Note that it may not be physically possible for the motor to operate with 10% or less PWM duty cycle. At this point I imagine that the internal friction of the motor and forces required to push the water along are greater than the force provided by a "10%" duty cycle.

Source: ekwb

# Answer
> 1 votes
> But how to set proper value on PWM pin so the flow equals to eg. 10%, 25% or 50%?

1. look at the pump's datasheet; and
2. experiment.

# Answer
> 1 votes
You'll need to tun the pump at some number of intermediate PWM values and measure its output at each one. The more intermediate values you measure, the more precise your control can be. Then you build a table of flow-rates vs. PWM level in flow-rate order, something like:

```
struct {
  float flow;  // measured flow rate
  float pwm;   // pwm value that gave that rate
} FlowTable[FLOWTESTS] = {
 // flow  PWM
  {   0.,    0. },
  { 218.,  256. },
  { 480.,  512. },
  { 732.,  768. },
  { 885., 1023. }
}

```

For a particular flow-rate, step through the table until you find a flow in the table that is \>= to the flow you want (if it's ==, just use that PWM and you're done.)

We'll interpolate between the two table values that span the desired flow-rate. The idea is, if your desired flow is say, 17% (0.17) of the way between those two flows, you want a PWM value that's about 17% of the way between the two PWM values.

Let's say you want a flow of 600 (in whatever units your measurements are in - cc/minute, for example. Index 3 in the table (remember, our arrays are 0-based) has the first measured flow greater than 600, the desired flow, so we know the required PWM will be between 512 and 768. To find it, find the desired flow as a fraction of the interval \[480, 732\]:

`frac = (600-480)/(732-480) = 120 / 252 = 0.476`,

or letting 'i' be the index of the first table entry whose flow exceeds the desired flow:

`frac = (flow_des-FlowTable[i-1].flow) / (FlowTable[i].flow-FlowTable[i-1].flow);`

. We need the PWM that is 47.6% of the interval \[512, 768\]:

`pwm_req = 512 + ((768-512) * 0.476)) = 634`
or

' pwm\_req = FlowTable\[i-1\].pwm + ((FlowTable\[i\].pwm-FlowTable\[i-1\].pwm) * frac);\`

---
Tags: pwm, voltage
---