# Question
Title: Understanding flow of current with pull-up and pull-down circuits
I am new to all of this and was trying to figure out what was happening with pull-up/pull-down circuits. I think I understand what happens when the board handles the pull-up/pull-down but I wanted to try to build the circuits. I got help from another forum. Once I made the circuits, I found that I don't understand the path that the voltage is traveling. I have 2 examples with multimeters attached.

Pull Up

I understand the press of the button connect circuit to ground. But why does the voltage everywhere go down to zero when it is connected to ground? Does it have something to do with the multimeter can't read the voltage because the current is taking the path of least resistance - which I have read is a myth?

Pull Down

When compared to the Pull Up, why does the voltage go to 5 before the yellow wire when the button is pushed? Isn't it connected to the ground again which seems like it should cause the same scenario as the Pull Up where they all read zero. Or does the resistor before ground have something to do with this.

I know nothing about electronics. Some information and links where I could find more information would be great. Thanks.

All the gifs are screen recordings from circuits I built with circuits.io. I want to get into making somethings but wanted to practice first before I spent any money.

# Answer
> 3 votes
It's very hard to read your circuit, because there are wires everywhere. However this is effectively what a switch and a pull-up resistor looks like:

Due to the pull-up, pin 8 on the Arduino (which the switch is connected to) is normally pulled-up to 5V if the switch is open.

When you close the switch pin 8 becomes 0V, thus your meter reads 0V.

---

On the other hand, with a pull-down resistor, the circuit looks like this:

Now pin 8 is normally zero volts with the switch open, and when closed pin 8 is connected to 5V to pin 8 becomes 5V.

---

See my tutorial on switches for more details.

---

> What happens with the flow of current and the resistor to make one example read high and the other low.

Imagine a door with a spring on it to close it. The spring is like a pull-up (or pull-down) resistor (depending on whether you are trying to keep the door closed or open).

The spring *gently* pulls the door shut. However if you barge out of it with a handful of pizzas in your hand your override the spring. In the absence of the spring the door would just flap in the breeze, sometimes opening and sometimes closing.

The point is, a person is strong enough to force the door open, despite the spring. Similarly if you close the switch you override the pull-up (or pull-down) resistor.

---

> Where does the 5V go when the switch is closed.

It flows through the resistor to ground (or 5V depending on which one you are talking about).

---

> When the switch is open in the pull up example - is voltage going through the resistor? From what I'm reading online, in the pull up case voltage isn't traveling through the resistor until the button is pressed.

Voltage doesn't "go through" a resistor, current does.

---

With the switch open, effectively a tiny amount of current goes through the resistor to pin 8. It is a "high impedance" input which means it puts a very small load on the input. Thus there is a very small voltage drop over the 10k resistor, and almost the full 5V is presented to the input pin for reading.

To work out the exact amount, we can look at the datasheet which says that the maximum leakage current through an I/O pin at 5V is 1 µA. Now using Ohm's Law we can find the voltage drop over the 10k resistor:

```
V = I * R
V = 0.000001 * 10000
V = 0.01 V

```

Thus with 5V at the 5V pin of the processor, and a (maximum of) 1 µA consumed at pin 8, it will therefore have 4.99 V at the pin, which therefore reads `HIGH`.

---

With the switch closed, then we use Ohm's Law to calculate the flow through the resistor:

```
I = V / R
I = 5 / 10000
I = 0.0005 A

```

Thus 0.5 mA flows through the resistor with the switch closed. This is not enough to damage the resistor, or make a significant load on the 5V line.

---

I think you are getting confused (as I did when I was young) that a big resistance (like 10k) must "resist" a lot of voltage. It is easy to think that after going through 10k resistance there can't be much "voltage" left.

The fact is, though, that the voltage on the other end of a resistor is proportional to *not only* the resistance (R) but *also* the current (I). This is Ohms's Law (`V = I * R`)

So, if the current is very small (as is the case with an input pin) then the voltage drop over a resistor - even a large one - is very small.

So, the idea of a pull-up resistor is, that with no external influences (like a switch) then after passing through 10k resistance, there is still 5V at the other side.

Let me issue you with a challenge. Find a voltage source (eg. a battery). Measure it with your multimeter. Let's say you have a 5V source which is the Arduino 5V pin. Now get a 10k resistor. Put it in series with the 5V source. Now measure it on the other side of the resistor. Depending on the quality of the meter (and thus how much current it takes to measure a voltage) you will get very close to the same voltage reading. In my case I had 5V on one side of the resistor, and 4.99V on the other side. This is exactly what my calculations above predicted.

---
Tags: arduino-uno, voltage-level, current
---


# Question
Title: Arduino Due - creating an 8Mhz clock signal
I am attempting to interface a OV7670 camera to an arduino Due. (I am fairly new to this although have been programming for many years).

I need to generate a clock signal for the camera at a minimum of 8Mhz - I realise using the pre-scalers I can only get an approximation but I am cool with that.

I finally got a nice steady 3mhz signal from the sketch below (note that the irq routine for TC6 is not used and will be removed very soon (as soon as I get home).

I think I have a conceptial problem with the timers because as I am initialising RA and RC to 1 and telling via TC\_Configure to toggle the line, and because I am using CLOCK1 (42 Mhz), I believe with those values of RA and RC I should be getting a 21'ish MHZ signal.

Ie RA starts at zero. First CLOCK1 tick. (at second/48,000,000) interval. RA Goes to 1 COmpares to RC Because they are equal, resets RA to 0 and toggles TIOA6 Next Clock1 tick occurs.....

As I said I am only getting a 3Mhz signal.

```
void TC6_Handler()
{
        TC_GetStatus(TC2, 0);

}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) {
        pmc_set_writeprotect(false);
        pmc_enable_periph_clk((uint32_t)irq);

        TC_Configure(tc, channel,
               TC_CMR_WAVE |
               TC_CMR_WAVSEL_UP_RC |
               TC_CMR_TCCLKS_TIMER_CLOCK1|
               TC_CMR_ACPA_TOGGLE );  // RC compare TOGGLES TIOA);

        TC_SetRA(tc, channel, 1); //50% high, 50% low
        TC_SetRC(tc, channel, 1);

        PIO_Configure(PIOC,
                   PIO_PERIPH_B,
                   PIO_PC25B_TIOA6,
                   PIO_DEFAULT);

       TC_Start(tc, channel);

}

void setup(){

        startTimer(TC2, 0, TC6_IRQn);
}

void loop(){
}

```

# Answer
> 1 votes
the code below should give you a 8.4MHz signal on digital pin 7 of the due. I have used it to generate a 4.2MHz clock (by setting `REG_PWM_CPRD6 = 20;` and `REG_PWM_CDTY6 = 10;` but I think it should work for a 8.4MHz clock also.

I have been using this to provide a 4.2MHz clock signal instead of using a crystal oscillator for an ADE7913 and can confirm it is working well in that application. I have taken this from the arduino forum here.

```
#include <Arduino.h>

const unsigned long serialPeriodMillis = 2000;
unsigned long previousMillis = 0;

void setup()
{
  int32_t mask_PWM_pin = digitalPinToBitMask(7);
  REG_PMC_PCER1 = 1 << 4;                         // activate clock for PWM controller
  REG_PIOC_PDR |= mask_PWM_pin;                   // activate peripheral functions for pin (disables all PIO functionality)
  REG_PIOC_ABSR |= mask_PWM_pin;                  // choose peripheral option B
  REG_PWM_CLK = 0;                                // choose clock rate, 0 -> full MCLK as reference 84MHz
  REG_PWM_CMR6 = 0 << 9;                          // select clock and polarity for PWM channel (pin7) -> (CPOL = 0)
  REG_PWM_CPRD6 = 10;                             // initialize PWM period -> T = value/84MHz (value: up to 16bit), value=10 -> 8.4MHz
  REG_PWM_CDTY6 = 5;                              // initialize duty cycle, REG_PWM_CPRD6 / value = duty cycle, for 10/5 = 50%
  REG_PWM_ENA = 1 << 6;                           // enable PWM on PWM channel (pin 7 = PWML6)

  Serial.begin(115200);
  Serial.println("Serial on");
}

void loop()
{
  if (millis() - previousMillis > serialPeriodMillis) {
    Serial.println("TIC");
    previousMillis = millis();
  }
}

```

# Answer
> 1 votes
Example from Khalid Abdulla is correct, but I used 10.5 MHz for my ov7670 camera:

```
int32_t mask_PWM_pin = digitalPinToBitMask(7);
REG_PMC_PCER1 = 1<<4;               // activate clock for PWM controller
REG_PIOC_PDR |= mask_PWM_pin;  // activate peripheral functions for pin (disables all PIO functionality)
REG_PIOC_ABSR |= mask_PWM_pin; // choose peripheral option B
REG_PWM_CLK = 0;                     // choose clock rate, 0 -> full MCLK as reference 84MHz
REG_PWM_CMR6 = 0<<9;             // select clock and polarity for PWM channel (pin7) -> (CPOL = 0)
REG_PWM_CPRD6 = 8;                // initialize PWM period -> T = value/84MHz (value: up to 16bit), value=8 -> 10.5MHz
REG_PWM_CDTY6 = 4;                // initialize duty cycle, REG_PWM_CPRD6 / value = duty cycle, for 8/4 = 50%
REG_PWM_ENA = 1<<6;               // enable PWM on PWM channel (pin 7 = PWML6)

```

My results: Arduino Due and OV7670

# Answer
> 0 votes
1) Timer counts close to zero are useless... i.e. they work same, as if count = 0; (I ran Due timers with TIMER\_CLOCK\_2 i.e. MCK/8 or 10.5MHz many times)

2) Select a reasonable pre-scalar depending on output frequency you need such that RC count will be a bit more. Here 42 MHz (TIMER\_CLOCK\_1) means you need a count of RC = 5 approximately (with RA = RC/2 for 50% duty ratio) for 8 MHz. When RA closes to RC we get output of half frequency i.e. close to 4 MHz.

I think here better option is to use master clock itself i.e. 84 MHz, then RC = 10 (approximately)(with RA = RC/2 for 50% duty ratio). Master clock can be selected using TIMER\_CLOCK\_5 (I am not sure..please check in the data sheet).

May be Arduino Due (with its clock and using timers) is not good option to generate pulses at that higher frequency (you can't execute other routines in just 10 clock cycles!) . If no additional processing is needed, why not go for a pulse generating IC....just my opinion :-)

---
Tags: arduino-due
---


title: PWM output voltage too high

text:
# Question
Title: PWM output voltage too high
I'm experimenting with PWM with the code below, but (according to my analog multimeter) the voltage on the output pins reach up to 5V whilst the largest `analogRead(IN1)` value is only around 700:

```
const int EN1 = 5;
const int EN2 = 6;
const int EN3 = 7;

const int IN1 = 9;
const int IN2 = 10;
const int IN3 = 11;

// SPWM (Sine Wave)
// const int pwmSin[] = {127, 138, 149, 160, 170, 181, 191, 200, 209, 217, 224, 231, 237, 242, 246, 250, 252, 254, 254, 254, 252, 250, 246, 242, 237, 231, 224, 217, 209, 200, 191, 181, 170, 160, 149, 138, 127, 116, 105, 94, 84, 73, 64, 54, 45, 37, 30, 23, 17, 12, 8, 4, 2, 0, 0, 0, 2, 4, 8, 12, 17, 23, 30, 37, 45, 54, 64, 73, 84, 94, 105, 116 };

/// SVPWM (Space Vector Wave)
//const int pwmSin[] = {128, 147, 166, 185, 203, 221, 238, 243, 248, 251, 253, 255, 255, 255, 253, 251, 248, 243, 238, 243, 248, 251, 253, 255, 255, 255, 253, 251, 248, 243, 238, 221, 203, 185, 166, 147, 128, 109, 90, 71, 53, 35, 18, 13, 8, 5, 3, 1, 1, 1, 3, 5, 8, 13, 18, 13, 8, 5, 3, 1, 1, 1, 3, 5, 8, 13, 18, 35, 53, 71, 90, 109};
const int pwmSin[] = {128, 132, 136, 140, 143, 147, 151, 155, 159, 162, 166, 170, 174, 178, 181, 185, 189, 192, 196, 200, 203, 207, 211, 214, 218, 221, 225, 228, 232, 235, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 248, 249, 250, 250, 251, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 253, 253, 253, 252, 252, 251, 250, 250, 249, 248, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 248, 249, 250, 250, 251, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 253, 253, 253, 252, 252, 251, 250, 250, 249, 248, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 235, 232, 228, 225, 221, 218, 214, 211, 207, 203, 200, 196, 192, 189, 185, 181, 178, 174, 170, 166, 162, 159, 155, 151, 147, 143, 140, 136, 132, 128, 124, 120, 116, 113, 109, 105, 101, 97, 94, 90, 86, 82, 78, 75, 71, 67, 64, 60, 56, 53, 49, 45, 42, 38, 35, 31, 28, 24, 21, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 21, 24, 28, 31, 35, 38, 42, 45, 49, 53, 56, 60, 64, 67, 71, 75, 78, 82, 86, 90, 94, 97, 101, 105, 109, 113, 116, 120, 124};

int currentStepA;
int currentStepB;
int currentStepC;
int sineArraySize;
int increment = 0;
boolean direct = 1; // direction true=forward, false=backward

//////////////////////////////////////////////////////////////////////////////

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

  setPwmFrequency(IN1); // Increase PWM frequency to 32 kHz  (make unaudible)
  setPwmFrequency(IN2);
  setPwmFrequency(IN3);

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);

  pinMode(EN1, OUTPUT);
  pinMode(EN2, OUTPUT);
  pinMode(EN3, OUTPUT);

  digitalWrite(EN1, HIGH);
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, HIGH);

  sineArraySize = sizeof(pwmSin)/sizeof(int); // Find lookup table size
  int phaseShift = sineArraySize / 3;         // Find phase shift and initial A, B C phase values
  currentStepA = 0;
  currentStepB = currentStepA + phaseShift;
  currentStepC = currentStepB + phaseShift;

  sineArraySize--; // Convert from array Size to last PWM array number
}

//////////////////////////////////////////////////////////////////////////////

void loop() {

  analogWrite(IN1, pwmSin[currentStepA]);
  analogWrite(IN2, pwmSin[currentStepB]);
  analogWrite(IN3, pwmSin[currentStepC]);

  if (direct==true) increment = 1;
  else increment = -1;

  currentStepA = currentStepA + increment;
  currentStepB = currentStepB + increment;
  currentStepC = currentStepC + increment;

  //Check for lookup table overflow and return to opposite end if necessary
  if(currentStepA > sineArraySize)  currentStepA = 0;
  if(currentStepA < 0)  currentStepA = sineArraySize;

  if(currentStepB > sineArraySize)  currentStepB = 0;
  if(currentStepB < 0)  currentStepB = sineArraySize;

  if(currentStepC > sineArraySize)  currentStepC = 0;
  if(currentStepC < 0) currentStepC = sineArraySize;

  /// Control speed by this delay
  delay(10);
  Serial.println(analogRead(IN1));
}

void setPwmFrequency(int pin) {
  if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
    if(pin == 5 || pin == 6) {
      TCCR0B = TCCR0B & 0b11111000 | 0x01;
    } else {
      TCCR1B = TCCR1B & 0b11111000 | 0x01;
    }
  }
  else if(pin == 3 || pin == 11) {
    TCCR2B = TCCR2B & 0b11111000 | 0x01;
  }
}

```

If `analogRead(IN1)` is just around 700 max, shouldn't the voltage be around 3.5V (700/1023 * 5V)? How come the output voltage is so high?

Any help would be appreciated.

# Answer
It seems that you misunderstand how pwm works. Pwm is the modulation of duty cycle, so the pin are outputting square waves 0-5v at the same frequency, but varying the time it's low and the time it's high. Your multimeter probably is only displaying high intervals, instead your analog read probably has filters and calculates the efficient voltage of the sine wave (divide max for sqr(2)).
> 2 votes

---
Tags: arduino-nano, c, pwm, analogread, analogwrite
---


# Question
Title: I want to play a sound based on my ultrason sensor reading
The idea is to play the tone that is given by the center value read it by the center ultrasound sensor.

The code that is in Arduino is this one:

```
#include NewPing.h

#define PING_CENTER  2  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
#define PING_RIGHT  3
#define PING_LEFT  4
#define PING_MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define buzzerPin = 10

long buzzerFreq1; // The frequency to buzz the buzzer
unsigned int BUZZ_FREQ_MAX = 2500; // Maximum frequency for the buzzer
unsigned int US_MAX = 2023; // Maximum value for ultrason sensor
int c1;

NewPing sonar2(PING_CENTER, PING_CENTER, PING_MAX_DISTANCE); // NewPing setup of pin and maximum distance.
NewPing sonar3(PING_RIGHT, PING_RIGHT, PING_MAX_DISTANCE);
NewPing sonar4(PING_LEFT, PING_LEFT, PING_MAX_DISTANCE);

void setup() {
  Serial.begin(9600);
  pinMode(buzzerPin, OUTPUT); // set pin for buzzer output
}

void loop() {
  buzzerFreq1 = (center * BUZZ_FREQ_MAX) / US_MAX;
  buzz(buzzerPin,buzzerFreq1,10);
  // tone(buzzerPin, center);
  delay(500);  // Wait 500ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int center = sonar2.ping() / US_ROUNDTRIP_CM; // Send ping, get ping time in microseconds (uS) and convert it to centimeters (cm)
  unsigned int right = sonar3.ping() / US_ROUNDTRIP_CM;
  unsigned int left = sonar4.ping() / US_ROUNDTRIP_CM;
  // Serial.println("Distance: " + String(distanceInCms) + "cm");

  Serial.println(center);
  Serial.println(right);
  Serial.println(left);

}

 // buzz(buzzerPin, buzzerFreq1, 10);
 void buzz(int targetPin, long frequency, long length) {
 // int c1 = center;
  buzzerFreq1 = (center * BUZZ_FREQ_MAX) / US_MAX;
  long delayValue = 1000000/frequency/2;

  int numCycles = frequency * length/1000;

  for (int i=0; i < numCycles; i++){
    digitalWrite(targetPin,HIGH);
    delayMicroseconds(delayValue);
    digitalWrite(targetPin,LOW);
    delayMicroseconds(delayValue);
  }
}

```

And I receive the following error that I have no idea how to solve it.

```
ultrason_onewire_sound.cpp: In function ‘void setup()’:
ultrason_onewire_sound.cpp:26:11: error: expected primary-expression before ‘=’ token
ultrason_onewire_sound.cpp: In function ‘void loop()’:
ultrason_onewire_sound.cpp:38:8: error: expected primary-expression before ‘=’ token
ultrason_onewire_sound.cpp: In function ‘void buzz(int, long int, long int)’:
ultrason_onewire_sound.cpp:48:18: error: ‘center’ was not declared in this scope

```

# Answer
> 4 votes
`#define buzzerPin = 10` shouldn't have an `=` in it.

With the `=` `pinMode(buzzerPin, OUTPUT);` will turn into `pinMode(= 10, OUTPUT);` by the pre-processor. Which would give the error, complaining about an `=` token, you got.

# Answer
> 0 votes
You should use arduino built in tone command to play sounds with a buzzer, it will simplify your code and your errors.

---
Tags: arduino-nano
---


title: Array of Strings and Callbacks

text:
# Question
Title: Array of Strings and Callbacks
I am trying to create an array of structs that contain pairs of Strings and Callbacks the problem I am having is assigning the callback function. I have the following code:

```
#define UI_ROUTINE_ITEMS 10

struct MenuItem{
    String label;
    typedef void (*callback)();
};

class MenuSystem{
   MenuItem routineMenu[UI_ROUTINE_ITEMS];

   MenuSystem(){
      routineMenu[0] = {"Test", &Test::TestCallback};
   }
}

class Test{
   void TestCallback(){
      Serial.println("Callback called");
   }
}

```

When I try to compile this I get:

```
error: no match for 'operator=' (operand types are 'MenuItem' and '<brace-enclosed initializer list>')

```

I know this is a Syntax issue I just can not figure out how this should be done. I have looked at several examples but I can't figure out how to do this with Classes without using free/malloc, what am I doing wrong?

---

**EDIT**

---

I finally got this working, the problem was that the function that I was trying to call was not static and the declaration in the structure was not quite right. Below is the corrected example:

```
#define UI_ROUTINE_ITEMS 10

#include <Arduino.h>

struct MenuItem{
    String label;
    void (*callback)(void);
};

class MenuSystem{
   MenuItem routineMenu[UI_ROUTINE_ITEMS];

   MenuSystem(){
      routineMenu[0] = {"Test", &Test::TestCallback};
   }
}

class Test{
   public static void TestCallback(){
      Serial.println("Callback called");
   }
}

```

# Answer
> 1 votes
Several issue with this code. First, use public/protected/private for classes. Second, use a const char\* instead of String or even better str\_P. It is the usage of String that is giving the compile error. Third, the Test::TestCallback function reference is not possible. It is a member function. To correct that either have an instance or define the callback function as static.

You could define an abstract MenuItem class with the string and a virtual member function. A Menu class would hold a collection of MenuItems. All the static data should be put in program memory.

There is a Menu system in Cosa. Please see the example sketch. This implementation follows the MVC design pattern.

Cheers!

# Answer
> 0 votes
Your system works in pure C too:

```
typedef struct _MenuItem
{
    const char *label; // or String if you like
    void (*callback)();
} MenuItem;

void testCallback()
{
    Serial.println("testCallback() Called");
}

MenuItem menu_system[10];
void setup()
{
    menu_system[0].label    = "Test";
    menu_system[0].callback = testCallback;

    ... # more menu definitions with callbacks
}

void loop()
{
    unsigned int user_menu_selection;

    ... # some menu code, user selection in <user_menu_selection>

    menu_system[user_menu_selection].callback();  // TODO: error checking
}

```

It might be a good idea to store any static Menu Strings into PROGMEM.

# Answer
> 0 votes
A pointer to a member instance function **is** possible:

```
void (Some_class::*Some_fnc_ptr)();

```

And in order to call different classes than just "Test" you'd have to play some games with templates and probably virtual functions. It would get pretty involved, but doable.

# Answer
> 0 votes
I know that you've resolved your dilemma, but I just wanted to show you a trick: personally, I ***hate*** the pointer-to-function mechanism that everyone uses, when there's a perfectly good alternative.

Here's a function that takes an `int` and returns a `char`:

```
char SomeFn(int i);

```

Here's a `typedef` describing that function as a type:

```
typedef char Fn(int i);

```

Looks pretty similar, huh? What's the point? Now that you've got a type, you can use that instead:

```
void SetCallback(Fn *fn);

```

`SetCallback` takes as a parameter a pointer to a function of type `Fn`. The `*` is necessary, and (to me) makes more sense than trying to barrel the pointer-ness inside the type itself - which is what leads to the parenthesis overload. You can call it like this:

```
SetCallback(&SomeFn);

```

What could be easier? If `SomeFn` was a `static` member of a class, you could just as easily use that:

```
SetCallback(&Class::SomeFn);

```

---
Tags: arduino-mega, c++, callbacks, array
---


# Question
Title: I'm having some undefined references and can't figure out why
Try verifying the code to see the errors. This is on a arduino nano with a 328 processor. I put the necessary library in the code. Pastebin for code

```
 #ifndef Pushbutton_h
#define Pushbutton_h

#include <Arduino.h>

#define PULL_UP_DISABLED    0
#define PULL_UP_ENABLED     1

#define DEFAULT_STATE_LOW   0
#define DEFAULT_STATE_HIGH  1

/*! \brief The pin used for the button on the
 * [Zumo Shield for Arduino](http://www.pololu.com/product/2504).
 *
 * This does not really belong here in this general pushbutton library and will
 * probably be removed in the future. */
#define ZUMO_BUTTON 12

class PushbuttonStateMachine
{
public:
  PushbuttonStateMachine();
  bool getSingleDebouncedRisingEdge(bool value);
private:
  uint8_t state;
  uint16_t prevTimeMillis;
};

class PushbuttonBase
{
public:

  PushbuttonBase();

  // wait for button to be pressed, released, or pressed and released
  void waitForPress();
  void waitForRelease();
  void waitForButton();

  // more complex functions that return true once for each button transition
  // from released to pressed or pressed to released
  bool getSingleDebouncedPress();
  bool getSingleDebouncedRelease();

  // indicates whether button is currently pressed
  bool isPressed();

  // Initializes I/O pin for use as button input.
  // This gets called automatically so normally you will not need to call this,
  // but it might be useful if the pin for the button is in the wrong state.
  virtual void init2() = 0;

protected:

  virtual bool _isPressed() = 0;

private:

  PushbuttonStateMachine pressState;
  PushbuttonStateMachine releaseState;
  bool initialized;

  // TODO: move all this init stuff down into Pushbutton
  inline void init()
  {
    if (!initialized)
    {
      initialized = true;
      init2();
    }
  }
};

/* \class Pushbutton Pushbutton.h
 * \brief Interface with pushbuttons on dedicated pins.
 *
 */
class Pushbutton : public PushbuttonBase
{
public:

  // constructor; takes arguments specifying whether to enable internal pull-up
  // and the default state of the pin that the button is connected to
  Pushbutton(uint8_t pin, uint8_t pullUp = PULL_UP_ENABLED,
      uint8_t defaultState = DEFAULT_STATE_HIGH);

  virtual void init2();

protected:

  virtual bool _isPressed();

private:

   uint8_t _pin;
   bool _pullUp;
   bool _defaultState;
 };

 #endif

// PIN Configurations #define SEARCH_SPEED 255

#define echoPin A0
#define triggerPin 3
#define rightBackMotor 4
#define rightMotorSpeed 10
#define leftMotorSpeed 9
#define leftForwardMotor 7  //if a motor goes backward swap the number on the FwdPin and BckPin
#define rightForwardMotor 8   //if a motor goes backward swap the number on the FwdPin and BckPin
#define leftBackMotor 11
#define LED 13
#define leftSensor A1
#define rightSensor A2
#define IRdriver 6

// Robot Configuration Parameters
// Speed range is -255 -> 255
#define MAX_SPEED 255
#define QTR_Threshold 500
#define ATTACK_DISTANCE 25
#define BACKUP_DISTANCE 4000
#define SEARCH_SPEED 255

// State variables
bool isBackup = false;
int backupTimer = 0;
long distance = 1000;
Pushbutton button(ZUMO_BUTTON);

void setSpeed(int speed, int motor);

void setup() {
   Serial.begin(9600);
   Serial.println("Setup.");

  pinSetup();

   Serial.println("Waiting for button");
}

void loop() {
   digitalWrite(IRdriver, HIGH);

  if (button.isPressed()) {
    // if button is pressed, stop and wait for another press to go again
    button.waitForRelease();
    waitForButtonAndCountDown();
 }

  int leftInput = analogRead(leftSensor);
  int rightInput = analogRead(rightSensor);

  if ( isBackup ) {
    backupTimer = backupTimer + 1;
    setSpeed(-MAX_SPEED, 0);
    setSpeed(-MAX_SPEED + 20, 1);
    if (backupTimer >= BACKUP_DISTANCE ) {
      isBackup = false;
      backupTimer = 0;
    }
  } else {
    if ( leftInput <= 500 || rightInput <= 500 ) { // WHITE LINE ABORT!
      //Serial.println("Abort! - "); Serial.println(leftInput); Serial.println(rightInput);
      isBackup = true;
      setSpeed(-MAX_SPEED, 0);
      setSpeed(-MAX_SPEED, 1);
    } else {
      distance = getDistance();
      if ( distance <= ATTACK_DISTANCE ) { // ATTACK!
        Serial.println("Attack!");
        setSpeed(MAX_SPEED, 0);
        setSpeed(MAX_SPEED, 1);
      } else { // search
        // TODO(erh): implement other searching algorithms
        Serial.println("Search");
        setSpeed(SEARCH_SPEED, 0);
        setSpeed(-SEARCH_SPEED, 1);
      }
    }
  }
}

void pinSetup() {
  // motors!
  pinMode(leftMotorSpeed, OUTPUT);
  pinMode(rightMotorSpeed, OUTPUT);
  pinMode(leftForwardMotor, OUTPUT);
  pinMode(leftBackMotor, OUTPUT);
  pinMode(rightForwardMotor, OUTPUT);
  pinMode(rightBackMotor, OUTPUT);

   // sonar sensor
  pinMode(LED, HIGH);
  pinMode(triggerPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // qtr light sensor
  pinMode(leftSensor, INPUT);
  pinMode(rightSensor, INPUT);
  pinMode(IRdriver, OUTPUT);
}

void setSpeed(int speed, int motor = 0) {
  int speedPin, forwardPin, backPin;
  if ( motor == 0 ) {
    speedPin = leftMotorSpeed;
    forwardPin = leftForwardMotor;
    backPin = leftBackMotor;
  } else if ( motor == 1 ) {
    speedPin = rightMotorSpeed;
    forwardPin = rightForwardMotor;
    backPin = rightBackMotor;
  }

  if ( speed == 0 ) {
    analogWrite(speedPin, 0);
    digitalWrite(forwardPin, LOW);
    digitalWrite(backPin, LOW);
  } else if ( speed > 0 ) {
    digitalWrite(forwardPin, HIGH);
    digitalWrite(backPin, LOW);
    analogWrite(speedPin, speed);
  } else if ( speed < 0 ) {
    digitalWrite(forwardPin, LOW);
    digitalWrite(backPin, HIGH);
    analogWrite(speedPin, abs(speed));
  }
}

long getDistance() {
  long duration, distance;
  digitalWrite(triggerPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(triggerPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  return distance;
}

void waitForButtonAndCountDown() {
  digitalWrite(LED, HIGH);
  button.waitForButton();
  digitalWrite(LED, LOW);

  for (int i = 0; i < 3; i++ ) {
    Serial.println(i);
    delay(1000);
  }

  delay(1000);
  Serial.println("ATTACK!");
  delay(1000);
}

```

# Answer
Your code contains only the header declarations (`.h` file) for those classes. There should also be another file (probably `.cpp`) that actually implements the code for the classes.

What you pasted looks very similar to the `Pushbutton` stuff in this project on GitHub.

You can look at their `Pushbutton.h` and `Pushbutton.cpp` files to get an idea of what I mean. In fact, you might be able to use those files instead of what you have. I can verify that it does compile, but not whether it works or not.
> 1 votes

# Answer
The error `Undefined reference` is a linker error, which means that the Arduino ecosystem is missing some of the pieces for the build. If you have indeed provided `PushButton.cpp` \- whether in a library or not - you need to put a `#include` of `Pushbutton.h` inside the `.ino` file. This tells Arduino that you want to include `PushButton`'s code as well as everything else.

If `Pushbutton.cpp` is inside the same directory as the `.ino` file then that will "just work". If it's elsewhere, you need to tell Arduino.
> 0 votes

---
Tags: arduino-nano
---


# Question
Title: Two Identical Potentiometers, two different results
quick question. I have two 10 turn precision potentiometers and I tested both when I bought them a few weeks ago, both worked as expected. However now that I have epoxied one of them into my project and wired it up, I don't get any resistance. I get a max reading all the time regardless of where the dial is set. So then I pull off the wiring and do the same setup with the other potentiometer and I am still getting expected results.

What could be the reasoning for the sudden difference in readings? Could the first one have gone bad, and if so how often does this happen and how can I avoid it in the future?

Everything falls within recommended specs of the pot and neither has been really used at all.

# Answer
> 1 votes
Multi turn pots range in size from about sugar cube dimensions:

...to weighing a pound or more:

It would be easy to imagine epoxy entering a small plastic multi turn pot and "freezing" the parts within. If this is what happened, try using a faster curing glue or mount the pot on a Printed Circuit Board (PCB) and glue the PCB.

# Answer
> 1 votes
Trimmers have a really low current rating, so if you hadn't protect it enough, maybe you have broken it. Always remember a pull up resistor of 10k or more.

---
Tags: wires
---


title: Bluetooth module as MCU?

text:
# Question
Title: Bluetooth module as MCU?
**Can I use Bluetooth Low energy devices as micro controllers directly instead of communicating to Arduino** e.g. HM-10/11 or even HC-05/06 ? If so **what are limitations** e.g. can I hook sensors or control other stuff like LEDs or transistors with PWM ?

---

*I have built a motion sensor, which consists of Arduino, Bluetooth Low energy HM-11, battery and sensor itself. It worked just fine, but one guy told me that Arduino may be completely unnecessary and that Bluetooth module could replace its functionality ! I then started digging for information, and either it's impossible or I am terrible at googling. Everything I found was info about some kind of development kits for HM-10/11, also pin outs of those boards. They do have some IO pins, which can mean it's possible, but I found no tutorials nor examples on how to program those boards and use with other components.*

# Answer
> 1 votes
All bluetooth modules will need some sort of mcu to handle the requirements of the protocol stack, and it seems common that there will be at least a couple of GPIO which can be used directly if your sensor requirements are simple. At the other end of the spectrum, you will find there are also mcus with a full set of peripherals - enough to support a couple of sensors and a small display for example. Remember, the wearables market is likely bigger than the hobby electronics market.

Limitations are most likely to be in the area of ease of use (as you hint at with your question), and possibly the toolchain which you would need to use (unlikely to be arduino compatible). Also, the bluetooth stack typically takes a reasonable proportion of these wearables focused devices, so there is not a big amount of ram/flash or CPU cycles to spare even if you opt for a part which is more than 'just' a serial-to-bluetooth bridge.

---
Tags: programming, bluetooth, remote-control
---


title: Arduino and a Web Server

text:
# Question
Title: Arduino and a Web Server
I'm here because I couldn't find any answer anywhere and the problem seems pretty easy and hard in a same time.

I have a website, for exemple : My\_website.host.fr I have arduino's sensors at home, for exemple temperature sensor in my garage, servomotor in shutter, etc... with Wifi-module.

I want to, as a User, access the website, update some information on the website, for exemple : I want the shutter down, so I put it to 0 on the website, and the arduino will, for exemple each X seconds check if the value has changed, if it does then it updates itself and so lower the shutter.

So, by this, i'll never have to connect directly through an @ip to my arduino, without hosting a server at home which could be hacked or anything, the arduino update itself with the infos that are on the website,

So from my arduino I must ? I have no idea, get the source code of the web page and search for some value, or, from the web page, update a file with PHP variables and retrieve that file with my arduino then read it for the values ?

I don't know if it's clear tho and I have no idea how to manage it.

Sorry about the bad english sentence or words, not main language;

Thank for the help i'm kind of lost.

# Answer
I believe the term you want to search on is "web scraping". Assuming you are fine with people knowing the state of "things" in your home, you can simply leave the states up on your public web page. That is, you click on a button on your web page and change the text from "shutter up" to "shutter down". Mean while, your Arduino is "web scraping" the same page looking for "shutter" and acting on the next word "up" or "down".

In this blog, someone has posted his Arduino "web scrapping" code. I have not tried it, so do some research before considering this particular solution.
> 1 votes

# Answer
Another option is Blynk who offer a server, a smartphone app, and a set of libraries and example sketches for Arduino. Also an active and helpful online user community, where the developers participate.

The server does not make view-able web pages; its job is to enable the Arduino and the app to communicate with each other.

The app lets the user quickly and easily configure a custom control panel which can communicate both ways with your Arduino.

The Arduino Blynk libraries can be installed and an example program compiled and uploaded a few minutes, with support for I/O port reading and writing already built-in. Online documentation describes how to expand the example code to do more specific things. Blynk is still under active development, meaning the documentation isn't always as detailed as one might like, that bugs are being fixed and occasional new ones appear, and new features are being developed.

I use it myself and teach other people how to, and I find it a really quick and easy to use platform for interactive remote control of my Arduino-based gadgets.

For example, I am using it right now to develop a ventilation controller for room- and window-fans. It will mix the room air in winter when the heat rises to the ceiling, and ventilate or just mix the room in summer depending on the floor, ceiling, and outdoor temperatures. It will report back to the smartphone which fans are on and off; allow me to turn any of them on or off; and display a history of the temperatures and fan states.
> 1 votes

# Answer
From your comment of Jul 1st, I understand that you can program your server in PHP. Then, and to expand on my own comments, I am only recommending that, whatever Web API you design, you keep it as simple as possible. For example, for telling the Arduino whether it should keep the shutter open or closed, you could write something like this in PHP:

```
header('Content-Type: text/plain');

if (user_wants_shutter_open())
    echo "open";
else
    echo "close";

```

In particular, it makes absolutely no sense to write a PHP program that generates an HTML document. Consider that the Arduino is a very low powered platform: there is no point in having it process more than a handful of bytes when you only want to communicate a single bit of information. And you should know that there is really nothing wrong with using HTTP to transport plain text (but you should use the header `Content-Type: text/plain`). If you want to send a more complex set of data, you could use something like text/tab-separated-values, or maybe even application/json.

Concerning web scrapping, it is a solution to a specific problem, the problem being that the server returns the information in a format that is not very well suited for machine consumption. You do *not* have this problem. Obviously, you could *create* the problem by having your PHP return an HTML document, and then you could apply the solution. My point is that it is better to avoid creating the problem in the first place: just return the information in a format that is as easy to parse as possible.
> 1 votes

---
Tags: web, http
---


# Question
Title: Sketch behaves differently when motor driver is added
I have written a simple sketch that takes values via serial communication through a Python script.
Here's the code-

```
#define LEDPin 13

void setup() {
Serial.begin(9600);
pinMode(LEDPin, OUTPUT);
Serial.println("Ready");
}

void loop() {
char inByte = ' ';
if(Serial.available()){
 inByte = Serial.read();
}
if (inByte == 'L')
 digitalWrite(LEDPin, HIGH);
if (inByte == 'R')
 digitalWrite(LEDPin, HIGH);
if (inByte == 'S')
 digitalWrite(LEDPin, LOW);
}

```

Now this code runs perfectly fine with my python script. No problems at all. But When I add code for my L293D motor driver module, like this -

```
int E1 = 6;
int Left= 5;
int Right = 4;
char data = ' ';

void setup()
{
  pinMode(E1, OUTPUT);
  pinMode(Left, OUTPUT);
  pinMode(Right, OUTPUT);
  pinMode(13, OUTPUT);
  Serial.begin(9600);

  }

  void loop(){
    if (Serial.available()>0){
      data = Serial.read();
    }
    if (data =='L'){
      digitalWrite(E1, HIGH);
      digitalWrite(Left, HIGH);
      delay(2000);
      digitalWrite(Left, LOW);
      digitalWrite(E1, LOW);
      digitalWrite(13, HIGH);
    }
     if (data == 'R') {
      digitalWrite(E1, HIGH);
      digitalWrite(Right, HIGH);
      delay(2000);
      digitalWrite(Right, LOW);
      digitalWrite(E1, LOW);
      digitalWrite(13, HIGH);
    }
     if(data == 'S'){
      digitalWrite(E1,LOW);
      digitalWrite(Right, LOW);
      digitalWrite(Left, LOW);
      digitalWrite(13, LOW);
    }

     }

```

With this code added, the sketch, takes the first value it recieves, for example L, and then would go on executing the if block for that particular value **ONLY**. Even if the valueschange, still the same code block gets repeated. If I reset the Arduino, using the reset button, again the first value it recieves it starts executing the conditions of the same value and not the rest of the sketch.

P.S- I have attached the capacitor between the pins 5v and RESET.

**EDIT**

I put `ser.readline()` in my python script and found that no matter what the script only sends S to the Arduino. Even if the other two conditions are being satisfied, only S is send, and then suddenly, either L or R will be sent and then thats it. No more sending from the script.

Here's my script-

```
import numpy as np
import cv2
import serial
ser = serial.Serial('COM3',9600,writeTimeout = 0)
def f(x): return
cv2.namedWindow('Thresholding Control')

# create trackbars for color change
cv2.createTrackbar('High H','Thresholding Control',179,179, f)
cv2.createTrackbar('Low H','Thresholding Control',0,179, f)
cv2.createTrackbar('High S','Thresholding Control',255,255, f)
cv2.createTrackbar('Low S','Thresholding Control',0,255, f)
cv2.createTrackbar('High V','Thresholding Control',255,255, f)
cv2.createTrackbar('Low V','Thresholding Control',0,255, f)
cv2.createTrackbar('Guassian Blur','Thresholding Control',0,99, f)

cap = cv2.VideoCapture(0)
while(True):
  ret, image = cap.read()
  HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  # Getting trackbar values
  highH = cv2.getTrackbarPos('High H','Thresholding Control')
  lowH = cv2.getTrackbarPos('Low H','Thresholding Control')
  highS = cv2.getTrackbarPos('High S','Thresholding Control')
  lowS = cv2.getTrackbarPos('Low S','Thresholding Control')
  highV = cv2.getTrackbarPos('High V','Thresholding Control')
  lowV = cv2.getTrackbarPos('Low V','Thresholding Control')
  # Thresholding the image.
  thresh = cv2.inRange( HSV, (lowH, lowS, lowV), (highH, highS, highV))
  blurVal = cv2.getTrackbarPos('Guassian Blur','Thresholding Control')
  if(blurVal%2==0):
      blurVal=blurVal+1
  thresh_smooth = cv2.GaussianBlur(thresh, (blurVal, blurVal), 0)
  #Defining the kernel to be used for Morphological ops.
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
  # Applying Opening and Closing.
  thresh_smooth = cv2.morphologyEx(thresh_smooth,cv2.MORPH_OPEN,kernel)
  thresh_smooth = cv2.morphologyEx(thresh_smooth, cv2.MORPH_CLOSE, kernel)

  #(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(thresh_smooth)
  eleR = np.count_nonzero(thresh_smooth[0:480, 320:550])
  eleL = np.count_nonzero(thresh_smooth[0:480, 0:320])
  eleO = np.count_nonzero(thresh_smooth[0:480, 550:640])
  if (eleL>eleR and eleL>eleO and eleL!= (eleR+eleO)):
     cv2.putText(image,"Left Turn", (320,240), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     print ('L')
  elif (eleO>eleR and eleO>eleL):
     cv2.putText(image,"Right Turn", (240,320), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     print ('R')
  else:
     cv2.putText(image,"Straight", (240,320), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     print ('S')
  cv2.imshow("BGR", image)
  cv2.imshow("Thresholded", thresh_smooth)
  print ser.readline();
  if cv2.waitKey(1) & 0xFF == ord('q'):
        break
#cv2.imwrite('ImG.png', thresh_smooth)
cap.release()
cv2.destroyAllWindows()

```

# Answer
> 0 votes
Okay I figured it out. Putting what I did here, for people who are curious and for those who need help.

It was probably the Arduino, autoresetoverserialcomm, for some reason the Arduino auto-resets whenever you send a value over the serial comm to the Arduino from a computer, not from the Serial port (obviously). I knew of this earlier, and another one of my script which also sends data to the Arduino was working fine with this setup.

What I did? I just put a 10µ capacitor between the RESET and the GND pins. That didn't work initially, but I tried putting the +ve of the capacitor in the GND pin and -ve in the RESET pin and voila! The script started working just fine.

I guess this wasn't a programming issue at all, but an issue of the Arduino and the script not being able to contact each other.

I still am not sure as to what was causing the problem or whether what I have done is a permanent fix, or even a fix at all, but my problem seems to have been solved. I'll keep updating the post.

Suggestions and discussions are always welcome!

# Answer
> 1 votes
You have got quite a bit of difference between the two codes.

In your first code you declare `char inByte = ' ';` at the beginning of `void loop`. This means that each time you run through the loop it clears the value which you assign the Serial value to.

In the second code you declare `data` as a global variable outside of loop.

What that means is that you first code basically allows a one-shot reaction to a Serial value because it clears the value at the beginning of loop. Thus it only goes into an `if()` statement once.

Whereas your second code will retain the value that it received at `Serial.read()` the first time. Thus it will continue to run the matching if statement.

What you could do is after each matched `if()` statement you do `data = ' ';` or at the beginning of loop you can clear it.

Also you might be missing the updates from your python script because of the delays during motor control. Also Gerben is correct about there possibly being issues with the motor drivers affecting the Arduino.

# Answer
> 0 votes
3 things:

1: your delay statement is worrying, I'd highly recommend parallel coding in this case.

2: you don't have a "data = ' ';" statement in your loop function of the second code, but you do in the first. Is this intentional?

3: if your arduino receives Serial while executing Delay, you mustn't pour in more than the buffer.

---
Tags: arduino-uno, serial, programming, python
---


title: Passing array to library function

text:
# Question
Title: Passing array to library function
I'm trying to pass an array to a library (written in c++) but the error:

```
undefined reference to `MyLib::arrayTest(int*)'
collect2: error: ld returned 1 exit status
Error compiling.

```

Is being produced.

My Code Is As Follows:

Testing.ino:

```
MyLib test = MyLib(5,4,6);

void setup(){
    int arr[10];

    test.arrayTest(arr);

    Serial.println(arr[0]);
}

```

MyLib.h:

```
class MyLib {
    public:
        MyLib(int x, int y, int z);

        void arrayTest(int* n);

```

MyLib.cpp:

```
void arrayTest(int* n){
    n[0] = 15;
}

```

Any help is greatly appreciated :)

# Answer
This function:

```
void arrayTest(int* n){
    n[0] = 15;
}

```

is lacking the class qualifier:

```
void MyLib::arrayTest(int* n){
    n[0] = 15;
}

```
> 0 votes

---
Tags: c++, library, array
---


title: Strange behaviour with using max

text:
# Question
Title: Strange behaviour with using max
I have this really simple code. Let's say I have a variable X. Then all I want to do is create a random value R, if R \> X then I want X to become R. But for some reason, my `n_of_buttons_pressed` climbs up and then sometimes drops back to lower values. I can not wrap my head around how it could get a lower value then a previous value.

```
#define N_OF_BUTTONS 60

int n_of_buttons_pressed;

void setup() {
  Serial.begin(9600);
  Serial.println("start");
}

void loop() {

  n_of_buttons_pressed = (int) max(random(0, N_OF_BUTTONS), n_of_buttons_pressed);

  Serial.print("n_of_buttons_pressed:");
  Serial.print(n_of_buttons_pressed);
  Serial.println();

  delay(100);

}

```

# Answer
The `max()` “function” is actually a macro defined in `Arduino.h` as

```
#define max(a,b) ((a)>(b)?(a):(b))

```

This expands in your code into something like

```
buttons_pressed = random(0, N_OF_BUTTONS) > n_of_buttons_pressed) ? \
                  random(0, N_OF_BUTTONS) : n_of_buttons_pressed

```

The problem with the macro is that it evaluates at least one of its arguments twice. In this case, if the test is true, the variable `buttons_pressed` gets assigned *another* pseudo-random number.

The way around this is to store the pseudo-random number in a variable, to avoid `random()` being evaluated twice:

```
int pseudo_random = random(0, N_OF_BUTTONS);
buttons_pressed = max(pseudo_random, n_of_buttons_pressed);

```
> 6 votes

---
Tags: arduino-uno
---


title: Interfacing pc mouse (serial port DB-9)

text:
# Question
Title: Interfacing pc mouse (serial port DB-9)
So I\`ve got that mouse with serial connector. It is named serial so it should be easier to connect than even a ps2 mouse, right?

I can\`t find any instruction on it. Or should I see instruction on ps2 mouse and plug in the same wires? Btw mouse has only 4 wires connected inside, as usual PS2 mouse. I want to connect it the same way as ps2 mouse to get easy readings of rotary encoder.

UPD1: I\`ve tried to connect it like a PS2 mouse according to this schema with no success. So either a mouse is dead or it uses some kind of different connection?

# Answer
> 3 votes
A serial mouse is designed to connect to a PC's true serial port - it's an actual RS-232 device using ±5V. As such it won't connect directly to the Arduino's `RX`/`TX` pins, you'll have to go through an RS-232 transceiver chip.

It also gets its power from the `RTS` line, but I never knew what the current draw of one of those things was - be careful trying to power it from the Arduino!

Different mouse manufacturers used different protocols. The original standard used a three-byte protocol at 1,200 bps 7N1. The encoding had the following properties:

* The leading bit of the first byte of the packet was set - all future bytes had the leading bit cleared.
* The first byte had the buttons' states, and the most significant bits of the X and Y deltas;
* The X delta was encoded in the second byte;
* The Y delta was encoded in the third byte.
> http://paulbourke.net/dataformats/serialmouse/

Other manufacturers added things like extra buttons and scroll wheels that didn't fit in the packet structure. So they modified the protocol, but stuck with some features of the original:

* The data rate was (usually) still 1,200 bps, although sometimes they used 7N2 or 8N1 instead.
* The leading bit was still used to indicate start of packet;
* The X, Y (and Z) wheels still indicated deltas.
> http://www.cpcwiki.eu/index.php/Serial\_RS232\_Mouse

---
Tags: serial, rotary-encoder, mouse
---


# Question
Title: How to make "IF "Temperature exceeds" logic to work in same arduino code
I have the below code working from https://www.youtube.com/watch?v=Y30iEOxl1To \- to receive temperature & humidity as an sms when i give a missed call to a specific number (sim on the gsm shield)

The above code is like on demand sms. I also want to alter this code so it can automatically send me another sms if the temperature exceeds a threshold.

Please help.

Below is the code...

```
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "call.h"
#include <DHT.h>
#include "sms.h"

SMSGSM sms;
#define DHTPIN 7
#define DHTTYPE DHT22

CallGSM call;
boolean started=false;
char sms_text[160];

DHT dht(DHTPIN, DHTTYPE);

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");
}

void loop()
{
    float humidity, temperature;
    String smsText ="";
    if(temperature>29)
    {
        switch (call.CallStatus())
        {
            case CALL_NONE: // Nothing is happening
                break;

            case CALL_INCOM_VOICE : // Yes! Someone is calling us
                Serial.println("RECEIVING CALL");
                call.HangUp();
                delay(1000);
                humidity = dht.readHumidity();
                temperature = dht.readTemperature();
                delay(1000);
                smsText = "Temperature: "+String(temperature,1)+"C Humidity: "+String(humidity,1)+"%";
                smsText.toCharArray(sms_text,160);
                //Serial.println(smsText);
                sms.SendSMS("+91**********",sms_text);
                break;

            case CALL_COMM_LINE_BUSY:  // In this case the call would be established
                Serial.println("TALKING. Line busy.");
                break;
        }
        delay(1000);
    }
}

```

# Answer
The code below will check if the temperature goes above 29 degrees. It also check whether the temperature was below 29 previously, to prevent it from sending an SMS every second, for as long as it's above 29 degrees C.

```
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "call.h"
#include <DHT.h>
#include "sms.h"

SMSGSM sms;
#define DHTPIN 7
#define DHTTYPE DHT22

CallGSM call;
boolean started=false;
char sms_text[160];

DHT dht(DHTPIN, DHTTYPE);

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");
}

float previousTemperature = 0;
void loop()
{
    float humidity, temperature;
    humidity = dht.readHumidity();
    temperature = dht.readTemperature();
    delay(1000);

    // check if temperature has raised to above 29 degrees
    if(temperature>29 && previousTemperature<=29)
    {
        sendSMS(temperature, humidity);
    }
    previousTemperature = temperature;

    // check for incomming call
    switch (call.CallStatus())
    {
        case CALL_NONE: // Nothing is happening
            break;

        case CALL_INCOM_VOICE : // Yes! Someone is calling us
            Serial.println("RECEIVING CALL");
            call.HangUp();
            delay(1000);
            sendSMS(temperature, humidity);
            break;

        case CALL_COMM_LINE_BUSY:  // In this case the call would be established
            Serial.println("TALKING. Line busy.");
            break;
    }

    delay(1000);
}

void sendSMS(float temperature, float humidity)
{
    String smsText ="";
    smsText = "Temperature: "+String(temperature,1)+"C Humidity: "+String(humidity,1)+"%";
    smsText.toCharArray(sms_text,160);
    //Serial.println(smsText);
    sms.SendSMS("+91**********",sms_text);
}

```
> 2 votes

---
Tags: arduino-uno
---


title: How can I include examples in library?

text:
# Question
Title: How can I include examples in library?
I have written a library for Arduino, `my_library`, consisting of `my_library.h` and `my_library.cpp`, both included in `my_library` folder. Actually the library is recognized from IDE Arduino and works fine.

I want to add some examples, let's say `Example1` and `Example2`. How is that possible?

Should the examples be included in `my_library` folder?

or should be included in another folder inside `my_library` folder?

I tried several combinations but none worked. Do I miss something?

# Answer
You need to create a folder called "examples" in your library folder. Within there, each in its own folder, you place your examples.

For example:

```
MyLib/
MyLib/MyLib.h
MyLib/MyLib.cpp
MyLib/examples/
MyLib/examples/Example1/
MyLib/examples/Example1/Example1.ino
MyLib/examples/Example2/
MyLib/examples/Example2/Example2.ino

```

Be sure to name the example's folder the same as the name of the example.
> 4 votes

---
Tags: library
---


# Question
Title: Getting negative results from calculations
I'm trying to proportion potentiometer value to analog pin value. Like 1024 to 255.

```
int readVolumePot() {
    int val = analogRead(potVolumePIN);

    Serial.print("VOL");
      Serial.println((val * 255/1024));

      return (val * 255/1024);
  }

```

As potentiometer turns I got irrelevant values.

```
VOL3
VOL3
VOL3
VOL17
VOL-16
VOL-16
VOL-21
VOL-1
VOL-10
VOL-3
VOL-4
VOL11
VOL8
VOL13
VOL17
VOL15

```

In Arduino's website they say

> some constant calculations may overflow (e.g. 60 * 1000 will yield a negative result).

Notwithstanding, I cannot find an appropriate way to convert the potentiometer value to analog pin value.

# Answer
> 5 votes
`analogRead()` returns a number from `0` to `1023`, and you want to convert that to a range from `0` to `255`? One easy way would be to simply divide the reading by `4`.

On a more general note, given that the numbers will (should!) never be negative, there's a flavour of `int` called `unsigned int`. By using that:

```
unsigned int val = analogRead(...);

```

you can cover a range from `0` to `65535` instead of `int`'s `-32768` to `32767`. That will give you a little more head room - but not enough to multiply the maximum value `1023` by `255` first.

There's also another type `long`. That covers the range from -2 to 2 billion (and a bit), while `unsigned long` goes from 0 to 4 billion (and a bit) - but that uses a LOT of processing for the poor Arduino to work with.

---
Tags: c++, potentiometer
---


# Question
Title: HUGE deviation in Sharp IR sensor values if other pins are defined in void setup()
I wrote this code for a project -

```
int sensorpin = A5;
int val = 0;
double avgval = 0;
int E1 = 11;
int brake = 12;
char data = ' ';

void setup()
{
  Serial.begin(115200);
  pinMode(E1, OUTPUT);
  pinMode(brake, OUTPUT);
  pinMode(sensorpin, INPUT);
}

void loop()
{

  if (Serial.available()>0){
      data = Serial.read();
    }

  val = analogRead(sensorpin);
  avgval = average(val);
  double volt = (avgval*5)/1023;
  Serial.println (avgval);
  Serial.println(volt);
  delay(1000);

  if (data == 'G'){
    analogWrite(E1, 255);
    digitalWrite(brake, LOW);
  }

  if( volt > 1.5 && volt < 1.75 ){
    digitalWrite(brake, HIGH);
  }
}

double average(double adc){
  int n = 1;
  double avg = 0.00, sum = 0.00;
  while(n<=23){
    sum = sum + adc;
    avg = sum/25;
    n++;
  }
  return avg;
}

```

The code works fine, except for the fact that the Sharp IR sensor (GP2Y0A710K0F) outputs values which are wrong (by a HUGE distance), **ONLY** if in the `void setup()` function, the commands -

```
pinMode(E1, OUTPUT);
pinMode(brake, OUTPUT);

```

are left *uncommented*. If I comment the above two statements, the sketch works fine.

What on earth is wrong here? I can't make out anything.

# Answer
> 3 votes
Not sure why commenting out those two lines makes a difference. I think we need to see a schematic to resolve this.

However...

You do not use "pinMode" to setup an analog input!

Look at the examples on the "analogRead" page. Notice there is no setup needed for the analog pin. Just call "analogRead" like you are doing and everything should be fine.

---
Tags: arduino-uno, programming, c++, sketch, ir
---


title: Uno timer 2 set up

text:
# Question
Title: Uno timer 2 set up
I am trying to use Timer2 in an Uno in fast PWM mode. Can someone explain how to set up the TCCR2A & B registers?

Currently I have:

```
  TCCR2A |= _BV(WGM21) | _BV(WGM20);
  TCCR2B &= ~_BV(WGM22);

  TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
  TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
  TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

```

I would like to have the inverted value on TCCR2B, but I think it can be inverted using OCR2B ^= 255, correct? This is to have a varying signal on Pin11 and its inverse on Pin3, the signal is generated by varying the OCR2B value.

Thanks

# Answer
If you want to get two complementary PWM signals, you have to set *the same* value to both output compare registers. This is necessary to have the two signals in phase. You also have to configure one PWM in non-inverting mode and the other in inverting mode. For example:

```
TCCR2A = _BV(COM2A1)  // non-inverting PWM on OC2A
       | _BV(COM2B0)  // PWM on OC2B:
       | _BV(COM2B1)  //    inverting mode
       | _BV(WGM20)   // fast PWM
       | _BV(WGM21);  // ditto
TCCR2B = _BV(CS10);   // clock at F_CPU / 1
OCR2A  = 84;          // duty cycle ~ 1/3
OCR2B  = 84;          // same signal, complemented

```

Checked on the scope: when pin 3 goes high pin 11 goes low and vice-versa.
> 2 votes

---
Tags: arduino-uno, timers
---


title: square wave with serial plotter

text:
# Question
Title: square wave with serial plotter
I have this code which produces a square wave:

```
int output_state = 0;
unsigned long start;

void setup() {
  Serial.begin(1200);
  start = millis();
}

void loop() {

  if((millis() - start) >=1000){
    output_state = ! output_state;
    //output_state *= 1023;
    start = millis();
  }

    Serial.println(output_state);
}

```

but should I multiply the signal by 1023:

```
output_state *= 1023;

```

this signal is produced by the Serial Plotter:

Mind that the timing is right, just the x axis speeds up in zero values. Why is that happening, and how can be solved?

Any thoughts would be appreciated.

# Answer
It takes twice as long to print "1023" (6 bytes, including the CRLF line terminator) than to print "0" (3 bytes). Thus, in the same time, you are printing twice as many "0" than "1023".

If you want the data points to be printed at a consistent rate, you can impose the printing timing just like you did on the `output_state`. Keep in mind that you cannot print more than 20 samples per second at 1200 bps. You could also pad the strings so that they always have the same length:

```
char s[5];  // one byte for the NULL terminator
sprintf(s, "%4d", output_state);
Serial.println(s);

```

I would prefer the first solution (explicitly control the timing).
> 3 votes

---
Tags: serial
---


title: Can I close an input?

text:
# Question
Title: Can I close an input?
I wan't to build a diversity controller similar to this one.

> A diversity controller is basically a circuit which detects the strongest RSSI Signal of multiple receivers and provides the data signal of that (the strongest) receiver.

As a receiver I use boscam RX5808 receivers.

This receiver can be switchen between 8 channals through a 3 bit output interface. The CH1-3 outputs are active high 5V which got to be pulled to ground.

**Is it possible to put these receiver-outputs on an arduino digital inputs, to either put them on ground or not?**

How exactly do I implement this in software?

# Answer
When you output HIGH you connect the pin to +5V. When you output LOW you connect the pin to ground. It's called a *push-pull* interface, and looks like this:

When it's set HIGH the p-FET is turned on and the n-FET is turned off. That connects the output direct to VDD. When it's set LOW the p-FET is turned off and the n-FET is turned off. That connects the output direct to GND.

They are just like switches, as depicted to the right. Only one is closed at a time - when HIGH the upper switch is closed, when LOW the lower switch is closed.

So you just connect the output pins of the Arduino direct to the input pins of your device and write either HIGH or LOW to them to set the 5V or GND connections you need.
> 2 votes

---
Tags: digital-in
---


# Question
Title: How to connect new OV7670 FIFO to Arduino?
I bought a new OV7670 FIFO camera to connect to my Arduino UNO a few days ago.

The picture of the cam board:

I found this forum, it is nice try but it looks chaotic and confusing with about 50 pages, where you can't find where the questions and where the answers are.

I also found this library which is for non-FIFO board and could not apply to my project. I also read the OV7670\_FIFO and OV7670 and AL422 datasheets and I read I2C protocol and basics; and there are many success story on the internet but there is no schematic on them.

The problem is, I can't find any simple example for FIFO with schematic to start with. I don't know if this camera is so new or it is so hard to understand, this problem getting so serious that somebody wrote a book named "Beginning Arduino ov7670 Camera Development" about it, but I think it is a matter of an Arduino to FIFO cam schematic and example code. I ask if there is a such schematic and code for it on the web or how can I connect them?

# Answer
> 2 votes
I recently brought this book off Amazon "Beginning Arduino ov7670 Camera Development". I'm loathed to recommend it, because it has a nice 80 page introduction to the Arduino and OV7670 and the rest of the 250 pages are just double space annotated code. That said, it does appear to be a very good introduction, with example code, for a OV7670-FIFO (the title of the book is incorrect).

It might be possible to find the code on the net and then you can decide if you want to buy the book or not. Oh and I am not Robert Chin, I do not know him and I have nothing to do with the book, other than owning a rather new and once read copy of it.

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


# Question
Title: How is the integration time set for a camera?
I using the TSL1401R-LF Linescan Camera Module, which reads in a 1 X 128 line of pixels, and I'm having trouble understanding how the integration time is set for this device.

I understand from page 9 that the minimum integration time is a constent that results from a function of the clock speed, but I don't fully understand when this integration period takes place.

According to the timing waveform (Figure 1 on Page 5) the integration period appears to be set after the first 18 clock cycles. Does this mean that the integration period is set while the camera is outputting pixels?

How is that even possible? Also does this mean that in order to achive the minimum delay time I would have to take that time and divide it across those remaining 110 clock cycles (i.e. 307 ns for a total of 33.75 us)?

UPDATE:

This is how I am currently programming the camera. I'm using `delayMicrosecond()` after the HIGH and LOW clock impulses as well as at the end. I have enough delays to achieve the minimum 33.75 microsecond delay, but I'm still having sensitivity problems.

```
int delayTime = 20;

void readPixels()
{
  digitalWriteFast(SI, HIGH);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(CLK, HIGH);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(SI, LOW);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(CLK, LOW);
  delayMicroseconds(delayTime);

  for(int i = 0; i < 128; i++)
  {
    digitalWriteFast(CLK, HIGH);
    pixelsArray1[i]=analogRead(Cam1Aout);
    pixelsArray2[i]=analogRead(Cam2Aout);
    pixelsArray3[i]=analogRead(Cam3Aout);
    delayMicroseconds(delayTime);
    digitalWriteFast(CLK, LOW);
    delayMicroseconds(delayTime);
  }

  digitalWriteFast(CLK, HIGH);
  delayMicroseconds(delayTime);
  digitalWriteFast(CLK, LOW);
  delayMicroseconds(delayTime);

  delayMicroseconds(20);

}

```

# Answer
It is quite a difficult system to get your head around, as you have noticed. I'll try and break it down more logically for you...

An important thing to note is that there are two capacitors in each pixel - the *integrating* capacitor and the *sampling* capacitor. It's these two capacitors that lead to a certain amount of confusion, and it's vital to understand the role of each one.

Under normal sampling operation light falling on the photodiode of a pixel generates charge through the internal amplifier which is stored in the *integrating* capacitor. Simultaneously that stored voltage level is mirrored in the *sampling* capacitor.

When you send the pulse on SI a signal called `HOLD` is generated internally. This signal is sent to all of the pixels and tells them to disconnect their sampling capacitors. They do that through the switch S2. At the same time the integrating capacitor is emptied by S1 causing a short circuit across it. That is held there for 18 clock cycles to make sure that it's completely empty. All this time the sampled voltage is still there in the sampling capacitor.

Then as you continue clocking the pulse you sent in through the SI pin is walked down a 128 bit shift register. As it pops out of each output in turn it connects the sampling capacitor of that pixel to the output buffer so you can read the voltage. It's then flushed out and re-connected to the integrating circuit again to sample the pixel again.

So there is actually multiple things happening during your 129 clocks. Reading and integrating are both happening at the same time. But you're not reading *this* set of clock's integration, but the *last* set of clocks integration.

So you have:

* SI pulse - HOLD generated, samples frozen
* 18 clocks of clearing the integrators and reading nothing much.
* 110 clocks of reading nothing much (nothing is sampled yet) and integrating.
* 1 clock to terminate
* SI pulse - HOLD generated, samples frozen
* 10 clocks of clearing the integrators and reading the **previously integrated samples 1-18**
* 110 clocks of reading the **previously integrated samples 19-128** and integrating new ones
* 1 clock to terminate
* ... etc ...

So clocks 130 to 258 are reading the light that was sampled during clocks 19 to 128.

The upshot of all this is that your integrating period is the total time taken for the 110 clocks that occur between the end of the 18 clocks that clear the integrators and the next SI pulse that creates a new HOLD signal.
> 2 votes

---
Tags: arduino-mega, programming, sensors
---


# Question
Title: Find a time server for NTP to get the current time (EtherCard library)
There are lots of examples around how to connect with an NTP server, but I do not see how to find such an IP-address. From the examples I conclude I need to find it on for example pool.ntp.org, but I do not even see how to get IP-addresses out of there myself, let alone to let my Arduino do it. Of course I looked at the `How do I use pool.ntp.org` page, but it doesn't seem to say anything about finding IP-addresses.

**Questions**

> 1. Is it possible to let my Arduino find a working NTP server (using the EtherCard library), and if so, how?
> 2. All the examples I saw have an NTP server IP address hard coded, isn't that a bad practice and also a bad idea for a longer running project?

The code I currently find the easiest to understand is from the Arduino forum, and has an IP address hard coded.

I have an Arduino Nano ATmega328 with a ENC28j60 ethernet shield, and therefore use the `EtherCard` libray. I do know of existence of RTC devices but I would prefer NTP.

# Answer
The `EtherCard` library offers a method called `ether.dnsLookup(host)` where you ask it to look up the IP address for you.

```
etherCard.dnsLookup("pool.ntp.org");

```

...only that might fail, so it returns a `false`:

```
if (!etherCard.dnsLookup("pool.ntp.org")) {
    // Error! Do something!
    return;
} // if

```

But if it works...

```
if (!etherCard.dnsLookup("pool.ntp.org")) {
    // Error! Do something!
    return;
} // if
// At this stage, dnsLookup() worked...

// Can now connect to IP adress in etherCard.hispip

```

Now: please note that `ntp.org` would prefer you to use a more precise locale than `pool.ntp.org`. If you're going to distribute your application worldwide, then that's fine. But I always use `au.pool.ntp.org` because I'm in the Australian region. There are others that you can/should use instead.
> 2 votes

---
Tags: time
---


# Question
Title: How do I reset an ESP8266 with an FTDI and no reset button?
How do I reset an ESP8266 with an FTDI and no reset button? I assume that it has something to do with the reset pin on the ESP8266, but I cannot find a step-by-step usage of the pin online.

# Answer
Pull the reset pin up by connecting it to 3.3v with a 10k ohm resistor, then to reset the ESP you temporarily ground the pin, bringing it down to 0v/GND. I'd recommend putting in a button for that :)
> 2 votes

---
Tags: esp8266, ftdi, reset
---


# Question
Title: Shield:FAIL problem in ESP8266-01 with Arduino UNO
I have been working on a Security System project wherein I should get an email if the PIR sensor detects any human presence. I have used an Arduino UNO, ESP8266-01 WiFi module and a PIR sensor.

Power supply: Arduino is powered through the USB connection of desktop and ESP8266-01 is powered through the 3.3V pin of Arduino UNO and I have not faced any problem with that 3.3V connection of Arduino.

The connection between Arduino UNO and ESP8266-01 are as follows:

Arduino UNO-ESP8266-01

Rx - Rx

Tx - Tx

3.3V - CH\_PD & VCC

GND - GND

GPIO0 and GPIO2 left open.

After successfully uploading the 'BareMinimum' code as found in 'File\>Examples\>Basics' of Arduino IDE, the ESP8266 is able to communicate correctly i.e. connecting to a wifi network or serving as an access point via

SERIAL MONITOR.The ESP8266-01 displays '0018000902-AI03' as the firware version when I type AT+GMR in the serial monitor of Arduino IDE v1.6.8 Then I created an account on https://temboo.com/ and used the 'SendEmail' choreo as found under 'Google\>Gmail\>SendEmail'. I selected the 'Arduino' option in one tab and 'Arduino Wifi' option in another tab.I then entered the required details including the 'App specific password' and I was able to successfully run the choreo.

**Problem:**

I was able to successfully upload the code to my Arduino UNO that was generated by Temboo. But after uploading the code, when I'm opening my SERIAL MONITOR window from Arduino IDE a message "Shield:FAIL" is being displayed. I'm not able to communicate with the ESP8266 any further. But if I upload the BareMinimum code again, then ESP8266 works normally.

After connecting Rx-Tx and Tx-Rx of Arduino UNO-ESP8266-01, the serial monitor still displays 'Shield:FAIL'.

I'm a newbie and dont know much about the programming of Arduino though some basics of C are clear.Please if anyone can help me with this, I would be very grateful.

**The code is as below:**

```
#include <SPI.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <Temboo.h>
#include "TembooAccount.h" // Contains Temboo account information

WiFiClient client;

// The number of times to trigger the action if the condition is met
// We limit this so you won't use all of your Temboo calls while testing
int maxCalls = 10;

// The number of times this Choreo has been run so far in this sketch
int calls = 0;

int inputPin = A0;

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

  // For debugging, wait until the serial console is connected
  delay(4000);
  while(!Serial);

  int wifiStatus = WL_IDLE_STATUS;

  // Determine if the WiFi Shield is present
  Serial.print("\n\nShield:");
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("FAIL");

    // If there's no WiFi shield, stop here
    while(true);
  }

  Serial.println("OK");

  // Try to connect to the local WiFi network
  while(wifiStatus != WL_CONNECTED) {
    Serial.print("WiFi:");
    wifiStatus = WiFi.begin(WIFI_SSID, WPA_PASSWORD);

    if (wifiStatus == WL_CONNECTED) {
      Serial.println("OK");
    } else {
      Serial.println("FAIL");
    }
    delay(5000);
  }

  // Initialize pins
  pinMode(inputPin, INPUT);

  Serial.println("Setup complete.\n");
}

void loop() {
  int sensorValue = analogRead(inputPin);
  Serial.println("Sensor: " + String(sensorValue));

  if (sensorValue >= 2) {
    if (calls < maxCalls) {
      Serial.println("\nTriggered! Calling SendEmail Choreo...");
      runSendEmail(sensorValue);
      calls++;
    } else {
      Serial.println("\nTriggered! Skipping to save Temboo calls. Adjust      maxCalls as required.");
    }
  }
  delay(250);
}

void runSendEmail(int sensorValue) {
  TembooChoreo SendEmailChoreo(client);

  // Set Temboo account credentials
  SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT);
  SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
  SendEmailChoreo.setAppKey(TEMBOO_APP_KEY);

  // Set profile to use for execution
  SendEmailChoreo.setProfile("JigarFaria");
  // Identify the Choreo to run
  SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");

  // Run the Choreo
  unsigned int returnCode = SendEmailChoreo.run();

  // Read and print the error message
  while (SendEmailChoreo.available()) {
    char c = SendEmailChoreo.read();
    Serial.print(c);
  }
Serial.println();
  SendEmailChoreo.close();
}

```

# Answer
> 1 votes
1. You seem to have the ESP connected via serial, but aren't sending it anything.
2. The Rx of the ESP needs to be connected to the Tx of the Arduino (via a logic level shifter) and the Tx of the ESP needs to be connected to the Rx of the Arduino.
3. Do you know with a proper email sending library you could use any email server, not some service that you may have to pay for?
4. The ESP8366 is a much more capable device than the Arduino (IMO). I suspect that you could directly connect your sensor to it, and program it (in Arduino C/C++) through the Arduino IDE and it would be much less hassle.
5. I think the problem with your code is that you haven't initialised the Wifi object, the first time you call it is to ask the status. However I don't think you need this code because its not talking to the ESP8266 and you should be sending the data via the serial connection.

# Answer
> 0 votes
Both @CodeGorilla and @Majenko make valid points.

The shield esp will talk with the uno through Serial and your esp8266 has the AT firmware on it. The BareMinimum reads input from serial and prints what the esp is sending . the code you posted has code meant for the Uno and code meant for the shield esp.

That wont work.

Your should use the arduino library for esp8266 (https://github.com/esp8266/Arduino,) make a suitable code for it , connect your sensor to the shield and forget the uno.

---
Tags: arduino-uno, sensors, wifi, esp8266
---


# Question
Title: Is there an easy way to turn integer values to pixels?
I'm working with a black & white camera and it gives me integer values to represent the amount of light hitting the sensor. Very bright is 1023 and totally dark is 0. The values are printed through serial and everything works fine but now I want to recreate the image based on the values.

Does anyone know if there is a simple way of doing this? I'm assuming the process would consist of looking up the value and giving a specific colored pixel in return, but I have no idea how to do this.

# Answer
Simplest thing may be to write down your image in plain Portable Gray Map format. This is a very simple (and inefficient) ASCII format consisting of a signature (the string "P2"), followed by the width and height of the image, followed by the maximum possible gray level (1023 in your case), followed by the pixel values. It's a free form format, meaning you can mix spaces and newlines at your convenience.

Here is an example image: two rows of pixels, five columns, and brightness increasing left to right and top to bottom:

```
P2
5 2
1023
  0 111 222 333 444
555 666 777 888 999

```

Then, any image conversion software should be able to convert that into the format of your choice (PNG, JPEG, whatever...).
> 1 votes

---
Tags: programming, sensors
---


title: Main Idea of Gyro

text:
# Question
Title: Main Idea of Gyro
I have a L3G4200D (GY-50 model) gyroscope. I have been trying to learn how a gyro sensor works. The circuit diagram is attached. I want to ask some questions;

a) According to the datasheet of L3G4200D, x\_lsb and x\_msb (28h and 29h), y\_lsb ,y\_msb (2Ah and 2Bh), z\_lsb , z\_msb (2Ch and 2Dh) as shown in the picture 3. But according to code that in the picture first, Arduino requests bytes from 168 address of gyro (in the picture, the mark number is 1). But, 0x28 (hex) stands for b00101000 . What's wrong with it ?

b) Output of gyro is outputs degrees/second, is it correct?

c) In the picture 2, I did not move it, as it shown its results change, how can the angle change? It must be zero when it does not move.

d) In the picture 1, what I should calculate: highbyte\*256+lowbyte ?

e) What does Fs=250,500,2000 dps mean? I know that Dps stands for Degree Per Second. But what would change by FS range, I mean if I pick either 500 or 2000 ?

# Answer
> 3 votes
> According to the datasheet of L3G4200D, x\_lsb and x\_msb (28h and 29h), y\_lsb ,y\_msb (2Ah and 2Bh), z\_lsb , z\_msb (2Ch and 2Dh) as shown in the picture 3. But according to code that in the picture first, arduino requests biytes from 168 adress of gyro(in the pciture ,mark number is 1). But , 0x28 (hex) stands for b00101000 . what's wrong with it ?

168 is, in hex, 0xA8. That's 0x28 with the MSB set. Why? Well, the datasheet says:

> In order to read multiple bytes, it is necessary to assert the most significant bit of the subaddress field. In other words, SUB(7) must be equal to 1, while SUB(6-0) represents the address of the first register to be read.

So address 0xA8 is the same as address 0x28 plus the instruction "I want to read multiple bytes".

> Output of gyro is outputs degrees/second ,is it correct ?

Kind of. The number is actually a representation of the fraction of FS. See below.

> in the picture 1,what I should calculate hightbyte\*256+lowbyte ?

That is turning two 8-bit values into a single 16-bit value. It's easier to represent it using bit shifts:

```
(bighbyte << 8) | lowbyte

```

That is, the high byte is shifted left 8 bits and the low byte is then ORed over the lower (zero) 8 bits.

> What does Fs=250,500,2000 dps mean ? I know that Dps stands for Degree Per Second .But what would change by FS range ,I mean if I pick either 500 or 2000 ?

That is the "Full Scale" value. It defines what the raw numbers from the gyro actually mean. The gyro returns -32768 to +32767. -32768 is -FS, +32767 is +FS. So if the FS is set to 500 degrees per second then:

* -32768 is -500 degrees per second
* +32767 is +500 degrees per second

The simple formula is (using floating point maths):

DPS = Reading / 32768.0 * FS

The format is more commonly known as *Q15* where a 16-bit value is split into 3 parts - a sign bit (bit 15), an integer part (there isn't one in this case), and 15 bits (14-0) of fraction. So the number actually represents, in Q15 format, between -1 and +1 in 65536 steps of 1/65536. That number is then multiplied by the full scale value, just like you would a percentage, to get the real DPS value.

# Answer
> 2 votes
According to the datasheet, FS seems to be Measurement Range. Also, I think you will find useful information in the following discussions: Understanding the sensitivity of an L3G4200D gyroscope and in How do I get gyro sensor data (L3G4200D) into degrees/sec? Due to the fact that the gyro is 16 bit, the range of values would be 2^16, what makes 65536. So, the values on your screen are between -65536/2 and +65536/2, that's why max. values that you see are around 32000.
There is always very tiny motion that the sensor can detect due to vibrations and etc. So, you should not expect the output of gyro to be a set of constants. Ideally, you should combine the data, lets say for 1 second, and find RMS value(average it) to get the result, don't look just for few instances/samples.
Also I should note that if there is ultrasound in the gyro environment, it might also cause wrong results. When outer frequencies coincide with the natural frequency of the gyro system, it leads to resonance and distorted data. This paper has explanation of this phenomenon among with other impacts to the gyroscope.

---
Tags: gyroscope
---


title: ESP8266 reset problem

text:
# Question
Title: ESP8266 reset problem
I am trying some AT commands with ESP8266 but it resets continously when it stop resetting, i can't get any response from ESP8266.

Example :

```
AT

OK
AT+CWMODE=1

OK
AT+CIPMODE=0

OK
AT+CIPMUX=1

OK
AT+CWJAP="..",".."

 ets Jan  8 2013,rst cause:4, boot mode:(3,1)

wdt reset
load 0x40100000, len 612, room 16
tail 4
chksum 0x12
load 0x3ffe8000, len 788, room 4
tail 0
chksum 0x50
load 0x3ffe8314, len 264, room 8
tail 0
chksum 0x4a
csum 0x4a

2nd boot version : 1.1
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd
ready

 ets Jan  8 2013,rst cause:4, boot mode:(3,1)

wdt reset
load 0x40100000, len 612, room 16
tail 4
chksum 0x12
load 0x3ffe8000, len 788, room 4
tail 0
chksum 0x50
load 0x3ffe8314, len 264, room 8
tail 0
chksum 0x4a
csum 0x4a

2nd boot version : 1.1
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd
ready

```

I have upgraded my firmware and I tried GPIO0 and GPIO2 are active but it still does not response fine. It worked yesterday but today it is working like crazy..

# Answer
Arduino can not provide enough current for ESP8266 operations. Use external 3.3V power supply, I would recommend 500ma. Also don't forget to put a small cap between vcc and ground. 100uf should do it.
> 1 votes

# Answer
I had the same problem. My esp8266 is powered by FTDI USB to serial module. Since this module can provide a limited amount of current to 3.3V. I use to get frequent reset.

I resolved it by adding a 1000ufd electrolyte capacitor near the power connection of the esp8266 module. And issue resolved like never been there.

I am sure that can also be done by a smaller capacitor. Try with 470 or 220ufd.

enjoy

Rauf
> 0 votes

---
Tags: esp8266
---


# Question
Title: Arduino Mega Hall sensor interrupt for a speedometer
I am having difficulty setting up an interrupt to count how many times the magnet passes so that I can count something like every 100 ms the actual speed.

I have a little code put together from the Internet:

```
const byte LED_pin =13;
const unsigned long wheel_circumference = 431800UL * 2UL * 31416UL; // = 94,248,000
unsigned long Speed = 0;
unsigned long PrevSpeed = 0;
volatile byte hall_rising = 0; // interrupt flag
volatile unsigned long irqMicros;
unsigned long startMicros;
unsigned long elapsedMicros;
unsigned long ledFlashStartMillis;
const unsigned long ledFlashWaitMillis = 10;
unsigned long displayStartMillis;
const unsigned long displayWaitMillis = 100;

void wheel_IRQ()
{
  irqMicros = micros();
  hall_rising = 1;
}

void setup()
{
  pinMode( 2, INPUT_PULLUP ); // pin # is tied to the interrupt
  pinMode( LED_pin, OUTPUT );
  Serial.begin( 9600 ); // can this be faster? faster would be better
  delay( 1000 );

  attachInterrupt( 0, wheel_IRQ, RISING ); // pin 2 looks for LOW to HIGH change
}

void loop()
{
  if ( hall_rising == 1 )
  {
    elapsedMicros = irqMicros - startMicros;
    startMicros = irqMicros;
    hall_rising = 2;
  }
  else if  ( hall_rising == 2 )
  {
    if ( millis() - ledFlashStartMillis >= ledFlashWaitMillis )
    {
      hall_rising = 0;
    }
  }

  // print speed 1000/Wait (10) times per second
  if ( millis() - displayStartMillis >= displayWaitMillis )
  {
    Speed = wheel_circumference * 0.0009 / elapsedMicros;

    displayStartMillis += displayWaitMillis;
    if ( Speed != PrevSpeed )
    {
      Serial.print(Speed); // this shows mm/sec with no remainder
      Serial.println(" kmh");
    }
    PrevSpeed = Speed;
  }
}

```

But when I use this code in U8glib to display the value on a GLCD . Values are totally wrong. Can someone help me?

# Answer
> 1 votes
You either need to change your code to count the number of revolutions in the interrupt. Then divide that value in your main loop by the elapsed time to get the angular velocity. This may or may not work, as the number of revolutions may be small or even zero when you do the calculations. Thus contributing to errors.

Or, change your code to record the elapsed time between rising edges in the interrupt. Then find the inverse of this value. This may be better as you could even miss an event in your main loop and still calculate the speed. Careful not to take the inverse of zero.

To calculate speed you need to find the rotational speed of the wheel, and, consequently, how fast you are bicycling. Use this equation:  ...where omega is the revolutions per time as calculated by the 1st method above or reported by the interrupt routine in the 2nd method above. Do not forget that the interrupt routine is probably using milliseconds and not seconds.

Also, do not forget to clear out the last value reported by the interrupt. No matter which of the above 2 approaches you take.

Also consider special cases. For instance, when you stop bicycling the interrupt will never fire. In your main loop you may have a second counter which, when exceeded, indicates that your speed is zero.

---
Tags: arduino-mega, sensors, interrupt
---


# Question
Title: Why SD.exists() only looks for inside media/realroot on Intel's Galileo?
I'm following a tutorial which says SD.exists() only look for files inside media/realroot on Intel's Galileo board. I just confirmed this using SSH to create e remove files during a loop which was looking for some specific named file. Where's information about this? I searched for cpp files inside SD library and found nothing.

# Answer
> 1 votes
The Intel Galileo runs Linux. Most Linux distributions (auto) mounts media under specific directories like "/media". So this is likely not so much a feature of the Arduino paradigm but of the Linux paradigm. If you really want to change this you will probably have to research how Linux (specifically how the Intel Galileo version of Linux) auto mounts media.

This is a stack exchange question about auto-mounting using a Linux distribution called Ubuntu. I am not sure how close the Intel Galileo Linux is to Ubuntu. But it's a starting point.

---
Tags: sd-card, arduino-galileo
---


# Question
Title: How to transmit serial data from laptop USB out to Teensy?
I want to send serial data from my laptop to a Teensy LC chip through the laptop's USB port. I am not sure how to do this. From reading I have found two possibilities, which both seem to have problems:

1. Get a USB to serial adapter cable, connect the USB to the laptop, the serial to a MAX232 chip, the MAX232 chip to the UART serial on the Teensy. The ambiguity in this option lies in the fact that the MAX232 chip requires a minimum 4.5V input, and the specs on the Teensy LC say it has 3.3V and *one* 5V digital output (would this one output be compatible with a MAX232?). Also, it has only 3.3V input, so it sounds like 5V coming from the MAX232 chip would be too much (I guess I could incorporate a chip like https://www.adafruit.com/product/735 ?). Now if I were to go this route with a Teensy 3.1, which says its input pins are 5V tolerant, its voltage output is also only 3.3V (and there is no mention of any 5V output). I guess the answer here would be to incorporate a chip like https://www.adafruit.com/products/1787 ?
2. The second possibility I looked into would be a USB-to-TTL adapter cable to go straight to the Teensy LC, but I read somewhere that the serial UART with Arduino is different in some way and I wasn't sure if the serial communication coming through the USB-to-TTL cable would be compatible with the Teensy. I was looking at one of these cables at Sparkfun, and I think I would connect the TxD from the cable to the RX on the Teensy, the RxD from the cable to the TX on the Teensy, and the GND cable to a ground on the Teensy.

Could someone point me in the right direction regarding sending serial data through a laptop's USB out to the Teensy?

# Answer
Your second option is the easiest.

> a usb to ttl adapter cable to go straight to the Teensy LC, but I read somewhere that the serial UART with Arduino is different in some way

Without seeing what you read, perhaps they were just talking about the fact that the Arduino is not "true" RS-232, it's only at TTL (or 3.3V) levels.

> and wasn't sure if the serial communication coming through the usb to ttl cable would be compatible with the Teensy.

It should be compatible, especially since you note that the Teeny is 5V-tolerant.

> I was looking at one of these cables at sparkfun, and I think I would connect the TXD from the cable to the RX on the Teensy, the RXD from the cable to the TX on the Teensy, and the GND cable to a ground on the Teensy.

That's it in a nutshell!
> 1 votes

---
Tags: teensy
---


# Question
Title: Detect if a chair is occupied using Arduino with some sensors
I want to detect if a seat is occupied by a person. This is the answer that I found on Stackoverflow.

However, how accurate is the output of 4 suggested sensors? Will the computing of all these 4 sensor values into one boolean recognize a case when, for instance, a box of 40kg is placed on a seat and some person is just slightly "shaking" that seat with a hand? In those cases Arduino should recognize that a seat is not occupied by a person. Will it work with only 4 sensors or is there any better and more accurate solution (maybe some existing library)? I guess that CapSense-Library is not applicable in my case.

# Answer
> 1 votes
As has been mentioned in the comments there's many ways of sensing, each with its own pros and cons.

Sensing the presence of something is actually twofold. First you need to know if there is something there, and secondly you need to try and identify *what* it is that's there and if it fits your criteria.

With passive sensors of the type used by Arduinos it all comes down to a matter of *probability*.

If you have force sensors, you know when *something* is there, but you can't work out *what* is there, only that it weighs a certain amount.

Using capacitative sensors you can get an idea about what the *something* is made of - how much does it affect the capacitance, etc.

Using ultrasound and/or infra-red beams etc you can get an idea of the kind of size of the object that is in the chair.

So combining them all together you can work out the likelihood that it is a human if:

* It weighs enough to be a human
* It has a suitable dielectric response to be a human
* It is big enough to be a human

Of course, there's always the chance that it's just a big dog, or a sack of potatoes.

So it's all a case of improving that probability by adding more sensors of different types, until you are *almost* certain that it is a human. You will never be 100% certain, of course.

# Answer
> 0 votes
I've also been trying to figure out a suitable idea for the same question.

* Image processing would be so accurate in this but there are some problems with this approach, since there is a lot of code work and in case we want to implement this system in restaurant people might not agree.
* Pressure sensors would work better for the idea but there are some issues with this approach also. Just as mentioned in the question if there is some kind of a weight in the chair there will be an issue. also there are several chairs for a table in case of a restaurant so if we need to know whether the table is empty or not we will have to check whether all the seats are empty or not. In this case we need to pair the chair to the table using some method. we can also take this approach assuming that the chairs of the table will never change i.e. the same set of chairs remain for the same table.

The best approach for this particular scenario would be the sensors being in the table, or having a set of sensors such as a pressure sensor, thermal sensor, IR and verifying the seat is occupied.

---
Tags: arduino-uno
---