title: RadioHead and DallasTemperature error

text:
# Question
Title: RadioHead and DallasTemperature error
The RadioHead library only runs on a very old core for the ATtiny85. It sends data but I would like to send something useful. The problem is I cannot read any sensors using this core. And on any other core the RadioHead library fails.

RadioHead library
ATtiny core

An old post in the Arduino forum, probably the same issue.

I would like to know what is in the DallasTemperature that conflicts with RadioHead making the code to hang.

The problem appears when I add `DallasTemperature sensors(&oneWire);` to the code.

```
// RadioHead ASK
#include <RH_ASK.h>

// DS18B20
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS PB0
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

// Sleep
#include <avr/sleep.h>
#include <avr/wdt.h>

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

// Absolute reference PB to overcome inter-IDE issues
#define T_PIN PB1 // transmission
#define L_PIN PB3 // optional LED pin
#define BAUD 2000

// Baud rate, receiver, transmitter
RH_ASK driver(BAUD, 9, T_PIN); // pin 9 is non existent

// the Tickle structure, what a name, ugh
struct tickle {
  uint16_t id;
  uint16_t value1;
  uint16_t value2;
};

// Watchdog
volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

// Sleep
void system_sleep() {
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

// Setup for Watchdog
void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

// With set_watchdog at 8 (4 sec.) we cycle from 0 to 14
// This timer is not precise
void minute_sleep(int ms) {
  for (int c = 0; c < ms; c++) {
    for (int i = 0; i < 15; i++) {
      system_sleep();
    }
  }
}

void setup() {
  // Debugging, if this takes less than a second, check fuses (core)
  if (!driver.init()){
    pinMode(L_PIN, OUTPUT);
    digitalWrite(L_PIN, HIGH);
    delay(500);
    digitalWrite(L_PIN, LOW);
    delay(500);
  }
  setup_watchdog(8);
  sensors.begin();
}

void loop()
{
  if (f_wdt==1) {
    f_wdt=0;
    struct tickle package; // make a Tickle package

    package.id = 38; // hard-coded device ID
    package.value1 = analogRead(PB0); // any positive int up to 2^16
    package.value2 = analogRead(PB2); // any positive int up to 2^16

    // sending data
    driver.send((uint8_t *)&package, sizeof(package));
    driver.waitPacketSent(); // wait for it ~Barney
    minute_sleep(10); // tested: 10 was 10:30, I like
  }
}

```

# Answer
I have experienced many issues when using RadioHead library on ATTiny85 together with the Arduino IDE. Your issue is not the Dallas temp sensor.

The problem lies in that RadioHead uses timer 0 on the ATTiny and changes the prescaler on the timer to match the baudrate you have requested for your tranciever. The change of prescaler changes the way Arduino IDE functions like `delay()`works since those also use timer 0. I believe your Dallas library depends on `delay()` to synchronize the signals on the 1-bus so there you have a conflict between the two libraries.

I solved this by rewriting the RadioHead RHASK files to allow for ATTiny85 timer 1 to be used instead. Here's my code. Although I use TinyHead instead of RadioHead, the change will be the same as TinyHead is a RadioHead clone.

The only change I made to RH\_ASK.h is the code to define whether to use TIMER1 or not.

```
// Flag to indicate whether to use timer1 in attiny85.
#define RH_ASK_ATTINY_USE_TIMER1

```

The below changes goes into RH\_ASK.cpp

First change. Update pre-scaler code and add the pre-scalers used by timer 1:

```
// Put these prescaler structs in PROGMEM, not on the stack
#if (RH_PLATFORM == RH_PLATFORM_ARDUINO) || (RH_PLATFORM == RH_PLATFORM_GENERIC_AVR8)
#if defined(RH_ASK_ARDUINO_USE_TIMER2)
// Timer 2 has different prescalers
PROGMEM static const uint16_t prescalers[] = {0, 1, 8, 32, 64, 128, 256, 3333};
#else
  #if defined(RH_ASK_ATTINY_USE_TIMER1)
   PROGMEM static const uint16_t prescalers[] = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16834, 3333};
  #else
   PROGMEM static const uint16_t prescalers[] = {0, 1, 8, 64, 256, 1024, 3333};
  #endif
#endif

```

Second change. This code sets up the timer 1 and goes before the existing code for ATTINY timer0 in function RH\_ASK::timerSetup(). please note the "... existing code" part. The existing code for setting up timer 0 goes between the #else and the #endif

```
#if defined(RH_ASK_ATTINY_USE_TIMER1)
#warning RH_ASK_ATTINY_USE_TIMER1 set.
   // figure out prescaler value and counter match value
   // REVISIT: does not correctly handle 1MHz clock speeds, only works with 8MHz clocks
   // At 1MHz clock, get 1/8 of the expected baud rate
   prescaler = timerCalc(_speed, (uint8_t)-1, &nticks);
   if (!prescaler)
       return; // fault

   TCCR1 = 0; // Stop the timer
   TCNT1 = 0; // Zero the timer
   GTCCR = _BV(PSR1);  // Reset the prescaler

   // Number of ticks to count before firing interrupt
   OCR1A = uint8_t(nticks);

   TCCR1 = _BV(CTC1); // Turn on CTC mode / Output Compare pins disconnected

   // convert prescaler index to TCCRnB prescaler bits CS00, CS01, CS02
   TCCR1 |= prescaler; // set CS00, CS01, CS02 (other bits not needed)

   // Set mask to fire interrupt when OCIE1A bit is set in TMSK
  #ifdef TIMSK0
   // ATtiny84
   TIMSK1 |= _BV(OCIE1A);
  #else
   // ATtiny85
   TIMSK |= _BV(OCIE1A);
  #endif
#else
#warning RH_ASK_ATTINY_USE_TIMER1 not set.
   // use timer 0 (default)
   // figure out prescaler value and counter match value
   // REVISIT: does not correctly handle 1MHz clock speeds, only works with 8MHz clocks
   // At 1MHz clock, get 1/8 of the expected baud rate
   prescaler = timerCalc(_speed, (uint8_t)-1, &nticks);

... existing code

   // ATtiny85
   TIMSK |= _BV(OCIE0A);
  #endif
#endif

```

Third change goes where the vectors are set up. Note the added #if defined for TIMER1 and the corresponding vector. Note also that the vector for timer0 is now called TIM0\_COMPA\_vect in later RadioHead/TinyHead but the names TIMx and TIMERx are interchangeable.

```
#if (RH_PLATFORM == RH_PLATFORM_ARDUINO)
#if defined(RH_PLATFORM_ATTINY)
 #if defined(RH_ASK_ATTINY_USE_TIMER1)
  #define RH_ASK_TIMER_VECTOR TIMER1_COMPA_vect
 #else
  #define RH_ASK_TIMER_VECTOR TIMER0_COMPA_vect
 #endif
#else // Assume Arduino Uno (328p or similar)

```

Mind you that I have had other issues using the DallasTempSensor library. I'm not sure whether the issue is a low quality crystal in my ATTiny or not, but I get garbage readings from my sensor. The same code works flawlessly on my Arduino Nano, so I'm currently investigating whether my ATTiny is too far off in its timings to work properly with that library. I'm also going to try the OneWire protocol to see whether that one works better. However, the above code change resolved my issues with Arduino IDE and RadioHead/TinyHead.
> 3 votes

---
Tags: library, attiny
---


# Question
Title: How do I get status of contactors using Arduino (more than 50 contactors)
I am new to Arduino. Sorry if my question sounds wrong.

Interest areas: Multiple devices inter-connected on the cloud. Single GSM for equipment in a typical panel connectivity for non-electrical parameter sensing devices e.g. Temperature, humidity. Mechanical operations & connection status Parameters of individual devices \[non-communication capable\] Connectivity with cloud

Interest areas: Connectivity for electromechanical devices – Contactors, MCBs, RCCB etc Parameters possible on IOT Device Status possible on IOT Size \[Compactness\] of the IOT solution to be integrated Aux Power requirement & possible ways to provide the same Memory retention Remote access/control and driving of the devices The estimated cost of the IoT connectivity devices should be a fraction of the device cost \[e.g. Contactor of 9A\]. Voltage level high

I am trying to read the status of more than 50 contactors i.e whether they are in ON\OFF\trip state using Arduino and display it on screen.

Can I use a single microcontroller to read the status of 50 or more contactors?

I searched on the net and I found out it can be done using shift registers or a latching system, but I didn't understand the method at all.

Please, can anyone explain me the method of doing this?Thanks.

# Answer
Due to lack of specifics, I cannot be more precise with my answer, but since you are working with "high" voltage (I'll assume 220V/415V) I would suggest the best solution to monitoring the current will be current transformers.

These are non-intrusive devices that you pass a single conductor through. It generates a small current in proportion to a large current flowing through the conductor.

This small current is then converted into a small voltage by passing it through a resistor and then measuring the voltage across that resistor.

Since it is AC you are dealing with simple digital IO pins will not suffice (except see below) - no matter how many you have. You need analog inputs, and you need to be able to sample that analog signal fast enough to at least capture the peaks and troughs of the incoming waveform. That means sampling at many times the frequency of the supply. For 50Hz you want to sample either at, say, 500 sps or more, or to sample at a rate that isn't a multiple of, or factor of, 50, but for a longer period of time.

Interfacing an AC voltage like this involves adding an offset voltage to it so that the zero point of the AC voltage lies in the middle of the ADC's range. This is most often done by feeding a voltage of 50% Vcc into the current transformer as a "virtual ground", so all output from it is superimposed on this offset voltage.

simulate this circuit – Schematic created using CircuitLab

Once you know the peak to peak voltage across the load resistor of the current transformer you can use that to calculate the peak to peak current the current transformer generated (Ohm's law), and thus the current through the central conductor.

This not only gives you the actual current through the conductor, but by simple logical reasoning, also gives you the state of the contactor: no current = contactor is off.

To reduce programming complexity at the cost of increased BOM cost it could be possible to build a simple rectifying and smoothing circuit (i.e., a simple integrating circuit) from diodes and a capacitor (either a single diode and a capacitor as a half-wave rectifier and smoothing, or a full-wave rectifier and smoothing) which will give you a simple DC voltage proportional to the current. Don't forget to take into account the voltage drop of the diode (or diodes) when doing your calculations, of course.

The integrating circuit could also be used, if you don't care about the current, to directly drive a digital input, as long as the voltage generated under normal load is above the threshold (VIH) of the IO pin, and never exceeds the maximum input voltage for the pin (a little over 5V). Adding a 5.1V zener diode and series resistor can help protect the input. The same should be done to an analog input as well to protect it from overvoltage.

simulate this circuit

One important thing with this integrating circuit, though, is that any downward changes in the current will take time to be reflected in the output. That is caused by the time C1 takes to discharge down to the new voltage level through R1. Balancing these values so you get a reasonable amount of responsiveness yet minimum amount of ripple on the signal will take a little experimentation and calculation.

You can read more about current transformers and interfacing them to an Arduino here.

---

For interfacing so many sensors to an Arduino you can, depending on if you are wanting to measure the current directly, or integrate the current to a DC voltage and use it as a threshold to a GPIO pin:

* Use shift registers (Parallel-to-Serial) for digital threshold reading,
* Use IO expanders (eg MCP23017) for digital threshold reading,
* Use external ADC chips (eg MCP3208) to provide more ADC inputs, or
* Use analog multiplexers (eg CD4051) to switch different analog voltages to a limited number of ADC inputs

Another option is to break your system down into smaller, more manageable, chunks. Group your signals into small subsections and have each subsection handled by a separate controller - be that an Arduino (maybe a Mini, or a Micro, or something) to handle a small group of signals. These can then feed their data into a more powerful management system (maybe a Raspberry Pi) through a serial protocol of some form (or wirelessly if you want to spend extra money), which then forwards the readings on to your chosen web service.
> 1 votes

# Answer
Yes you can.

There are special ICs, called Shift-In registers to do this job. You can daisy chain 4 of them, each capable of handling 8 outputs or inputs.

The most known is for outputs (e.g. LEDs) which is a 74HC595 (called shift-out register).

For inputs. you can use a CD4021BE. See the Shiftin Example how to use them. It will cost 3 pins (except VCC/GND) to control 32 inputs, so you need 6 pins for 50 (max 64). You need 50 / 8 = 7 of these ICs, but they are very cheap (10 for about 2 dollars).

Note that you will receive either a 0 or 1, so it's up to you how to detect trip states.
> 0 votes

---
Tags: arduino-uno, relay, shift-register
---


# Question
Title: Trying to make a heart rate analyser with Arduino that will calculate the BPM of a person
I am trying to make a heart rate analyzer device using an Arduino board that will calculate the BPM of a person by using raw sensor signals greater or equal to the threshold value to calculate pulses/heartbeat in 10 seconds and then multiply the number of pulses by 6.

The circuit is fairly simple: it has a led that is going to flash on the finger of the person. In-front of the finger there is going to be a photoresistor that is going to read changing values of light falling on it. The values will be varying because of the blood flowing through the finger. When there is going to be a pulse/heart-beat the amount of light falling on the photoresistor will increase, hence the reading of the photoresistor will also increase.

If the raw values read by the sensor are equal to or greater than the threshold value the code will increment the number of pulses by 1. To calculate the heartbeat rate we will have to count the number of pulses/heart-beats for 10 seconds and then multiply the count by 6.

In short the code that I will use will convert raw analog sensor data into BPM (Beats Per Minute) so that a user can get a standard measurement of his pulse rate.

I took the code that I am going to use from a website. Here is a link to page so that you can also have a look at the code.

I had some problem in the code and was wondering if anyone could help me with it. The full code is given below:

```
int sensorValue = 0;
int sensorValue = 0;
// variable to store the value coming from the sensor
int count=0;
unsigned long time1=0; // store the initial time
unsigned long time2; // store the current time

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(sensorPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  if(count==0) {
    time1=millis();
  }
  time2=millis();
  sensorValue = analogRead(sensorPin);
  if(sensorValue>156) {
    increment();
  }
  if(time2>=time1+10000) {
    counter();
  }
}

void increment() {
  count++;
  while(sensorValue>156) {
    Serial.print("Sensor value is greater than .75V\n");
  }
}

void counter() {
  count=count*6;
  Serial.print("Heartbeat rate is ");
  Serial.print(count);
  Serial.print(" per min\n");
  time1=0;
  time2=0;
  count=0;
}

```

Part of the code I'm not able to understand. This is located at the very top of `void loop()`:

\[note: i pretty much understand how increment and counter functions work but i am not able to understand how the program is able to take input for 10 seconds.basically how the counter function runs for 10 seconds\]

```
 if(count==0) {
    time1=millis();
  }
  time2=millis();
  sensorValue = analogRead(sensorPin);
  if(sensorValue>156) {
    increment();
  }
  if(time2>=time1+10000) {
    counter();

```

Although I know that this part of the code that I am not able to understand counts the pulses for 10 seconds by taking raw sensor values and checking if these values are above or equal to the threshold value, I am not able to understand how it is working.

I would be highly obliged if anyone could help me with this problem of mine.

# Answer
```
// Record the start time into time1
if(count==0) {
  time1=millis();
}

// Set time2 to the current time
time2=millis();

// Read the sensor
sensorValue = analogRead(sensorPin);

// If the sensor value is high enough, increment the beat counter
if(sensorValue>156) {
  increment();
}

// If the current time is greater than, or equal to, the start time
// plus 10,000 milliseconds (10 seconds), show the heart rate
if(time2>=time1+10000) {
 counter();
}

```
> 2 votes

# Answer
```
int sensorValue = 0;
// variable to store the value coming from the sensor
int count=0;
unsigned long time1=0; // store the initial time
unsigned long time2; // store the current time

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(A1, INPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  if(count==0) {
    time1=millis();
  }
  time2=millis();
  sensorValue = analogRead(A1);
  if(sensorValue>800) {
    increment();
  }
  if(time2>=time1+10000) {
    counter();
  }
}

void increment() {
  count++;
  while(sensorValue>800) {
    Serial.print("Sensor value is greater than .75V\n");
  }
}

void counter() {
  count=count*6;
  Serial.print("Heartbeat rate is ");
  Serial.print(count);
  Serial.print(" per min\n");
  time1=0;
  time2=0;
  count=0;
}

```
> 0 votes

---
Tags: programming, arduino-ide
---


title: Servo causes disconnection

text:
# Question
Title: Servo causes disconnection
I've only started using Arduino in the last week, and I'm having a problem with the servo supplied with the kit I purchased. It's a SG90 microservo. I'm trying to connect the servo as shown on the Arduino tutorial site:

But when I connect the power and ground pins to the board, the board powers down and disconnects from the USB. I've had the servo working before without a problem.

Yesterday I was trying out another tutorial without any luck, and I noticed the servo getting hot (not too hot to touch though).

Could I have accidentally fried the control board in the servo?

# Answer
Have a look at the current requirements of the SG90 and compare this to the maximum current available from an Arduino Uno.

Another thing to look at is how much current your computer's USB port can supply. My laptop, for example, can only supply 500mA per USB port.

My advise is to use a separate 5V power supply for the servo.
> 2 votes

---
Tags: servo
---


title: Run two steppers one by one

text:
# Question
Title: Run two steppers one by one
I want to run two stepper motors one after the other. Stepper 1 has to move 5 rotations, and stepper 2 has to move 1 rotation. Here is the code.

Stepper 1 is nema 34 And stepper 2 is nema 24

```
#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper1 (1, 3, 2); // Defaults to 4 pins on 2, 3, 4, 5 mortor (A)
AccelStepper stepper2 (1, 5, 4); // Defaults to 4 pins on 2, 3, 4, 5 motor (B)

long Steps_For_Distance1 = 3; // 3cm
long Steps_For_Distance2 = 5; // 5cm
long currentPos = 0;
long targetPos = 200;
long targetPos_Reverse = -200;
long Motor_Speed1 = 50;
long Motor_Speed2 = 400;
long Motor_Speed3 = 800;
int Op_Sw = 0;
const int buttonPin = 2;     // the number of the pushbutton pin

const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup()
{
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);

  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void checkStepper1_For_DT(AccelStepper &astepper)
{
  if (astepper.distanceToGo() == 0)
  {
    // Random change to speed, position and acceleration
    // Make sure we dont get 0 speed or accelerations
    astepper.setCurrentPosition(currentPos);
    astepper.moveTo(targetPos);
    astepper.setSpeed(Motor_Speed1);
    astepper.setAcceleration(100);
  }
}
void checkStepper2_For_360(AccelStepper &astepper)
{
  if (astepper.distanceToGo() == 0)
  {
    // Random change to speed, position and acceleration
    // Make sure we dont get 0 speed or accelerations

    astepper.moveTo(targetPos);
    astepper.setMaxSpeed(Motor_Speed2);
    astepper.setAcceleration(100);
  }
}
void PatternToBeLooped_For_Cycle1()
{
  int count = 0;

  for (count == 0; count <= 5; count ++)
  {
    checkStepper1_For_DT(stepper1);
    stepper1.runSpeedToPosition();
  }

  checkStepper2_For_360(stepper2);
  stepper2.runSpeedToPosition();
}
void loop() {
    PatternToBeLooped_For_Cycle1();
  }

```

I ran the code, but it didn't work. Both motors are running at the same time.

Please help me. Where did I make a mistake?

Thank you in advance.

---

I tried with `delay(1000);`, but But still both steppers are moving at the same time and get delay at the same time.

# Answer
> 1 votes
I looked into the source of the AccelStepper library here, which may be your library or one similar to it. The function `runSpeedToPosition()` does not block until the desired position is reached. Instead inside the function you see code that executes a step, when the right time (according to `millis()`), calculated through the speed, is reached, else it will return false. You are supposed to call this function very often while the motor moves. This enables you to drive more than one motor simultaneously with different speeds.

Since you don't want to drive both motors at the same time, you have to loop, until the first motor have reached the desired position; then doing the same with the second motor. Try something like this:

```
void PatternToBeLooped_For_Cycle1()
{
  int count = 0;
  for (count == 0; count <= 5; count ++)
  {
    checkStepper1_For_DT(stepper1);
    while(stepper1.currentPosition() != stepper1.targetPosition()) stepper1.runSpeedToPosition();
  }

  checkStepper2_For_360(stepper2);
  while(stepper2.currentPosition() != stepper2.targetPosition()) stepper2.runSpeedToPosition();
}

```

Note: With this change the function `PatternToBeLooped_For_Cycle1()` blocks the execution of the loop function, until the motors have done their movement. To avoid this you can use an if-statement, which executes the code for stepper1 or stepper2 depending on the `millis()` function. This works the same way as the BlinkWithoutDelay example in the Arduino IDE.

---
Tags: accelerometer, stepper
---


# Question
Title: Is the arduino hackable when using communication shields?
Let's say I have an arduino Uno connected to a W5100 ethernet shield. The arduino communicates with the ethernet shield using the tx0 and rx0 pins. When I upload a new script to the arduino using USB, it uses the same tx0 and rx0. So that made me think.

What if I run a script on my arduino that fetches some data from a webpage using HTTP requests but someone manages to hack into my server. Is it possible for the hacker to upload some kind of code to my server, which will erase (when fetched by the arduino) the old script and upload a new arduino script, by making the arduino think it's uploading a new script while it's getting data from the ethernet shield (or other communication shields?)

EDIT: Let's expand the question a bit.. How can I add security to my code to prevent this situation from happening?

# Answer
> 5 votes
You should be pretty safe, at least as long as your code handles the incoming data properly.

When you upload a new sketch through USB, the USB-to-serial interface uses the Arduino pins TX0, RX0 **and RESET**. Your Ethernet shield, on the other hand, does not control the RESET pin. Pulling the RESET pin LOW is needed to make the processor enter the bootloader, which in turn is needed in order to upload a new program. For pulling this pin low, the malicious code would need not only to break into the Ethernet shield's firmware, it would also need a **hardware hack** to access the pin.

Now, if your own code is not safe, it is conceivable that the malicious payload tricks your program into jumping to the bootloader or, as suggesting by Juraj, into triggering a watchdog reset (which ends up being equivalent). Thus you should treat *anything* coming from the network as potentially malicious.

# Answer
> 1 votes
No it's not possible. Assuming you mean this shield (and if you don't, please clarify):

> Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega.

Further on it mentions:

> The shield contains a number of informational LEDs:
>
> ...
>
> RX: flashes when the shield receives data
>
> TX: flashes when the shield sends data

That's Rx and Tx on the shield, not the Arduino. Since it does not connect to the Tx/Rx on the Arduino, and since it cannot reset the Arduino, it therefore cannot reprogram it.

If you are worried, disable the BOOTRST fuse on the Arduino so that the bootloader is not active after a reset.

If you are *really* worried, disable the SPIEN fuse so that you cannot even reprogram it using SPI. Of course, then you won't be able to reprogram it either.

Personally I would be more worried that a cockatoo would come and peck at the shield.

---
Tags: serial, communication, ethernet
---


# Question
Title: How to: Connecting 4-pin Joystick to Arduino board
I am completely new at Arduino. I have a joystick:

It is however quite different from all the other joystick-tutorials, as their joysticks have 5 pins, not just 4. So I am quite at loss here. How do I connect it?

# Answer
> 1 votes
If the link that Mark Smith provided is correct, that is a “dual-axis mini xy joystick module PSP 2-Axis Analog Thumb Joystick Module Thumb Joystick for Arduino”, with (as other comments suggested) pins labeled on back of board as GND, X, Y, VCC.

To use it, attach GND to Arduino ground; connect each of X and Y to analog inputs, like A0 ... A7; connect VCC to (typically) 5 V. Then read results on your analog input lines.

Note, it makes sense to test the device using a DVM beforehand. Measure resistance from GND to VCC to find out overall resistance, so you can decide if 5 V is appropriate or if you should use a lower voltage. (For example, if overall resistance is several thousand ohms, 5 V is ok; if only a few hundred, add one or two thousand ohms in series and take analog readings using a 1.1 V reference instead of 5 V reference.) Also measure resistance from GND to X as you move the thumb control, and from GND to Y.

# Answer
> 0 votes
For sure there should be 4 pins, 'GND', 'VCC', 'X' and 'Y'. GND (-) is used when the joystick goes into a negative axis (depending x or y) on a Cartesian plane it transfers as negative into the Arduino board. The same thing happens when it goes to positive (VCC (+)) (depending x or y) on a Cartesian plane it transfers as positive onto the Arduino Board.

---
Tags: joystick
---


title: Arduino --> RPI I2C issue

text:
# Question
Title: Arduino --> RPI I2C issue
ok, I feel like this should be simple, but I am at a loss

Simple code mock up to send 4 bytes(mimicking a float) over I2C from Arduino to rpi. I am trying to create a state machine so that I can request certain "registers" containing 4 bytes each. I send a byte from pi to arduino indicating what "register" I want, then read back 4 bytes. I was attemping to reset the state back to NO\_STATE after the end of the switch statement, but it effects the bytes received by the pi, and I dont see how.

```
#include <Wire.h>
#define SLAVE_ADDRESS 0x04

//States
#define NO_STATE 0x00
#define GET_BAT_TEMP 0x03

byte state = NO_STATE;
void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);
}

void loop() {
  delay(100);
}

// callback for received data
void receiveData(int byteCount){

  while(Wire.available()) {
    state = Wire.read();
  }
  Serial.print("Got:");
  Serial.println(state);
}

// callback for sending data
void sendData(){
  Serial.println("Sending...");
  byte b[4]={1,1,1,1};

  switch (state){
    case NO_STATE:
      //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
      Wire.write(0);
      Wire.write(0);
      Wire.write(0);
      Wire.write(0);
      break;
    case GET_BAT_TEMP:
      //send battery temp
      Wire.write(3);
      Wire.write(3);
      Wire.write(3);
      Wire.write(3);
      break;
    default:
      Wire.write(9);
      Wire.write(9);
      Wire.write(9);
      Wire.write(9);
      //send back error code
  }
  //reset state to none
  state=NO_STATE;

}

```

with this code I receive \[3,0,0,0\]

if I comment out the line

```
//state=NO_STATE;

```

I then receive back \[3,3,3,3\]

which is what I would expect. But I do not see how reseting the state "after" all the bytes are sent would cause an issue

output from arduino shows entering that function only once, and sending the 4 bytes

```
Got:3
Sending...
Sending...
Sending...
Sending...

```

# Answer
I'm not an expert, but I think I found why it is not working.

The main problem is that you are using always the same byte (0, 3 or 9) for debugging, so you are not noticing that it is not sending four bytes, but only one, and the function gets called four times. This is obvious however from the reply on the serial interface (+1 for adding it in the question, good work).

What you can do is to track how many bytes you sent, and send the successive one. After the bytes are all sent you can reset back the state. The code can be something like

```
//States
#define NO_STATE 0x00
#define GET_BAT_TEMP 0x03

byte sentData;
byte batteryLevel[4]={3,4,5,6};

byte state = NO_STATE;
void setup() {
    Serial.begin(9600);
    pinMode(13, OUTPUT);
    Wire.begin(SLAVE_ADDRESS);
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);
}

void loop() {
  // delay(100); // Useless, let it cycle at its max speed
}

// callback for received data
void receiveData(int byteCount){
    while(Wire.available()) {
        state = Wire.read();
        sentData = 0;
    }
    Serial.print("Got:");
    Serial.println(state);
}

// callback for sending data
void sendData(){
    Serial.println("Sending...");

    switch (state){
        case NO_STATE:
            //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
            Wire.write(0);
            break;
        case GET_BAT_TEMP:
            //send battery temp
            Wire.write(batteryLevel[sentData]);
            if (sentData < 3)
                sentData++;
            else
                //reset state to none
                state=NO_STATE;
            break;
        default:
            Wire.write(9);
            //send back error code
    }
}

```

I haven't tested it, so forgive any bugs. But I'm sure you understood the main point.

Just some remarks: the delay is useless (you are not saving energy or other with it, so just remove it); the serial is ok for debugging, but I think you should remove it from the code you will use (not ok to stop the interrupts for such a long time).

And most important: I hope you considered the 5V vs 3.3V voltage problem on the I2C ;)

In any case, I second Look Alterno: good way to ask a question, with all the information needed.

EDIT: as pointed out in the comments, there exist a function to send all the data together. I'm not sure how it behaves in different conditions (e.g. when less bytes are requested), but if you trust the communication the function can be simplified in

```
// callback for sending data
void sendData(){
    Serial.println("Sending...");

    switch (state){
        case NO_STATE:
            //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
            Wire.write(0);
            break;
        case GET_BAT_TEMP:
            //send battery temp
            Wire.write(batteryLevel, 4);
            state=NO_STATE;
            break;
        default:
            Wire.write(9);
            //send back error code
    }
}

```

(and the `sentData` variable becomes useless)
> 0 votes

---
Tags: i2c, raspberrypi
---


title: ESP8266 - Webserver not working in loop

text:
# Question
Title: ESP8266 - Webserver not working in loop
I have simple example, where in loop is called webServer to handle clients and also text drawing on display. The thing is that webServer is not responding, but when I remove second part of loop - drawing text to display then web server starts to work normally.

Server does not respond:

```
 void loop() {
      server.handleClient();
      unsigned long timeNow = millis();
      if ((timeNow > screenChangeTime))  {
          display.clear();
          display.setFont(ArialMT_Plain_16);
          display.setTextAlignment(TEXT_ALIGN_CENTER);
           display.drawString(12, 20,"Loaded: "+String(particles));
           screenChangeTime= timeNow + delay;
           display.display();
      }
    }

```

Server responds:

```
void loop() {
      server.handleClient();
}

```

# Answer
My guess is, that you're wasting too much time within the drawing-part.

What is the value for `delay`? I guess you have a number too low chosen here. And you should really set this new time **after** you have updated the display by `display.display();`.

Your webserver doesn't respond because he's not called often enough inside this code.
> 1 votes

---
Tags: esp8266, web-server
---


title: Two Arduino boards - one IDE

text:
# Question
Title: Two Arduino boards - one IDE
Have been using UNO MEGA for small projects. Recently bought an UNO for other projects. Can I just go into the IDE an under Tools select UNO and a different port to do projects and rename sketches to keep track of sketches. Do not wish to use boards at the same time.

# Answer
> 6 votes
That's the way to do it.

You need to select the type of board first:

And then the port. You can have both devices connected at the time and select which one you want to program.

With Arduino you can do OTA (Over The Air uploads) to NodeMCU and other ESP8266 based systems.

If you want to run two instances of the IDE, to work with two different boards at the same time, use UECIDE.

---
Tags: arduino-ide
---


title: convert byte and float to char

text:
# Question
Title: convert byte and float to char
I am trying to send sensor values to internet via enc28j60 module and web client example.

My problem is that i chose byte and float form for some sensors i can't convert these values to char form.

Code example below

```
UVSensorValue = analogRead(A0);               // UVSensorValue is in byte form
concentration = 1.1*pow(duration,3)-3.8*p...  // concentration is in float form

```

I want to store them in a char variable like this:

> param = "uv=5&temp=23.2&dust=0.62..."

And send them here:

```
ether.browseUrl(PSTR("/measures?"), param, website, browseUrlCallback);

```

I tried strcpy function or String convention but nothing worked. I know its a silly question however i stuck and cant find solution.

If someone could help me i would be pleased. Thanks in advance!

# Answer
In any other C/C++ platform, you can use "%f" as a format specifier when you want to print (or convert to string) a float using `printf` or its siblings. Any, except in Arduino.

To convert a float you need use `dtostrf()`,

```
char * dtostrf(
    double __val,
    signed char __width,
    unsigned char __prec,
    char * __s)

```

> The dtostrf() function converts the double value passed in val into an ASCII representationthat will be stored under s. The caller is responsible for providing sufficient storage in s.
>
> Conversion is done in the format "\[-\]d.ddd". The minimum field width of the output string (including the possible '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. width is signed value, negative for left adjustment.
>
> The dtostrf() function returns the pointer to the converted string s.

To convert a byte (or anything not float) to ascii, use `snprintf()`

```
int snprintf ( char * s,
               size_t n,
               const char * format,
               ... );

```

> Write formatted output to sized buffer.
>
> Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by s (taking n as the maximum buffer capacity to fill).

You can read the details by yourself, but here is a demo.

The idea is to produce in `buffer` a traditional C-style string (null terminated). That string you can print or transmit.

The float value is printed in two step. First, we use `dtostrf` to convert the float value to his ascii representation. Then we use `snprintf` to include that value (as a string) inside a whole line, latter to be printed.

```
void setup() {
  Serial.begin(9600);
  while(!Serial);
  Serial.println("Start");

  float value = 123.45;
  byte balue = 128;

  char buffer[80];
  char fValue[16];
  dtostrf(value, 3, 2, fValue);
  snprintf(buffer, sizeof(buffer), "float %s", fValue);
  Serial.println(buffer);
  snprintf(buffer, sizeof(buffer), "byte value is %d", (int) balue);
  Serial.println(buffer);
}

void loop() {

}

```
> 2 votes

---
Tags: arduino-uno, web
---


# Question
Title: Adafruit Motor Shield steppers not turning
The Adafruit Motor Shield is connected to 2 steppers which are wired correctly and work when I just use the onestep function. I understand that I cannot drive both at once, so I am using a while loop with two if statements. The Motors were wired:

The left motor was wired:

Green -\> m3+
White -\> m3-
Red -\> m4+
Blue -\> m4-

The right motor was wired:

Red -\> M2+
Blue -\> M2-
Green -\> M1+
Black -\> M1-

Here is the code:

```
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *leftMotor = AFMS.getStepper(200, 2);
Adafruit_StepperMotor *rightMotor = AFMS.getStepper(200, 1);
//79 steps per half inch
//half inch is a coordinate
//declaring global variables for Hypotenuses (cord lengths)
int leftHyp;
int rightHyp;
int prevX = 0;
int prevY = 0;
//space from shaft to shaft is 30"
//calculating function
void CordCalc(int xCord, int yCord)
{
    Serial.begin(9600);
  //cords start at 0,0
    xCord = xCord - prevX;
    yCord = yCord - prevY;
    int xSquared = sq(xCord);
    int ySquared = sq(yCord);
    int addSquares = xSquared + ySquared;
    int leftHyp = sqrt(addSquares);
  //now for the right
    int rightX = 60 - xCord;
    int rightXsq = sq(rightX);
    int rightSquares = rightXsq + ySquared;
    int rightHyp = sqrt(rightSquares);
  //leftMotor->step(leftHyp * 79, FORWARD, MICROSTEP);
  //rightMotor->step(rightHyp * 79, FORWARD, MICROSTEP);
    int lStepsTaken = 0;
    int rStepsTaken = 0;
    leftHyp = leftHyp * 79;
    rightHyp = rightHyp * 79;
    bool stepsComplete = false;

  //This is the section for moving the Motors
    while(stepsComplete == false) {
        if(lStepsTaken <= leftHyp) {
            leftMotor->onestep(FORWARD,DOUBLE);
            lStepsTaken++;
            Serial.print("Left");
        }

        if(rStepsTaken < rightHyp) {
            rightMotor->onestep(FORWARD,DOUBLE);
            rStepsTaken++;
            Serial.print("Right!");
        }

        if(rStepsTaken >= leftHyp && lStepsTaken >= leftHyp) {
            stepsComplete = true;
        }
    }

    int prevY = yCord;
    int prevX = xCord;
    stepsComplete = false;
}

void setup()
{
// direction from project point of view
    int leftLength = 0;
    int rightLength = 0;
    leftMotor->setSpeed(122);
    rightMotor->setSpeed(122);
    Serial.begin(9600);

    CordCalc(15, 15);
}

void loop()
{
}

```

Loop is empty on purpose because only need to move to coordinates once.

# Answer
> 0 votes
The missing line was afms.begin(); which starts communication with the adafruit motor shield.

---
Tags: arduino-uno, motor, adafruit, stepper
---


title: Repairing Analogue Inputs on Uno?

text:
# Question
Title: Repairing Analogue Inputs on Uno?
After a long afternoon, chasing a fault on my project, I've come to find that I've damaged 2 out of the 6 Analogue Inputs. Their ADC reading doesn't display 0 when grounded, nor a known ADC value from a sensor.

I've identified the problem to the voltage divider sensors that were connected to these particular Analogue Inputs, I've since researched that topic and made some alterations.

I don't suppose by buying a replacement chip, will solve the problem of 2 bad Analogue Inputs? So I can save the hardware and reduce cost?

Thanks in advance for any help you can provide.

Stu

# Answer
If the Analog input of your Arduino Uno is damaged, then unfortunately you have damaged the pins on the ATMEAGA328P chip directly.

As per the schematic below of Arduino Uno R3, the pins A0 to A5 are connected directly on the Pins 23 to 28 of the ATMEGA328P chip.

Therefore if you say that the 2 out of 6 Analog pins have been damaged then ***the only way to fix that is to replace the ATMEGA328P chip with a new one.***

More can be read here about the UNO's hardware design.

PS. When replacing the ATMEGA328P chip, be sure to program the new chip with the Arduino Bootloader so you can upload sketches to it, otherwise it won't work ;)

Cheers!
> 2 votes

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


# Question
Title: Using C - How do I make my button press nearly instant without using interrupts
How can I make the press of a button nearly instant, WITHOUT using interrupts or millis() - and NO preset arduino functions, just C. There is a delay at the end of my while loop of 500ms - perhaps the solution lies in breaking up the delay (NOTE: I need to keep the delays)

# Answer
> 0 votes
You can delay a small period, check button, delay again. Loop this until the full delay is achieved

---
Tags: button
---


# Question
Title: Attiny13 project with leds and electret microphone
I want to make a project similar to this Turn Signal Biking Jacket

.

But, instead of using Arduino Lilypad I want to use an 8 pin attiny13A-SH and want to use one electret microphone instead of the buttons.

I want to use led's only for the left, right and a stop indicator(on the back, i don't want the leds on the sides like the instructable project).

According to me, the leds require 1 pin each and will share a common gnd(that's 4 pins).

The microphone will require 1 additional pin, with 1 going to the gnd (5 pins).

And I might require 2 pins for the power outlet (6 pins out of 8).

Now, i am a newbie in all this stuff so i don't want to go about experimenting with the chips. I am ready to disable the reset pin cause i wont require the chip again. I have got a couple of instructable's to help me in the programming and set-up plan(though they have used Arduino Uno or Lilypad), so **I only want to know if it is possible to make the project with the attiny13a chip without the requirement of any additional parts.**

Also, as an alternative, i wanted to use these leds instead of the lilypad led's, so i want to know if i can do the model in exactly the same way without using any mofsets etc(i just want 6 leds on each side). I'm extremely sorry for my horrible drawing(First time and no correct tools. used paint!)
**ANY HELP IS APPRECIATED.**

# Answer
> 1 votes
> want to use 1 electret microphone instead of the buttons.

In what way do you want to use the microphone? You do realise, don't you, that an Arduino can't understand speech (or much of anything really) without powerful extra hardware? A microphone by itself is pretty much useless, especially without any form of preamp and signal conditioning.

> i only want to know if it is possible to make the project with the attiny13a chip without the requirement of any additional parts.

No, it's not possible. You will require lots more parts. You can't just take an arbitrary chip and connect it to a battery and expect it to work properly. You need to consider correct supply voltages (voltage regulation or boosting depending on your power source), decoupling capacitors, drive circuitry, amplification, signal processing, etc...

> i wanted to use these leds instead of the lilypad led's, so i want to know if i can do the model in exactly the same way without using any mofsets etc

Again, no. Those are 12V LED strips. You need both a 12V supply (and the associated regulation down to 5V to power the ATTiny etc) and MOSFETs (or something similar) to allow the ATTiny to switch that 12V to the LED strips as needed.

# Answer
> 0 votes
A simple answer would be "**No, it's not possible**"

You cannot run a single chip independently without any protection and regulating components(e.g. capacitor, regulator, current limiting resistor)

Also by replacing components with other ones, it would require you additional adjustments in the code and also in the hardware(Referring to the replacing buttons with Electret Microphone). There is a reason for the Arduino Lilypad to have additional components so that it can run smoothly and avoid damages to both the user and the device itself.

---
Tags: arduino-uno, attiny, led-strip
---


# Question
Title: How to blink the LED forever when detect an object is more than 30 cm away using ultrasonic sensor
I would like to make an alarm system using ultrasonic sensor.

My aim is to blink an LED for ever once ultrasonic sensor detect an object is more than 30 cm away.

But the problem is that my code some time fail to detect object accurate distance and even LED blinks but when ultrasonic sensor off LED becomes off.

I am using timer to on the ultrasonic sensor for 2 minutes (timer code not attached) so within that period if it detect an object is more than 30 cm away it blinks the LED till the power is cut.

```
int echoPin = 10; // pin 10 for the echo

int trigPin = 9; // pin 9 for trigger
int duration, inches, cm; // Establish variables for duration of the ping, and the distance result
#include <NewPing.h> // Library for improved ultrasonic sensor readings

#include <SoftwareSerial.h>

NewPing sonar(trigPin, echoPin,30); // sets up the sonar function and limits distance to 30 cm

int ledpin=7;
// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 250;           // interval at which to blink (milliseconds

void setup() {
    pinMode(ledpin,OUTPUT);
    Serial.begin(9600); //sets up serial monitor
}

void loop() {

    delay(50);

    Serial.print("Ping: ");
    Serial.print(sonar.ping_cm());
    Serial.println("cm");

    //warning
    Serial.println("cm");

    //warning
    if(sonar.ping_cm()>=30)
    {
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }

        // set the LED with the ledState of the variable:
        digitalWrite(ledpin, ledState);
      }

    }
}

```

# Answer
> 1 votes
You are initiating the `NewPing` library with `NewPing sonar(trigPin, echoPin,30);`. The last parameter is the maximum distance in cm, that will be measured. On the Arduino Playground site of the library it says

> sonar.ping\_cm(); - Send a ping, returns the distance in centimeters or 0 (zero) if no ping echo within set distance limit

You're not handling the special case of no ping (in the defined limit), which occurs everytime you exceed 30cm in your case, and your value cannot get greater than 30 cm. You can change the if-statement for your warning from

```
if(sonar.ping_cm()>=30)

```

to

```
if(sonar.ping_cm()==0)

```

---
Tags: programming, led
---


title: Send SMS Arduino Uno + SIM900A shield

text:
# Question
Title: Send SMS Arduino Uno + SIM900A shield
I am working on a module to send messages. I write the message on the serial monitor + phone number and I have to send the message to the line.

***Question:***

How to send messages through the SIM900A shield?

***Problem:*** What am I doing wrong in my code? Because I do not get an error but it does not send the SMS using the shield.

Try:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6, 7);
char msg;

void setup() {
  mySerial.begin(9600); // Setting the baud rate of GSM Module
  Serial.begin(9600); // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop() {
  if (Serial.available()>0)
    switch(Serial.read()) {
      mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
      delay(1000); // Delay of 1000 milli seconds or 1 second
      mySerial.println("AT+CMGS=\"+XXXXXXXXX\"\r"); // mobile number
      delay(1000);
      mySerial.println("sim900a sms");// The SMS text you want to send
      delay(100);
      mySerial.println((char)26);// ASCII code of CTRL+Z
      delay(1000);
    }
  if (mySerial.available()>0) Serial.write(mySerial.read());
}

```

***This is my shield***

Other try:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6, 7);
char msg;

void setup() {
  mySerial.begin(9600);  // Setting the baud rate of GSM Module
  Serial.begin(9600); // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop() {
  mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"+XXXXXXXXX\"\r"); // mobile number
  delay(1000);
  mySerial.println("sim900a sms");// The SMS text you want to send
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
}

```

# Answer
> 1 votes
There was not really a question, but I do notice there is no case's in your switch statement..

example from here

```
// do something different depending on the range value:
  switch (range) {
    case 0:    // your hand is on the sensor
      Serial.println("dark");
      break;
    case 1:    // your hand is close to the sensor
      Serial.println("dim");
      break;
    case 2:    // your hand is a few inches from the sensor
      Serial.println("medium");
      break;
    case 3:    // your hand is nowhere near the sensor
      Serial.println("bright");
      break;
  }
  delay(1);        // delay in between reads for stability

```

---
Tags: arduino-uno, shields, gsm, port-mapping
---


title: changed behaviour in I2C LCD

text:
# Question
Title: changed behaviour in I2C LCD
I reinstalled a previously working sketch to my UNO and now the behaviour of the lcd has changed.

Previously this example worked perfectly:

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd

  // Print a message to the LCD.
  lcd.backlight();
  lcd.print("Hello, world!");
}

void loop()
{
}

```

Now it only displays the very first character 'H'

This version does work though:

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd

  // Print a message to the LCD.
  lcd.backlight();
  lcd.print("H");
  lcd.print("e");
  lcd.print("l");
  lcd.print("l");
  lcd.print("o");
  lcd.print(" ");
  lcd.print("W");
  lcd.print("o");
  lcd.print("r");
  lcd.print("l");
  lcd.print("d");
}

void loop()
{
}

```

Can anyone shed me any light what is the reason of this change in behaviour and how to solve it?

Running version 1.8.3 on a W7pro PC

# Answer
> 1 votes
There seems to be an incompatibility between recent versions of the IDE and the library I was using.

Installing the latest version of the library from GitHub and replacing the `lcd.init()` command with `lcd.begin()` in my sketches solved the problem.

---
Tags: arduino-uno, i2c, lcd
---


# Question
Title: Arduino tone frequency isn't always precise
I'd like to play an asynch 'beep' sound (2.5kHz, pin 8) on an Arduino Mega with several other modules connected. I write them here, just for the record: SDCard reader and RFID reader through SPI bus, RTC through I2C, GSM module through hardware Serial 1. And I use PWM on two other pins (11,12) for controlling LEDs brightness.

It works well, however, sometimes (1 of 10) the beep frequency is about half-tone higher.

The code itself is good, because I use a constant in the tone() function call for specifying the frequency.

Does anybody have an idea what can influence the tone's PWM frequency such way, maybe on hardware level?

# Answer
As far as I know, `tone()` implements pin toggling in software (using timer interrupt), so it's possible that the frequency is lower when there's a lot of activity and higher when the CPU is mostly idle.

Try calling your beeping code alone inside an otherwise empty sketch and with no external hardware, and check out whether the sound is higher than you expect.
> 1 votes

# Answer
Half-tone, that's a lot of change. I would expect a lowering of frequency if anything from other resources being active. An increase in frequency suggests perhaps something is changing the internal counter values that is used for the toggling. 2.5KHz is 400microseconds, toggling every 200us. You might consider using Arduino "blink without delay" to monitor the passing microseconds and toggling based on that. I've created up to 20KHz signal that way, but not with anything else running.
> -1 votes

---
Tags: arduino-mega, sound
---


# Question
Title: Is there a way to play .mp3 files from an SD card on Arduino?
Is there a way to have mp3 files on an SD card in the SD card shield for the Arduino and play an mp3 file on that SD card with a buzzer?

If possible also with something like:

```
playmp3(thismp3.mp3);

```

So that if I execute that command, the Arduino will play thismp3.mp3 through a buzzer.

Thank you.

# Answer
> 1 votes
If you're not specifically trying to make the arduino itself do the decoding and playback, you can get something like the Mini DFPlayer which would let you do essentially what you're asking for and offloads the decoding and playback so your arduino can do something else while the audio is playing.

# Answer
> 0 votes
It's not as easy as that. The SD card and playing audio are two different things.

However, probably the easiest way is to buy an MP3 shield (but that spoils the fun to make it yourself).

On the other hand, to make it yourself, takes quite some effort.

Also, the audio quality will be very low. Besides that, decoding MP3 is far from trivial.

In case you want to make it yourself:

* First write a program to read (stream) bytes from the SD card
* Write an MP3 decoder (maybe/probably there are open source variants)
* Forward the MP3 bytes to the decoder
* Forward the audio bytes to the buzzer

Of course, there are time constraints otherwise you hear gaps in the music.

# Answer
> -1 votes
I believe MP3 uses licensed software that is implemented on decoder chips like VS1053. Usually one would use a board like this, with an SD card for holding the massive amount of info that makes a sound. http://www.oddwires.com/mp3-decoder-module-vs1053-for-arduino/?gclid=EAIaIQobChMInKS7lJGm2QIVE4\_ICh1kTQa4EAQYAiABEgIKH\_D\_BwE You then send commands to the unit to tell it to start, stop, advance, etc.

---
Tags: arduino-uno, sd-card, sound, sd, buzzer
---


title: Elechouse MP3 shield play random song

text:
# Question
Title: Elechouse MP3 shield play random song
Using this code to try and play a random song when someone walks by my distance sensor I get an error, the same song (track 0001) plays every time. Any advice?

```
#include <SoftwareSerial.h>
SoftwareSerial Geno(7, 8); // Rx, Tx

unsigned char Data[10];
unsigned char i;

// defines pins numbers
const int trigPin = 8;
const int echoPin = 9;

// defines variables
long duration;
int distance;

void setup() {
  delay(1000);
  Geno.begin(9600);
  delay(1000);
  SetVolume(30);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}

void playTrack(int num) {
    delay(100);

    Data[0] = 0x7E;
    Data[1] = 0x04;
    Data[2] = 0xA0;
    Data[3] = 0x00;
    Data[4] = 0x00 + num;
    Data[5] = 0x7E;
    Command(Data,5);

    play_pause();

    delay(10000);
}

void SetVolume(int vol) {
   Data[0] = 0x7E; // START
   Data[1] = 0x03; // Length Not 0x02
   Data[2] = 0xA7; // Command
   Data[3] = vol;  // new volume
   Data[4] = 0x7E; // END
   Command(Data,5);
}

void play_pause() {
  Data[0] = 0x7E; // START
  Data[1] = 0x02; // Length
  Data[2] = 0xA3; // Command
  Data[3] = 0x7E; // Mode parameter
  Command(Data,4);
}

void Command(unsigned char *Data, int length) {
  for (int i=0; i<length; i++) {
    Geno.write(Data[i]);
  }
}

void loop() {
  //Assigns a random number
  int song = random(0,200);
  Serial.print("Song is:");
  Serial.print(song);
  Serial.print("\n");
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance = duration * 0.034 / 2;

  Serial.print("Distance: ");
  Serial.println(distance);
  if (distance < 20) {
    playTrack(random(1,25));
  }
  //playTrack(1);
  //playTrack(2);
}

```

# Answer
> 0 votes
Disclaimer: I know nothing about this media player except what's in this question. I'd never heard of it before. The following is simply from observation of the code you posted.

Look at your `play_pause()` function where the meanings of all the elements are described.

```
Data[0] = 0x7E;          // START
Data[1] = 0x02;          // Length
Data[2] = 0xA3;          // Command
Data[3] = 0x7E;          //Mode parameter
Command(Data,4);

```

It seems a message starts with `0x7E`, followed by the length , followed by a command and whatever else, followed by another `0x7E`.

The length field is 1 less than the total length, so I guess it doesn't include the 'start', or whatever - there are various equivalent ways you could look at it.

In `playTrack()` you set 6 elements, but with the length element set to 4. You then tell `Command()` there are 5. So the last element (`0x7E`) won't get sent, and the length element which you have sent is wrong anyway.

The receiver is going to get into some weird state, I presume. Perhaps that explains the problem you're seeing.

# Answer
> 0 votes
`random(1,25)` is deterministic. It's PRNG should produce the same sequence of outputs in the same order each time. You need to call randomSeed() at some point, passing it an unpredictable value. Something like:

```
if(distance < 20){
  randomSeed(micros());
  playTrack(random(1,25));
}

```

---
Tags: arduino-uno, shields, audio, mathematics
---


# Question
Title: Why is there a third connection to the host in this 3 wire current output sensor diagram?
I've got a 3 wire 4-20mA current output sensor, externally powered by 12V, which I want to read from an Arduino Uno (5V). The sensor connection diagram is below, but I don't understand why it says to connect the sensor power out (12V) to the host as well?

Below that is how I think I should connect it (i.e. with the power out from the sensor simply connected back to itself). Will this work? Could I damage my board or, far worse, the sensor itself this way?

Thanks alot!

# Answer
The connection diagram is showing the sensor being powered by a host that runs at 12v. Normally the host would provide the power. However, you provide the power yourself from another source. So you don't need power from the host, so you do not connect the 12v to the host.

All you need is the signal and the ground (along with a load resistance to convert the current into a voltage, and maybe some over voltage protection on the signal in case the load resistance becomes disconnected or fails in some other way).

simulate this circuit – Schematic created using CircuitLab

In that example RL is the "Load" resistor and is calculated as the nearest common resistance value that gives, with 20mA (assuming a standard 4-20mA sensor) through it, close to 5V across it without going over. In this case, 4.4V, which is good. RP is a "protection" resistor to prevent damage to the sensor should the load resistor fail, which would give 12V (though limited in current) across the zener diode D1. It just limits the current that can flow through D1 and be pulled by an effective short circuit across the sensor's output when D1 fails over (if it ever does). D1 is there to prevent the ADC from ever seeing any more than 5.1V in the event of a problem.
> 0 votes

---
Tags: arduino-uno, sensors, voltage-level, voltage-protection
---


# Question
Title: Use Wii Remote and Arduino to emulate a keyboard for Windows 10?
Is it possible to use an Arduino to communicate with a Wii Remote, connect the Arduino to a Windows 10 computer, and have the Wii Remote inputs be translated into keyboard keys for Windows 10?

I've used several Wii Remote Windows 10 apps, such as WiiUSoft, but I find such programs very unreliable.

Thanks for any help.

# Answer
> 0 votes
The Arduino Leonardo and Arduino Micro (as well as other third-party boards, such as the Teensy and the chipKIT Lenny) can be directly programmed to emulate a keyboard. There are examples in the IDE that show how to do this.

It is possible with an Uno, but that requires replacing the firmware on the USB interface's ATMega32U4 chip with special HID firmware. This is a non-standard setup, though, and may make programming of the Arduino through the USB port impossible. So I wouldn't recommend doing that, and would instead go for a board that can directly emulate a keyboard.

There are plenty of tutorials on the web for connecting a Wii Remote with an Arduino, (including a library), so couple that with the examples in the IDE and a suitable board and you are good to go. From then on it's just a Simple Matter of Programming...

---
Tags: bluetooth, keyboard, windows
---


# Question
Title: Why am I getting only around 40% the range of my ADS1115 using an Arduino Uno?
I've connected my ADS1115 to an Arduino Uno as in the diagram (Vdd - 5V, Gnd - Gnd, SDA/SCL - SDA/SCL), all powered from the USB on a PC, with A0-3 unconnected, and am getting readings of around 3000 (i.e. 3000/65535 on 5V supply = 0.23V) from all four analog pins. Then if I connect them to 3.3V output on the arduino they give me only 17625 (i.e. 1.34V) i.e. about 40% of the full range I expected. If I try with a seperate 5V supply, it's still the same problem. Why is this?

P.S. sorry the code format below isn't very good, but basically it reads the four pins by
`int16_t V1 = ads.readADC_SingleEnded(PIN)`.

```
#define THERMISTORPIN1 0
#define THERMISTORPIN2 1
#define SHELLPTPIN 2
#define SPAREPIN 3
#include < Wire.h >
#include < Adafruit_ADS1015.h >

Adafruit_ADS1115 ads(0x48);  //16 bit ADC add-on for arduino for better temperature resolution
float Voltage = 0.0;

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

void loop(void)
{
    int16_t V1;
    int16_t V2;
    int16_t V3;
    int16_t V4;
    long cumV1;
    long cumV2;
    long cumV3;
    long cumV4;
    float avgV1;
    float avgV2;
    float avgV3;
    float avgV4;

    //take readings of voltages between resistor and thermsitor
    int i=0;

    while(i<6) {
        V1 = ads.readADC_SingleEnded(THERMISTORPIN1); //5 readings to allow the arduino capacitors to equalize with the pin voltage, to increase accuracy
        V2 = ads.readADC_SingleEnded(THERMISTORPIN2);
        V3 = ads.readADC_SingleEnded(SHELLPTPIN);
        V4 = ads.readADC_SingleEnded(SPAREPIN);
        i++;
        delay(10);
    }

    while(6<=i && i<16) {
        cumV1+= ads.readADC_SingleEnded(THERMISTORPIN1);  //multiple measurements from which to take an average, to increase precision
        cumV2+= ads.readADC_SingleEnded(THERMISTORPIN2);
        cumV3+= ads.readADC_SingleEnded(SHELLPTPIN);
        cumV4+= ads.readADC_SingleEnded(SPAREPIN);
        i++;
        delay(10);
    }

    avgV1=cumV1/10;
    avgV2=cumV2/10;
    avgV3=cumV3/10;
    avgV4=cumV4/10;

    //print out information to serial monitor on laptop
    Serial.print(V1);
    Serial.print(" ");
    Serial.print(V2);
    Serial.print(" ");
    Serial.print(V3);
    Serial.print(" ");
    Serial.println(V4);
    Serial.print(" ");
    Serial.print(avgV1);
    Serial.print(" ");
    Serial.print(avgV2);
    Serial.print(" ");
    Serial.print(avgV3);
    Serial.print(" ");
    Serial.println(avgV4);
    //Serial.println();
    delay(1000);
}

```

# Answer
Your readings are correct because you have the default gain set. You have incorrectly assumed that you can convert the ADC reading from your 16-bit ADC to Volts by dividing by `2^16 - 1`. Your ADC has gain settings to have more accurate readings for certain voltage intervals. If we look at the example sketch, we see

```
 void setup(void)
{
  Serial.begin(9600);
  Serial.println("Hello!");

  Serial.println("Getting single-ended readings from AIN0..3");
  Serial.println("ADC Range: +/- 6.144V (1 bit = 3mV/ADS1015, 0.1875mV/ADS1115)");

  // The ADC input range (or gain) can be changed via the following
  // functions, but be careful never to exceed VDD +0.3V max, or to
  // exceed the upper and lower limits if you adjust the input range!
  // Setting these values incorrectly may destroy your ADC!
  //                                                                ADS1015  ADS1115
  //                                                                -------  -------
  // ads.setGain(GAIN_TWOTHIRDS);  // 2/3x gain +/- 6.144V  1 bit = 3mV      0.1875mV (default)
  // ads.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
  // ads.setGain(GAIN_TWO);        // 2x gain   +/- 2.048V  1 bit = 1mV      0.0625mV
  // ads.setGain(GAIN_FOUR);       // 4x gain   +/- 1.024V  1 bit = 0.5mV    0.03125mV
  // ads.setGain(GAIN_EIGHT);      // 8x gain   +/- 0.512V  1 bit = 0.25mV   0.015625mV
  // ads.setGain(GAIN_SIXTEEN);    // 16x gain  +/- 0.256V  1 bit = 0.125mV  0.0078125mV

  ads.begin();
}

```

Your ADC has a default gain of 2/3, or 0.1875mV per count. You say when you connect 3.3V to the pin, you get a reading of 17625. Thus we have

```
17625 * 0.1875 / 1000.0 [V]
= 3.3046875 [V]

```

Which is a correct reading. A reading on a floating pin (nothing attached) is irrelevant. Use the correct factors from above to convert your read ADC value to voltage.

Side note: In line

```
avgV1=cumV1/10;

```

You have the `float avgV1` on the left and `cumV1` (a `long`) divided by 10 on the right; this will do a integer division. Make sure to divide by `10.0f` if you want a floating point average.

Side note 2:

These factors do make sense. If you apply positive 6.144V on the 2/3rd gain setting, you will read the maximum positive value of a `int16_t`, i.e. 2^15-1 = 32767 (solve above formula for the count). If you apply -6.144V, you get -32768; thus the full 16-bit number space is used. On differnt gain settings it analogous.
> 1 votes

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


title: writing very long function

text:
# Question
Title: writing very long function
I'm writing an Arduino program, and I need to write a function to input some numbers trough a computer connected to it trough the serial interface.

This function should perform many different and well-defined tasks, e.g.: obtain data (characters) from the computer, check if the characters are valid, transform the characters in actual numbers, and many others. Written as a single function it would be at least 500 lines long. So I'll write a group of shorter functions and one "main" function that calls the others in the only meaningful order. Those functions will never be called in the rest of the code (except of course the main function). One last thing - the functions need to pass each other quite a lot of variables.

---

What is the best way to organize those functions? My first tough was to create a class with only the "main" function in the public section and the other functions and the variables shared by different functions as private members, but I was wondering if this is good practice: I think it doesn't respect the C++ concept of "class"... for example to use this "group of functions" I would need to do something like that:

```
class GetNumbers {
    public:
        //using the constructor as what I called "main" function
        GetNumbers(int arg1, char arg2) {
            performFirstAction();
            performSecondAction();
            ...
        }
    private:
        performFirstAction() {...};
        performSecondAction() {...};
        ...

        bool aSharedVariable;
        int anotherVariable;
        ...
};

```

And where I actually need to input those numbers from the computer:

```
GetNumbers uselessName (x,y);

```

Making the "main" function a normal class method (and not the constructor) seems to be even worse:

```
GetNumbers myClass;
myClass.getNumbers(x,y);
...
//somewhere else in the same scope
myClass.getNumbers(r,s);

```

# Answer
Maybe it's my background of old C programmer but... I would just write plain functions, no classes, like in C. And I would keep all this stuff in a single file, to provide some form of encapsulation:

my\_parser.h:

```
some_type get_numbers(int arg1, char arg2);

```

my\_parser.cpp:

```
static int performFirstAction(float arg1, int arg2, char arg3)
{...}

static bool performSecondAction(long arg1, void *arg2, int arg3)
{...}

some_type get_numbers(int arg1, char arg2)
{...}

```

Note that there is only one function declared in the .h: this is the “interface” to your module. Note also that all the other functions are defined as `static`. This tells the compiler to keep them hidden from the linking phase, so they do not pollute the global namespace. And finally, note that there is no global shared variable: everything is passed as arguments to the functions.

The rationale for the last point is that this helps the compiler optimize things. A static function that is called only once is almost guaranteed to be inlined by the compiler. Which means there is no overhead in passing the arguments. On the other hand, if you use global variables and the compiler doesn't manage to optimize them away, you will incur the cost of RAM access.
> 3 votes

---
Tags: programming, c++
---


title: Hold all "millis()" values in an array?

text:
# Question
Title: Hold all "millis()" values in an array?
I'm working on a project where I could have up to six devices connected to an arduino, it might be the case that not all of them will be attached at the same time, and all of them need to be able to receive PWM signals but without using delay().

There are a number of different PWM patterns already programmed into the code, what I'd like to do is be able to assign more than one device to a single pattern, and start/stop the patterns at different times to different devices.

I have a python script (and soon an Android app) that sends a message in the following format to the device:

`<int(pin_number), string(pattern_name), int(highest_pwm_value 0 - 255), int(delay_between_pulses_in_seconds)>`

Is there some way of coding something like the following, and if so, how would I go about it?

```
array timings[];

void fade(unsigned long thisMillis, int fadeInterval, int maxPWM, int motor_pin) {
  if (thisMillis - timings[motor_pin] >= fadeInterval) {
    // yup, it's time!
    if (fadeDirection == 1) {
      fadeValue = fadeValue + fadeIncrement;
      if (fadeValue >= maxPWM) {
        // At max, limit and change direction
        fadeValue = maxPWM;
        fadeDirection = 0;
      }
    } else {
      //if we aren't going up, we're going down
      fadeValue = fadeValue - fadeIncrement;
      if (fadeValue <= minPWM) {
        // At min, limit and change direction
        fadeValue = minPWM;
        fadeDirection = 1;
      }
    }
    // Only need to update when it changes
    analogWrite(motor_pin, fadeValue);

    // reset millis for the next iteration (fade timer only)
    timings[motor_pin] = thisMillis;
  }
}

```

The bit that I'm unsure about is how the array should be defined etc, as I'm primarily a python developer so it's rare I have to explicitly set the type of an item in an array!

# Answer
This is a classic example where you want to create a class. A class will contain all the control logic for dealing with one pin - all the functions, all the variables, etc.

Then you just create as many instances of the class as you need for your different pins. Each one is completely separate from the other, and each one can be controlled at will.

For instance, you might make something like this (untested):

```
class FaderPin {

    private:
        uint32_t timestamp;
        int motor_pin;
        int fadeInterval;
        int minPWM;
        int maxPWM;
        int fadeDirection;
        int fadeValue;

    public:
        FaderPin(int pin, int minp, int maxp, int interval) {
            motor_pin = pin;
            minPWM = minp;
            maxPWM = maxp;
            fadeInterval = interval;
            fadeDirection = 1;
            fadeValue = minp;
            timestamp = millis();
        }

        void fade() {
            uint32_t thisMillis = millis();
            if (thisMillis - timestamp >= fadeInterval) {
                // yup, it's time!
                if (fadeDirection == 1) {
                    fadeValue = fadeValue + fadeIncrement;
                    if (fadeValue >= maxPWM) {
                        // At max, limit and change direction
                        fadeValue = maxPWM;
                        fadeDirection = 0;
                    }
                } else {
                    //if we aren't going up, we're going down
                    fadeValue = fadeValue - fadeIncrement;
                    if (fadeValue <= minPWM) {
                        // At min, limit and change direction
                        fadeValue = minPWM;
                        fadeDirection = 1;
                    }
               }
               // Only need to update when it changes
               analogWrite(motor_pin, fadeValue);
               // reset millis for the next iteration (fade timer only)
               timestamp = thisMillis;
           }
       }

};

```

Then you can:

```
FadePin motorOne(5, 0, 255, 10);
FadePin motorTwo(6, 0, 255, 10);

```

And regularly call:

```
motorOne.fade();
motorTwo.fade();

```
> 1 votes

# Answer
The answer given at https://forum.arduino.cc/index.php?topic=529364.msg3608306#msg3608306 is as follows:

```
struct motor_data {
   int id;
   unsigned long start_time;   //store time stamp here
   unsigned long duration;      //time ends    ...
};

motor_data motors[6] //declaration
motors[0].start_time = millis(); //accessing

```

Thoughts on this approach?
> 1 votes

---
Tags: pwm, millis
---


# Question
Title: Initialization of function pointer array
I have an array of function pointers:

```
unsigned int dimension = 8;
void (* myFunctions [dimension])();

```

This array is a member of a class:

```
class myClass {

    static const unsigned int dimension;

    void (* myFunctions [dimension])();
}

```

and in a cpp file:

```
const unsigned int dimension = 8;

```

It's size is known at compile time, but it's values will be added through a public method in unknown parts of the code. I need to be able to find out at any time whether there is a valid pointer at some index in that array at any time, and my idea was to do that by comparing the pointer against `nullptr`: if it doesn't equals it then I'll assume that it holds a valid function pointer.

I was wondering if I need to initialize the array before making that kind of speculation. How is this array initialized if I only write the above two lines of code? Can I assume something like `myFunctions[x] == nullptr` is true in that case? Or do I need to do an explicit initialization like the following one?

```
for(int i = 0; i < dimension; i++)
    myFunctions[i] = nullptr;

```

# Answer
You should actively zero-initialize your pointers in the constructor of your class.

The "zero-initialization" of the C++ language only applies in certain cases defined here. In certain configurations, e.g., when the object of the class has an explicit constructor which does not initialize the array, or when the class has no constructor and an object is function-locally created by typing `myClass myObject;`, the pointers are not initialized to `nullptr`.

They do get automatically zero-initialized via the C++ standard without you doing anything if an object of this class is declared and defined as a global variable, though. Then you have a "static storage location", and your object is zero-init'ed by zero-init'ing every data member. Your array of function pointers gets then member-wise zero-init'ed to the zero-value of a pointer, i.e., `nullptr`.

But you should write robust code which is always correct regardless of which kind of method is used to instantiate the object. Thus, the `for` loop in the constructor as you have it is correct.

See the analogous question I asked here (which I asked because I gave an initially wrong answer and felt responsible).
> 1 votes

# Answer
It's seem like the array is initialized with nullptr. I got to read the 1,600 pages C++17 specification to be sure. Meanwhile, I test.

You can always initialize explicitly the array, in the constructor.

Here a brief proof of concept for you to try. (I made public the class member to keep things short).

```
//  An empty function, do nothing
void someFunction()
{

}

class MyClass
{
public:
    MyClass()
    {
        for(int i = 0; i < dimension; i++) {
            myFunctions[i] = someFunction; // Replace with nullptr to test.
        }
    }

static const unsigned int dimension = 5;
void (*myFunctions[dimension])();
};

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

    while(!Serial);

    MyClass test;

    for(auto x : test.myFunctions) {
        if(x == nullptr) {
            Serial.println("null");
        } else {
            if(x == someFunction) {
                Serial.println("some function");
            } else {
                Serial.println("????");
            }
        }
    }
}

void loop()
{

}

```
> 1 votes

---
Tags: programming, c++
---


title: Grove A12-200 current sensor

text:
# Question
Title: Grove A12-200 current sensor
I am trying to measure current from an LFG with Arduino Uno and Grove current sensor (A12-200). I found a code at this link you can see Arduino code here.

The code works, but there are some operations that I don't understand. Let me copy and paste the code here (for further information, please follow the link above).

```
/****************************************************************************/
//  Function: Measure the amplitude current of the alternating current and
//            the effective current of the sinusoidal alternating current.
//  Hardware: Grove - Electricity Sensor
//  Date:    Jan 19,2013
//  by www.seeedstudio.com
#define ELECTRICITY_SENSOR A0 // Analog input pin that sensor is attached to

float amplitude_current;               //amplitude current
float effective_value;       //effective current

void setup()
{
    Serial.begin(9600);
    pins_init();
}
void loop()
{
    int sensor_max;
    sensor_max = getMaxValue();
    Serial.print("sensor_max = ");
    Serial.println(sensor_max);
    //the VCC on the Grove interface of the sensor is 5v
    amplitude_current=(float)sensor_max/1024*5/800*2000000;
    effective_value=amplitude_current/1.414;//minimum_current=1/1024*5/800*2000000/1.414=8.6(mA)
                        //Only for sinusoidal alternating current
    Serial.println("The amplitude of the current is(in mA)");
    Serial.println(amplitude_current,1);//Only one number after the decimal point
    Serial.println("The effective value of the current is(in mA)");
    Serial.println(effective_value,1);
}
void pins_init()
{
    pinMode(ELECTRICITY_SENSOR, INPUT);
}
/*Function: Sample for 1000ms and get the maximum value from the SIG pin*/
int getMaxValue()
{
    int sensorValue;             //value read from the sensor
    int sensorMax = 0;
    uint32_t start_time = millis();
    while((millis()-start_time) < 1000)//sample for 1000ms
    {
        sensorValue = analogRead(ELECTRICITY_SENSOR);
        if (sensorValue > sensorMax)
        {
            /*record the maximum sensor value*/
            sensorMax = sensorValue;
        }
    }
    return sensorMax;
}

```

```
effective_value=amplitude_current/1.414

```

I don't understand why dividing `amplitude_current` by 1.414 we'll get `effective_current`.

And in the function `getMaxValue()`, I know what it does, but I don't understand why we just need `maxvalue`.

# Answer
> 1 votes
You are measuring a sinusoidal "signal" that is alternating in polarity. What the code notes as "effective" current the equivalent DC current for purposes of measuring power consumption. In EE, it's called "RMS" or Root Mean Square, and it's the mathematical derivation to calculate consumed power or current in a situation where the current flows symmetrically back and forth, and thus a time average would give zero.

It's dividing the peak current by the square-root of 2 (1.414).

---
Tags: arduino-uno, current
---


title: ESP8266 Connection to Arduino Mega 2560

text:
# Question
Title: ESP8266 Connection to Arduino Mega 2560
Im trying to connect my **esp8266-01** to my **arduino mega 2560** to get the code working from the following video tutorial found on youtube:

https://www.youtube.com/watch?v=zGgUfAB4m24

This is the code Im using from the youtube video:

```
#include <SoftwareSerial.h>

#define ESP8266_rxPin 4
#define ESP8266_txPin 5

//SSID + KEY
const char SSID_ESP[] = "SSID";
const char SSID_KEY[] = "PASSWORD";

// URLs
const char URL_youtube[] = "GET https://api.thingspeak.com/apps/thinghttp/send_request?api_key=S7QNK85SG9D9YD27 HTTP/1.0\r\n\r\n";
const char URL_current_temp[] = "GET https://api.thingspeak.com/apps/thinghttp/send_request?api_key=S7QNK85SG9D9YD27 HTTP/1.0\r\n\r\n";

//MODES
const char CWMODE = '1';//CWMODE 1=STATION, 2=APMODE, 3=BOTH
const char CIPMUX = '1';//CWMODE 0=Single Connection, 1=Multiple Connections

SoftwareSerial ESP8266(ESP8266_rxPin, ESP8266_txPin);// rx tx

//DEFINE ALL FUNCTIONS HERE
boolean setup_ESP();
boolean read_until_ESP(const char keyword1[], int key_size, int timeout_val, byte mode);
void timeout_start();
boolean timeout_check(int timeout_ms);
void serial_dump_ESP();
boolean connect_ESP();
void get_youtube();
void get_current_temp();
void get_hilo_temp();

//DEFINE ALL GLOBAL VAARIABLES HERE
unsigned long timeout_start_val;
char scratch_data_from_ESP[20];//first byte is the length of bytes
char payload[150];
byte payload_size=0, counter=0;
char ip_address[16];
char youtube_subs[10];
char youtube_views[13];
char current_temp[5];
char hi_temp[5];
char lo_temp[5];

//DEFINE KEYWORDS HERE
const char keyword_OK[] = "OK";
const char keyword_Ready[] = "Ready";
const char keyword_no_change[] = "no change";
const char keyword_blank[] = "#&";
const char keyword_ip[] = "192.";
const char keyword_rn[] = "\r\n";
const char keyword_quote[] = "\"";
const char keyword_carrot[] = ">";
const char keyword_sendok[] = "SEND OK";
const char keyword_linkdisc[] = "Unlink";

//keywords for youtube
const char keyword_html_start_b[] = "b>";
const char keyword_html_end_b[] = "</b";

//keywords for current temp
const char keyword_html_start_temp[] = "p\">";
const char keyword_html_end_temp[] = "<s";
const char keyword_html_start_body = "<body>";
const char keyword_html_end_body = "</body>";

void setup(){//        SETUP     START
  //Pin Modes for ESP TX/RX
  pinMode(ESP8266_rxPin, INPUT);
  pinMode(ESP8266_txPin, OUTPUT);

  ESP8266.begin(9600);//default baudrate for ESP
  ESP8266.listen();//not needed unless using other software serial instances
  Serial.begin(115200); //for status and debug
  delay(5000);//delay before kicking things off

  setup_ESP();//go setup the ESP
}//                    SETUP     END

void loop(){//         LOOP     START

  //get_youtube(); // get youtube views and subs
  //delay(15000);//thingspeak needs ~12 secs before next connection

  get_current_temp();//current temperature
  delay(15000);

}//                    LOOP     END

```

Whenever I run the code everything just fails and Im not able to send **AT** commands from my arduino to the **ESP**.

Im using the following connection between the arduino and the ESP:

```
**ESP <---------------------> ARDUINO
GND -------------------------- GND
GP2 -------------------------- Not connected
GP0 -------------------------- Not connected
RXD -------------------------- DIGITAL PIN 4
TXD -------------------------- DIGITAL PIN 5
CHPD ------------------------ 3.3V
RST -------------------------- Not connected
VCC -------------------------- 3.3V**

```

If I connect RESET pin on the arduino to GND and the RX and TX pins on the ESP to digital pins 1 and 0 on the arduino and run the serial monitor and try the AT commands they work fine.

But when I try to run the **AT** commands by sending them from the arduino to the ESP (by running the code) I get the failed every time. What am I doing wrong?

Here is the link to the full code:

http://www.kevindarrah.com/wp-content/uploads/2015/01/ESP8266\_BASE\_01\_28\_15.zip

# Answer
> 1 votes
I fixed it by changing everything on the code from **SoftwareSerial ESP8266** to the hardware serial: **Serial1**.

I used the pins 18 and 19 of the hardware serial. I also made sure connect the **RX** pin of the ESP to the **TX** pin of the **Arduino** and do the same with the **TX** pin.

---
Tags: arduino-mega, esp8266
---


# Question
Title: How to Write a function or Loop or program to receive fixed number of Integers or characters over Serial?
I am want to receive a 5 character hexadecimal input from user over serial port of arduino Uno.

```
int count = 0;                                    // count = 0
char userInput[5];

void setup()
{
  delay(1000);
  Serial.begin(19200);                            // begin serial port with baud rate 9600bps

}
void loop()
{
  if (Serial.available() > 5)
  {
    Serial.read();
  }

  else if (Serial.available() < 4)
  {
    Serial.read();
  }

  else if (Serial.available() == 5)
  {
    for (int i = 0; i < 5; i++)
    {
      userInput[i] = Serial.read();
    }

    Serial.print("User Input - ");
    Serial.println(userInput);
  }

  delayMicroseconds(10000);
}

```

But I want to discard the input if user inters less than 5 characters or more than 5?

Since the Serial.flush() have a different meaning now, I can not clear the buffer if user enters less than or more than 5 characters and the characters gets added to next input.

e.g. If I upload above program and entered input in following sequence:

```
abcde
abcd
abcd
abcd
abcd
abcdef
abcde

```

I got the following output:

```
User Input - abcde
User Input - dabcd
User Input - dacbd
User Input - bcdef
User Input - abcde

```

Two invisible characters appear in output which are not visible but when I copied the output from serial monitor but these characters appear when I copy paste the output into Text Editor.

So How can I modify the program to receive only 5 hex character input from user (Which user will input from Hex Keypad)? And if user enters more or less character I want to clear the input buffer for next user input so that characters from previous input doesn't get added to next one.

# Answer
> 2 votes
As noted in the comments, since your prototype is receiving data from the serial port, you need some way for the user to indicate to the program that they are finished entry, since a 4-character entry is a necessary point along the way to a 5-character entry.

What you are doing now, by checking if `Serial.available()>5` is letting the serial buffer hold 6 characters before you read from it (note: 5 is not \>5), but then your `else` statement:

```
else if (Serial.available() < 4)
{
  Serial.read();
}

```

Clears out the buffer (`Serial.read()` removes one character from the buffer), so you will never get to 5 characters anyway, unless all 6 characters come in between runs of `loop()`, which is not likely at 19200 baud.

Not to mention that while data is sitting in the buffer, you don't know what it is and can't act on it. It is better to use the buffer as intended, which is to allow the Arduino to collect serial data, even while your program is working on other things, and then grab any pending data from the buffer as the program `loop()`s.

You have declared the `userInput[5]` array to hold user input, but note that if you only declare it at 5 `char`s long, it cannot hold the null-character terminator that is standard for C-style strings. It would be better to declare this as:

```
char userInput[6];  // Holds 5 user characters, plus null terminator.

```

In your `loop()`, you should copy out the contents of the buffer into your `userInput`, check the length or for a termination character, such as a carriage return or newline (i.e., pressing 'Enter' on the serial terminal.) and act accordingly. Here is an example, showing just the relevant bits for the user input and hiding the rest in \[...\]:

```
char userInput[6];  // Holds 5 user characters, plus null terminator.

void setup() {
  userInput[0] = '\0';  // Initialize string to empty
  Serial.begin(9600);
}

void loop() {
  uint8_t processInput = 0;   // Set to 1 if we have complete entry
  while (Serial.available()>0) {
    char input = Serial.read();
    if (input=='\r' || input=='\n') {
      // Have received a terminating character,
      // Flush the rest of the buffer
      while (Serial.available()) {
        Serial.read();
      }

      processInput = 1;

    } else {
      int s_len = strnlen(userInput, 5); // Get current length of userInput
      if (s_len<5) {
        userInput[s_len++] = input;      // Append character
        userInput[s_len] = '\0';         // Null-terminate string
      } else {
        // User has entered more than 5 characters and no terminating
        // character; here is where you can decide to clear the userInput
        // and start over, or just drop the first character and care
        // about the most recent 5, etc. Here, we will clear the input
        // and start over; The 6th character is dropped/ignored and
        // user input starts again. It is as though the 6th character
        // entered is like pressing Enter, but it does not process
        // the incoming data, beacuse 6 characters is an invalid input.
        userInput[0] = '\0';
        s_len = 0;
        processInput = 0;
        // Invalid input
        Serial.println("Error: invalid data");
      }
    }
  }

  if (processInput) {
    Serial.print("User input - ");
    Serial.println(userInput);

    if (strnlen(userInput, 5)==5) {
      // Do something **here** with the input string!!

      // Reset input string
      userInput[0] = '\0';
    } else {
      // Invalid input
      userInput[0] = '\0';
      Serial.println("Error: invalid data");
    }
    processInput = 0;
  }
}

```

Note, this code is not fully tested and may contain bugs. In particular, I did not intensely check if the `while (Serial.available()) {}` properly handles a lot of extra data.

One final note, you don't need the `delay()` with this code.

**EDIT:**

I tried the sample code above and it had a couple of bugs, one of which was that after a successful 5-digit entry, the input string was not reset to empty. I have now updated the code and it's a valid, working program to receive and process a 5-character input on the serial port and to toss an error if fewer than 5 or more than 5 characters are entered. Entry is terminated with a carriage return or newline (enter key).

# Answer
> -1 votes
I wrote following program, it receives 5 character input from user and if user enters input more than 5 characters then program store only 1st 5 characters and if user inputs less than 5 characters long the it rejects than input altogether..

```
char userInput[5];
void setup()
{
//delay(1000);
Serial.begin(9600); // begin serial port with baud rate 9600bps
}

void loop()
{
if (Serial.available() < 5)
{
   Serial.read();
}
else if (Serial.available() >= 5)
{
      for (int i = 0; i < 5; i++)
      {
        userInput[i] = Serial.read();
      }
     while (Serial.available() > 0)
     {
       Serial.read();
     }
Serial.print("User Input - ");
Serial.println(userInput);
}
delay(100);
}

```

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