# Question
Title: Is it possible to press a button from Arduino and my computer will get a key event?
My idea seems easy:

I connect a button with arduino, then write some code and upload it to arduino. Then I open the notepad(or any other editor) on my computer. When I press the button, there will be a character "A" displayed in the notepad.

I have tried with my Arduino uno, and use `Serial.write/print` function to send an `A` to serial port `9600`, but it seems the character `A` only shows in the serial monitor GUI.

My question is:

1. Is "Arduino uno" is OK to implement this?
2. If not, what other board should I use?
3. Is `Serial.write/print` the correct function?
4. Or shall I use the `Keyboard.???` function?
5. Do I have to write an application which runs on the computer and listens the serial port, and emit a real key event? (that's sad)

# Answer
> 9 votes
The Uno is not the best board for this. You may be able to get somewhere with the Virtual USB project but there are a couple of boards that are better suited for this.

Those are the Arduino Leonardo, Micro, and Due. In those, you can use the Keyboard Library just like you are using the Serial library now. This page has an example very similar to your project:

```
void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(2, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  //if the button is pressed
  if(digitalRead(2)==LOW){
    //Send the message
    Keyboard.print("Hello!");
  }
}

```

# Answer
> 4 votes
There is a micro designed more specifically for keyboard emulation, I haven't done any experimenting with it (yet), but it's very popular in the flight simulator world where these micro's are rigged up with buttons and switches and rotary encoders to simulate a cockpit. These inputs are converted to keyboard inputs (as far as I can see).

There are some general projects here: https://www.pjrc.com/teensy/projects.html

Some more keyboard specific stuff: https://www.pjrc.com/teensy/usb\_keyboard.html

More info on the teensy in the arduino environment: https://www.pjrc.com/teensy/teensyduino.html

More specifically about what you're looking for, this could be quite useful: https://www.pjrc.com/teensy/td\_keyboard.html

I'm not steering you away from Arduino, it's just something else to look into

# Answer
> 1 votes
Your example describes collecting text - does that meet your goal or do you need to generate any kind of key-event? If you don't need to generate system events, any terminal emulator (not just the Arduino IDE) should be able listen to that same port and to log whatever it receives to a file.

# Answer
> 0 votes
Check this video, Arduino UNO as a USB keyboard (HID device) \[Anything Arduino\] (ep 6), as I think this is what you are looking for.

From the youtube video you can get links to the library site and schematics.

You do need to build a small interface to connect your Arduino to a PC. I got it for Uno and Micro, but other Arduinos with latest firmware would be OK.

# Answer
> -1 votes
I think you also need to install `processing`.

See this link

It enables you to program the computer-side of the application.

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


title: Arduino not working / not uploading

text:
# Question
Title: Arduino not working / not uploading
Could anybody please help me with my problem? My Arduino doesn't work correctly. I was between a project, and suddenly it started acting weird. First, it started taking about 4 minutes to compile and a minute to upload, I do not know why!

Second, now it doesn't accept any code at all. I will paste the error message below.

Also, could anything be damaged as I inserted the USB cable of the Arduino to my power bank, rated 5V 2A, for about 30 seconds as power source and then again inserted it to the computer itself.

Please help me. I have already tried searching on various forums, reinstalling the software and driver on my PC, pressing the reset button... No help so far.

> ERROR MESSAGE: Arduino: 1.6.7 (Windows 10), Board: "Arduino/Genuino Uno"
>
> avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2009 Joerg Wunsch
>
> System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

```
Using Port                    : COM6
Using Programmer              : arduino
Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x49
Error opening serial port 'COM6'. (Port busy)
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x49

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

# Answer
Connecting to the 5v/2A power supply would cause no trouble at all. Taking 4 minutes to compile is strange but unlikely to be related to the Arduino board. "programmer is not responding" errors are communication errors.

* Did the program compile without errors?
* Are any LEDs lit or blinking on your board?
* Is the correct board selected in the Tools | Boards menu?
* Is the correct port selected in the Tools | Ports menu?
* Is the correct programmer selected in the Tools | Programmer menu?
* Try another USB cable.
* Try pressing/releasing the board's reset button right after you click the upload button.
> 1 votes

# Answer
I am getting the same exact errors. Tried different boards, cables, upgrade to 1.6.7, etc. Maybe will go back to pre1.6 and try. Will also try via tinyisp when I get a chance. FYI - having no issues with studio 6/tinyusb/avrdude combination, just on arduino. Wonder if it is a USB driver or arduino version of avrdude problem?
> 0 votes

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


title: Low Cost Motorized Valve

text:
# Question
Title: Low Cost Motorized Valve
I'm looking for a low cost motorized water valve. I've done a number of searches and have found nothing compelling. Has anyone here used a motorized water valve with Arduino? What would you recommend?

A fail-open solenoid might also work but I'd like to try my hand at a motorized valve.

The valves I found start at US$50. I'm looking for something cheaper. The purpose is tinkering and I'd like to make an "if water detected - then close valve" sketch. Ir's simple, just more expensive than I expected.

# Answer
> 1 votes
You can get sprinkler valves, that use solenoids, for under $20 that fit on plastic PVC pipe and are designed for water, such as these at SprinklerWarehouse. They typically use pipe sizes of about 1 inch.

---
Tags: arduino-uno, programming, motor
---


# Question
Title: Sending 5 Led pixel values to arduino , is this a good way?
I wanted to install a 5 LED strip underneath my PC's front panel. I want to send color over PC so it can change when i open different apps, with temperature or etc!

So all I think the best way to do this is to just use Arduino to set the LED Values!

But I have had some troubles creating a good communication protocol for this, I've been just simply sending 45 digits (15 3 digit numbers) to my Arduino with serial. here's code: Arduino :

```
#include "Adafruit_NeoPixel.h"
#include "WS2812_Definitions.h"

#define PIN 4
#define LED_COUNT 5

struct pixel {
  int R = 0;
  int B = 0;
  int G = 0;
};

Adafruit_NeoPixel leds = Adafruit_NeoPixel(LED_COUNT, PIN, NEO_GRB + NEO_KHZ800);

char count = 1;
int pixelNumber = 0;
struct pixel tempPixel;
//struct pixel Pixels[LED_COUNT];

void setup()
{
  Serial.begin(9600);
  Serial.println("Init");
  leds.begin();  // Call this to start up the LED strip.
  clearLEDs();   // This function, defined below, turns all LEDs off...
  leds.show();   // ...but the LEDs don't actually update until you call this.
}

void loop() {
  if(Serial.available() > 0) {
    if(count == 1) {
      tempPixel.R = PC_Receive();
    } else if (count == 2) {
      tempPixel.G = PC_Receive();
    } else if (count == 3) {
      tempPixel.B = PC_Receive();
      count = 0;

      setPixelColor(pixelNumber, tempPixel);
      Serial.println(pixelNumber);
      leds.show();
//      Pixels[pixelNumber] = tempPixel;
      if(++pixelNumber >= LED_COUNT) {
        pixelNumber = 0;
      }
    }
    count++;
  }

//  if(pixelNumber == 0) {
//    for(int i = 0; i < LED_COUNT; i++ ) {
//       setPixelColor(i, Pixels[i]);
//    }
//
//    leds.show();
//  }
}

void setPixelColor(int a, struct pixel P)
{
  leds.setPixelColor(a, P.R, P.G, P.B);
}

char PC_Receive() {
  int result = 0;

  while(Serial.available() == 0);
  result += ((int)Serial.read() - '0') * 100;

  while(Serial.available() == 0);
  result += ((int)Serial.read() - '0') * 10;

  while(Serial.available() == 0);
  result += ((int)Serial.read() - '0');

  Serial.println(result);
  return result;
}

void setColourRgb(unsigned int red, unsigned int green, unsigned int blue) {
  for(int i = 0; i < LED_COUNT; i++) {
    leds.setPixelColor(i, red, green, blue);
  }
  leds.show();
 }

```

And here's PC's dirty code in python:

```
import serial
import time
import random

class Pixel:

    def __init__(self, R, G, B):
        self.R = R
        self.G = G
        self.B = B

def clearAll():
    for i in range(0,5):
        ser.write("000000000")

def sendPixel(pixels):
    for i in range(0,5):
        ser.write(str(pixels[i].R).zfill(3))
        ser.write(str(pixels[i].B).zfill(3))
        ser.write(str(pixels[i].G).zfill(3))

ser = serial.Serial('/dev/ttyACM2', 9600)

little = [0,0,0,0,0]

for i in range(0,5):
    little[i] = Pixel(0,255,50)
sendPixel(little)

time.sleep(0.5)
clearAll()

```

the problem is it isn't stable, i think i should just use an \n at end or send back OK or something to confirm it, but that would make it slow if i did it for each value! (and checking only once after all 5 leds are send would mean sending more values until i receive the ok and clearing and sending them again!)

Can you recommend me a better way?

Thanks!

EDIT: Just wanted to say! it's almost done! It does change color when i open chrome, and i think at 115200 baud rate it's fast enough to not notice a delay (although at 9600 i felt like it's slower then my (xxx/xxx/xxx....) protocol but it's better and works at 115200

i will add some basic functions to my python side and add a rainbow effect I will also add GPU temperature and etc... it's not going to be really hard on linux but windows, im not sure :D

# Answer
I would recommend a similar solution as DaveX with a small modofication.

If you bitmask your LEDS, and leave room for a possible additional 3, you can mask any combination of them in the space of 00-FF. then you could send to the arduino a single string of 0xFFFFFFFF FF(LED bitmask),FF(Red value), FF(Green Value), FF(Blue Value).

so LED 1 {`00000001` =`01`} all red {`FF0000`} would be `0x01FF0000`

LED 2 and 4 {`00001010` =`0A`} all green {`00FF00`} would be `0x0A00FF00`

LED 5 and 1 {`00010001` =`11`} all blue {`0000FF`} would be `0x110000FF`

ALL LEDS off would be `0xFF000000`

All LEDS onn full white would be `0xFFFFFFFF`
> 1 votes

# Answer
I'd recommend adding digits to a digit register, setting the an R,B,G register with R,B,G and setting values of led a-e to the RBG registers when you get an a-e, ignoring whitespace, and clearing the register otherwise. So:

```
 ser.write("xRBGabcde\n")  # clear all the LEDs
 ser.write("x127RBb")       # make led b half-purple, relying on prior state
 ser.write("x255Gc")        # make led c greenish-white

```
> 0 votes

---
Tags: communication
---


# Question
Title: Can't make Wee serial WiFi work with Arduino Uno
I'm trying to plug a Wee serial WiFi module on my Arduino Uno, through an XBee shield .

I'm simply trying to make work the example from the library.

All I get is

```
setup begin
FW Version:
to station err
Join AP failure
setup end

```

The code i'm using :

```
#include <SoftwareSerial.h>
#include <doxygen.h>
#include <ESP8266.h>

SoftwareSerial mySerial(3, 2); /* RX:D3, TX:D2 */
ESP8266 wifi(mySerial);

#define SSID "yuflowoffice"
#define PASSWORD "cashless"

void setup(void) {
  Serial.begin(9600);
  mySerial.begin(115200);
  Serial.print("setup begin\r\n");

  Serial.print("FW Version: ");
  Serial.println(wifi.getVersion().c_str());

  if (wifi.setOprToStation()) {
    Serial.print("to station ok\r\n");
  } else {
    Serial.print("to station err\r\n");
  }
  delay(1500);

  if (wifi.joinAP(SSID, PASSWORD)) {
    Serial.print("Join AP success\r\n");
    Serial.print("IP: ");
    Serial.println(wifi.getLocalIP().c_str());
  } else {
    Serial.print("Join AP failure\r\n");
  }

  Serial.print("setup end\r\n");
}

void loop(void) {
}

```

What can I do?

# Answer
A look at https://github.com/itead/ITEADLIB\_Arduino\_WeeESP8266/blob/master/ESP8266.h shows that when you pass a `SoftwareSerial` object to the ESP8266 constructor, a default baud rate of 9600 is also passed to it. Also, the library source file shows that, in the constructor, the `begin()` method of the `SoftwareSerial` object you passed (myserial) is called with 9600 baud. Thus, this line in your code:

```
    mySerial.begin(115200);

```

is a duplicate, albeit one with a different baud rate, thus rendering the constructor's call of `mySerial.begin()` useless, since your call comes after the constructor's. If you are certain that 115200 is the right baud rate for the hardware, then you should get rid of the line above and instead pass the baud rate to the constructor like this:

```
    ESP8266 wifi(mySerial, 115200);

```

Replace 115200 with any baud rate you discover to be the right one for the AT commands. You also need to uncomment the line in ESP8266.h in your library:

```
    //#define ESP8266_USE_SOFTWARE_SERIAL

```

and then save, since you are using SoftwareSerial to communicate with the module.
> 0 votes

---
Tags: xbee
---


title: >> << and -> Syntax in arduino

text:
# Question
Title: >> << and -> Syntax in arduino
I was trying to follow this tutorial and came across `>>`. What exactly does this do?

# Answer
`>>` is right shift a value by a certain number of bits. `<<` is left shift a value by a certain number of bits. `->` is accessing a member of a class or struct that is referenced by a pointer.

# Right Shift and Left Shift

If you have a binary number `0b00010000` and right shift it two bits you get `0b00000100`. The C notation for that is `val >> 2`. The same for left shift - `val << 2` would result in `0b01000000`.

# Pointers and members

Normally when you access a member of a class or struct you use `.`, such as `Serial.println()`. However it is possible to make a *pointer* to a class instance, and when you do you need to access the members with `->` instead of `.` \- such as `mySerial->println()`. This arrow notation serves as syntactic sugar: `mySerial->println()` is interpreted as `(*mySerial).println()`. The parentheses are necessary because the dereferencing operator `*` has a lower order of precedence compared to the dot `.` operator.
> 4 votes

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


# Question
Title: Plug/socket between thermocouple wires and the amplifier
I am building a temperature monitoring system that has 24 thermocouples. Managing all the wires is a hassle, and I'd like to connect all 48 wires to a few plug and socket connectors. Maybe 6 of these lead wire harnesses from eBay (see below).

The point of this would be to allow me to quickly disconnect all the thermocouples from their amplifiers when I need reposition the arduino, and then reconnect them afterwards without tracking each individual cable.

I don't know if this will have a negative impact on the function of the thermocouples. Is it ok to have a 'joint' (i.e., the socket) in the thermocouple cables, or do they need to remain intact from the end all the way to the amplifier?

Alternatively, would having a few inches of regular copper wire inserted between the thermocouple wires and the amplifier be ok? That is, having two copper wires attached to the amplifier, joining 8 of these wires together in a socket, and attaching the plug to the actual thermocouple (alumel/chromel) wires? The thermocouple wires are several feet long.

# Answer
> 4 votes
I do not know the accuracy that you will require in your temperature measurements.

Your idea of using copper wire and connector sockets is reasonably ok as long as you are aware of the following :

Where you make a connection from thermocouple wire to copper, that creates another thermocouple in itself. This isn't a great problem since the temperature of the "undesired" thermocouple is likely to be at room temperature (constant?)

No matter what you do, you always end up with undesired thermocouples (example when you connect your thermocouple directly to your circuit board copper, darn it.)

Thermocouple Selection and use is a page you can go to for more information. Especially the *Cold junction compensation* (CJC) section.

EDIT added : You should twist your extention leads together to reduce electrical noise from the environment. Twist each pair, do not twist the bundle all together.

---
Tags: temperature-sensor
---


# Question
Title: constant current or constant voltage power supply to use with RGB shield with high power LEDs
So, I got an arduino uno and a RGB shield from velleman for christmas because I mentioned I might want to do a project with high power LEDs - a neat surprise, but now I have to use it (: The shield can do PWM on an external power supply and this can be wired through to the high power LEDs itself. I aim to power about 10W of LED light in total, with different colors in order to make good use of the board. Can I go for Option 1? If not, what would you advise?

**Option 1**

As high power LEDs need a constant current, I am inclined to connect a constant current supply as the external supply of the board (assuming all channels' LEDs need the same current).

*Update*: I talked to an electrician and a constant current supply typically works on a PWM basis; putting this in series with the PWM of the shield is not smart.

**Option 2**

Alternatively I could connect a standard constant voltage supply and make sure that the current is within limits:

* One option would be to use *resistors*; but, with 12V DC and 350mA I would need like 33 Ohm resistance dissipating 4 Watts of power, which is inefficient.
* Alternatively there are DC voltage to constant current LED drivers which will take care of the constant current for me; I could put those at the exits of the shield for the LEDs. They supposedly have a better conversion efficiency than the resistors, but I do have any knowledge about their performance with PWM as input; but I have serious doubts they would like that type of input. Furthermore, these drivers also often have PWM capabilities. This kind of module would render the shield functionality largely useless.

# Answer
> 1 votes
Your thinking and reasoning is pretty much spot on.

The board you have is basically a trio of high current low side switches. So yes, you need *something* to limit the current, and as you have noted resistors are not going to be very efficient.

The best way to drive high power LEDs is, as you know, with constant current. However, you need a constant current source *per LED channel*, not one single one for the whole board. That means three individual constant current sources, each providing the right current for the LEDs you are driving on that channel.

It's possible to roll your own cheap constant current sources using LM317T linear voltage regulators (http://diyaudioprojects.com/Technical/Current-Regulator/). It's a cheap option, though pretty much as in-efficient as using resistors, just easier to deal with the heat sinking. Note that on the LM317T the tab is live, so you must use three separate heat sinks for each channel.

My personal preference though is to use PWM capable constant current sinks. My favourite is the CAT4101 which can deal with up to 1A per channel (more if you parallel them) and uses a single resistor to set the current. It has a PWM input that you can drive direct from an Arduino's PWM pin. Of course, as you note, that then makes your nice shield redundant.

---
Tags: arduino-uno, power, led
---


# Question
Title: Generate 2 PWM signals Vc and Vh from Arduino Uno
I want to generate two PWM signals VC and VH to give input to the gas sensor with the duty cycle mentioned below. I also want to take the reading from the same sensor at the same time using Arduino Uno.

\[

I am confused how to proceed with the code in Arduino Uno.

# Answer
> 1 votes
You can use the `millis()` function to see how much time has passed and use this to create your waveform while still being able to perform other tasks. You will check in which part of the wave you are in each iteration of `loop()` and adjust your outputs accordingly.

E.g:

```
long vhtime;
uint8_t vhpin = 9;   // the VH output pin
uint8_t vcpin = 10;  // the VC output pin

long period = 250;   // the period of your pwm signal in ms
long vhduty = 14;    // amount of ms vh should be high
long vcdelay = 2;    // amount of ms we wait for vc to go high after vh has gone high
long vcduty = 5;     // amount of ms vc should be high

long curtime;        // this will hold our current position in one period of the waveform

void setup() {
  pinMode(vhpin, OUT);
  pinMode(vcpin, OUT);
  digitalWrite(vcpin, LOW);
  digitalWrite(vhpin, HIGH);
  vhtime = millis();
}

void loop() {
  curtime = millis() - vhtime;
  if (curtime > vhduty)        // we are in the last 236ms of the wave, vh should be low
    digitalWrite(vhpin, LOW);
  else                         // we are in the first 14ms of the wave, vh should be high
    digitalWrite(vhpin, HIGH);
  if (curtime > vcdelay && curtime < vcduty + vcdelay) // vc should be high during this time
    digitalWrite(vcpin, HIGH);
  else
    digitalWrite(vcpin, LOW);
  if (curtime > period) {
    // we should start a new period
    digitalWrite(vhpin, HIGH);
    vhtime = millis();
  }
  // do your other calculations here
}

```

---
Tags: arduino-uno, programming, pwm
---


title: Arduino TMP36 sensor

text:
# Question
Title: Arduino TMP36 sensor
I am following the tutorial Tiny WiFi Temperature Sensor with Arduino. everthing works fine, but I have a little problem.

When the serial monitor is opened the sensor is reading fine like 23.20, 20.25 etc., but when I closed the serial monitor window I got wrong values, for example, 289.34, 289.90.

What does the serial monitor do?

I am stuck with this problem for last two days. Please give me a hand.

---

* The baud rate is as you can see 115200 and i have changed it various time but it doesn't do anything.
* I haven't test commenting out the Serial.println() lines
* The values i can see at my server (see the function send\_request).
* The problem is when i am testing the program opening the serial monitor windows everything works fine for example: 29.20, 30.12, 28.12 but when i close the windows i start getting wrong values for exmaple: 289.45, 289.89 , etc... .

## Here is my code.

```
#include <Adafruit_CC3000.h>
#include <Adafruit_CC3000_Server.h>
#include <ccspi.h>

/*
   Tiny WiFi temperature sensor with Arduino, the TMP36 sensor & the CC3000 chip
   Writtent by Marco Schwartz for Open Home Automation
*/

// Include required libraries

#include <SPI.h>
#include <string.h>
#include "utility/debug.h"
#include<stdlib.h>

// Define CC3000 chip pins
#define ADAFRUIT_CC3000_IRQ   2
#define ADAFRUIT_CC3000_VBAT  A3
#define ADAFRUIT_CC3000_CS    8

// WiFi network (change with your settings !)
#define WLAN_SSID       "ssid"        // cannot be longer than 32 characters!
#define WLAN_PASS       "password"
#define WLAN_SECURITY   WLAN_SEC_WPA2 // This can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2

// Create CC3000 instance
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                         SPI_CLOCK_DIV2);

// Local server IP, port, and repository (change with your settings !)
uint32_t ip = cc3000.IP2U32(10,0,129,108);
int port = 8080;
String repository = "/tiny-wifi-temperature/";

void setup(void)
{

  Serial.begin(115200);
  Serial.println("Start setup");

  // Initialise the CC3000 module
  if (!cc3000.begin())
  {
    Serial.println("Impossible to start");
    while (1);
  }

  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  listSSIDResults();
  connectNetwork();
  displayConnectionDetails();
  /*
  while(!displayConnectionDetails())
  {
    connectNetwork();
  }*/

}

void connectNetwork(void)
{
  Serial.println(F("Trying to connect wifi ")); Serial.println(WLAN_SSID) ;

  /*
  uint32_t ipAddress = cc3000.IP2U32(10, 0, 130, 200);
  uint32_t netMask = cc3000.IP2U32(255, 255, 0, 0);
  uint32_t defaultGateway = cc3000.IP2U32(10, 0, 1, 1);
  uint32_t dns = cc3000.IP2U32(10, 0, 1, 1);
  if (!cc3000.setStaticIPAddress(ipAddress, netMask, defaultGateway, dns)) {
    Serial.println(F("Failed to set static IP!"));
    while(1);
  }
  */

  /*
  if (!cc3000.setDHCP()) {
    Serial.println(F("Failed to set DHCP!"));
    while(1);
  }*/

  // Connect to  WiFi network
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }
  Serial.println("Connected to WiFi network!");

  // Check DHCP
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100);
  }

}

void loop(void)
{

  // Measure the temperature
  int sensorValue = analogRead(A4);
  float milliVoltsValue = sensorValue * 5000. / 1024.;
  float temperature = (milliVoltsValue - 500.) / 10.;

  // Print the result
  Serial.println(temperature);

  // Transform to string
  char temp[5];
  dtostrf(temperature, 5, 2, temp);

  // Send request
  String request = "GET " + repository + "sensor.php?temp=" + String(temp) + " HTTP/1.0";
  send_request(request);

  // Update every second
  delay(1000);
}

// Function to send a TCP request and get the result as a string
void send_request (String request) {

  // Connect
  Serial.println("Starting connection to server...");
  Adafruit_CC3000_Client client = cc3000.connectTCP(ip, port);

  // Send request
  if (client.connected()) {
    client.println(request);
    client.println(F(""));
    Serial.println("Connected & Data sent");
  }
  else {
    Serial.println(F("Connection failed"));
  }

  while (client.connected()) {
    while (client.available()) {

      // Read answer
      char c = client.read();
    }
  }
  Serial.println("Closing connection");
  Serial.println("");
  client.close();
}

void listSSIDResults(void)
{
  uint32_t index ;
  uint8_t valid , rssi, sec ;
  char ssidname[33];

  if (!cc3000.startSSIDscan(&index)) {
    Serial.println(F("SSID scan failed!"));
    return;
  }

  Serial.print(F("Networks found: ")); Serial.println(index);
  Serial.println(F("================================================"));

  while (index) {
    index--;

    valid = cc3000.getNextSSID(&rssi, &sec, ssidname);

    Serial.print(F("SSID Name    : ")); Serial.print(ssidname);
    Serial.println();
    Serial.print(F("RSSI         : "));
    Serial.println(rssi);
    Serial.print(F("Security Mode: "));
    Serial.println(sec);
    Serial.println();
  }
  Serial.println(F("================================================"));

  cc3000.stopSSIDscan();
}

bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if (!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

```

# Answer
> 2 votes
The serial monitor gives you a way to "talk" relatively directly with the Arduino – in this case it give you a way to easily confirm that the basic circuit is working and that you are getting sensible temperatures. That's a foundation on which you can build.

It is unlikely – I think – that the serial monitor is causing the problem. But before you believe me, there is one thing you should consider. The serial monitor runs relatively slowly, so outputting the temperature via the serial monitor introduces a delay in your code. That could explain the difference.

So your next step is to trace your bad value. So, first more questions:

* What baud rate are you running the serial monitor at? Does changing the baud rate affect the result? That would point to a timing related issue.
* Is there any code that writes to the serial monitor (e.g., a call to Serial.println())? If there is what happens when you comment it out?
* Where are you seeing the two values (the correct and incorrect values)? I assume that both are at the web server, but I want to confirm this.
* Can you explain more clearly the process to demonstrate the problem? In the tutorial that you link to I don't think that the code pathway is the same to see the value on the serial monitor as it is on the server, so I'm wondering if an error was made as you changed the code.

---
Tags: temperature-sensor, arduino-mini
---


# Question
Title: Arduino compiler uploading last saved version of sketch, not current
Is this an issue or a defined behavior? I am using Arduino IDE 1.6.6

Sometimes I made changes in code, and immediately upload them to the Arduino board. And many times issues already fixed are persisting, leaving me that feeling of "the uploaded code has not the changes I have just made". Then I save my sketch, compile and upload again and the issue vanishes. As long as the issue get someway fixed, I tend to forgot about it.

As software engineer, most of the times I assume the code I am compiling and uploading / publishing to any platform is always the latest, not the latest saved. I believe this is not the behavior of the Arduino IDE. It uploads the last saved version of code, not the last modified.

**In summary: I believe the Arduino IDE uploads to the board the last saved version of the sketch, not the current one being modified.** Can anyone confirm this?

Thanks in advance.

# Answer
> 2 votes
I haven't tried it but it would be an easy experiment to make on some throw-away code.

However, do note that saving before compiling or uploading is *optional* in the Arduino IDE. That may very well be the key to what you observed. I keep mine enabled, i.e., to save before any compile or upload. The option is in the Preferences dialog accessed from the menus, not in the manually-edited `preferences.txt` file. That might be the key to what you observed.

Update: In that case, including the pre-defined macros `__DATE__` and `__TIME__` (of the pre-processor run) and `__TIMESTAMP__` (of the file's last modification) in a "Hello" string can help debug this.

These pages list the standard, and common predefined macros implemented in gcc's pre-processor. Note also that most version control systems offer similar macros that get replaced at checkout to embed a revision number and other version-control information.

---
Tags: sketch, uploading, ide
---


title: Push-Pull tone code

text:
# Question
Title: Push-Pull tone code
I wanted to use a piezo sounder to sound an alarm in an application. Testing indicated that `tone()` was not very loud.

I could use some external circuitry to swing the pins ±5V but as I have plenty of spare pins, it seemed feasible to use 2 pins driven in anti-phase to increase the power by 4.

I looked at the source `Tone.cpp` but the code is somewhat intimidating. Before I start to modify it I was wondering if anyone else has already done something like this.

# Answer
> 3 votes
Yes, Tim Eckel has already published a library "toneAC" on the Arduino website at http://playground.arduino.cc/Code/ToneAC

All of the syntax is there too.

---
Tags: sound, piezo
---


# Question
Title: How does the PID controller actually work?
Preferably PID functions on an Arduino uno or any other examples. I have been researching but many of the the websites really do not explain it.

**P.S is there an algorithm for a PID? Thanks**

# Answer
I, also, didn't get the idea behind PID from just reading Wikipedia. After some videos/tutorials, I believe the best way to explain it is:

**What is PID**

PID is an algorithm. It involves three factors which can be adjusted to tune a signal.

It is often used in servo's (and things like thermostates, basic signal controllers)

**Imagine this**

The servo will be used in the practical examples.

A servo has: \- a current position (signal) \- the position you want the servo to be in (goal signal) \- a speed (PID output signal)

The PID output signal/algorithm makes sure that the servo reaches it's goal.

**In short:**

PID is an algorithm that can adjust a signal towards an setpoint. Or correct it for that matter. It regulates how much you have to adjust the signal, without getting serious overshoot, or oscillation around the setpoint.

**Detail:**

P stands for proportional.

Which means that the further the servo is from it's setpoint, the more speed we want to/can give it. So that we're faster towards the set point. This also means that we slow down as we near the set point. Of course you can multiply each of these rules with a factor, to achieve a better balance.

I stands for integrating.

It basically comes down to the fact that it constantly keeps adding to the signal, depending on how long there is a difference between the current point and set point. This is so that if P is still a little slow, it adds some speed over time.

D stands for differentiating

It's less commonly used. (Wikipedia) The D factor reacts on the speed of the change in value. Or speed of change in setpoint (Dutch wikipedia is not 100%, comment if neccesary :) )

These factors / the algorithm provides a smooth regulation of various systems, hence that's why it is so adjustable.

It can be used for balancing quadcopters or making your house comfortably warm (without sudden changes, or too slow changes)

**Why?**

How would you balance a quadcopter? If it shifts to one side, you don't want to fully reverse the throttle. It'll make it wobble, since you get a lot of overshoot. Controlling things can be hard, PID is an known working algorithm for those cases. But you have to adjust the factors right to adjust it to your specific system. (They all react differently, or have to react differently).
> 3 votes

# Answer
How a PID controller works depends on the particular implementation.

There is a algorithm/library for PID on the Arduino: http://playground.arduino.cc/Code/PIDLibrary and an excellent explanation of the all of functions within it at http://brettbeauregard.com/blog/2011/04/improving-the-beginners-pid-introduction/

Over on stackoverflow and electronics, there are some good questions and explanations that might help:
> 3 votes

---
Tags: arduino-uno, programming, electronics, pid
---


# Question
Title: Arduino raise the error "variable-sized object 'my2dArray' may not be initialized" while trying to change the elements of 2d array
I' m trying to change 1 to 0 in two-dimensional (5x5 matrix) for specific servo positions.First, i tried to program forward movement of my robot. My code is like this:

```
#include <Servo.h>
#define x 5
#define y 5

Servo myServo;
Servo myServo2;

int pos = 0;

int counter1;
int counter2;
int integer;

void setup() {
  Serial.begin(9600);
  myServo.attach(9);
  myServo2.attach(10);
}

void loop() {

  int my2dArray[x][y]= {
  {1,1,1,1,1},
  {1,1,1,1,1},
  {1,1,0,1,1},
  {1,1,1,1,1},
  {1,1,1,1,1},
  };

  int robot = my2dArray[2][2];

   if (counter1 > 0){
     for (integer = 0;  integer <2; integer +=1){
      int my2dArray[2 + integer][2] = robot * my2dArray[2 + integer][2];

     }
 }
}

  int moveForward(){
  for (pos = 0; pos <= 360; pos += 1) {
    myServo.write(pos);
    myServo2.write(pos);
    delay(15);
    if (pos == 360){
    counter1 += 1;
    }
    return counter1;
}
}

int moveBackward(){
  for (pos = 360; pos <=0; pos -= 1) {
    myServo.write(pos);
    myServo2.write(pos);
    delay(15);
    if (pos == 360){
    counter2 += 1;
    }
    return counter2;
}
}

```

But i can' t change the \[3\]\[2\] and \[4\]\[2\] elements from 1 to 0. I get an error:

```
 error: variable-sized object 'my2dArray' may not be initialized

```

Can you help me? Thanks.

# Answer
The error is in this line:

```
  int my2dArray[2 + integer][2] = robot * my2dArray[2 + integer][2];

```

The presence of the word `int` there tells it to try and make a new variable. You don't want to do that, since it's an error. Lose the `int` and it might work.
> 1 votes

---
Tags: arduino-uno
---


title: Trouble when avoiding delays

text:
# Question
Title: Trouble when avoiding delays
I am new to Arduino and I am learning how to avoid using delay.

I have written some code to move my servo by 20° using delays, but can only move the servo once with my current code. In `setup()`, I assign the servo 150. The next value the servo receives is 15, which it performs. It does not iterate through the following values though. I have been using this guide, BlinkWithoutDelay, with no luck.

Here is my code:

```
#include <Servo.h>
Servo myservo;
unsigned long previousMillis = 0;
const long interval = 1000;

    void setup() {
       myservo.attach(9);
       myservo.write(150);
    }

   void loop() {
       unsigned long currentMillis = millis();

       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(15);
       }
       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(35);
       }
       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(65);
   }

```

# Answer
> 7 votes
You are resetting the timer on the first phase \[`write(15)`\] instead of *after* the last phase \[after `write(65)`\]! The `previousMillis = currentMillis` should be only after the last phase, before the loop repeats. Not only that, but the time at which each phase executes needs to be different. Currently every `if()` statement is set to run after *interval* has elapsed. If, for example, you wanted *interval* to be the delay between each phase, you could use *interval\*1* on the first phase, *interval\*2* on the second, and *interval\*3* on the third. For example:

```
   if (currentMillis - previousMillis <= interval * 1) {
        // Runs from interval*0 to interval*1;
        myservo.write(15);
   }
   else if (currentMillis - previousMillis <= interval * 2) {
        // Runs from interval*1 to interval*2;
        myservo.write(35);
   }
   else if (currentMillis - previousMillis <= interval * 3) {
        // Runs from interval*2 to interval*3;
        myservo.write(65);
   }
   else {
        // Runs once after interval*3;
        // *or* runs on first iteration when previousMillis is zero;
        previousMillis = currentMillis;// Reset the loop;
   }

```

To put the above logic in English:

1. `write(15)` while time is between 0 and 1 intervals;
2. `write(35)` while time is between 1 and 2 intervals;
3. `write(65)` while time is between 2 and 3 intervals;
4. reset the loop once time reaches 3+ intervals.

Note the use of `else if` instead of simply `if` on consecutive statements. This prevents more than one code block from running on the same iteration of the `loop()`.

Edit: I highly recommend having a small delay (like 1ms) somewhere in the `loop()`, such as at the end. It would be a bad idea to constantly run the `write()` function when the value is the same as on the last call.

On the other hand, if your starting value is indeed 150 and the loop should start only after interval\*1, you may want to iterate from interval\*2 through interval\*4:

```
   if (currentMillis - previousMillis <= interval * 1) {
        // Runs from interval*0 to interval*1;
        // Do nothing; servo is set to either 150 or 65 during this time;
   }
   else if (currentMillis - previousMillis <= interval * 2) {
        // Runs from interval*1 to interval*2;
        myservo.write(15);
   }
   else if (currentMillis - previousMillis <= interval * 3) {
        // Runs from interval*2 to interval*3;
        myservo.write(35);
   }
   else if (currentMillis - previousMillis <= interval * 4) {
        // Runs from interval*3 to interval*4;
        myservo.write(65);
   }
   else {
        // Runs once after interval*4;
        // *or* runs on first iteration when previousMillis is zero;
        previousMillis = currentMillis;// Reset the loop;
   }

```

# Answer
> 1 votes
If you want to change the servo every second, try to use a conditional expression in the timing structure. If you want to use more parallel structure with multiple intervals use different counters (example see: here).

Here is an example of the every second version:

```
#include <Servo.h>
Servo myservo;
unsigned long previousMillis = 0;
const long interval = 1000;
int angle = 150;

void setup() {
   myservo.attach(9);
   myservo.write(angle);
}

void loop() {
    unsigned long currentMillis = millis();

    if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;

        switch (angle) {
            case 150:
            case 65:
              angle = 15;
              myservo.write(angle);
              break;
            case 15:
              angle = 35;
              myservo.write(angle);
              break;
            case 35:
              angle = 65;
              myservo.write(angle);
              break;
        }
    }
}

```

**EDIT:** Add variable assignment `angle` in conditional expression.

---
Tags: arduino-uno
---


# Question
Title: Control the ethernet shield with Chrome and Safari
I am trying to communicate with ethernet shield. When I enter the IP in Chrome the job is done (simply an LED turns off and on with IP/$1 and IP/$2) but with Safari it is not. Any idea what the difference is?

# Answer
> 1 votes
I had the same problem. I forgot to complete the `client.println` with a newline (`\n`).

---
Tags: ethernet
---


title: Menu system without libraries

text:
# Question
Title: Menu system without libraries
I was wondering if there are a way to do a menu system for arduino UNO using buttons and without libraries.

I tried to do it by myself but the code was too long and heavy.

I don't want full code, just a pseudo-code idea and how does it works.

I know there are libraries that to this, but I want to practise C++.

Thanks!

# Answer
> 1 votes
Interactive menus are certainly not a "simple" task. That is why people use libraries.

Whatever you try you will end up with complex code - either long winded with lots of duplication, or somewhat cryptic with lots of pointers, arrays, and structures. Not an easy task for a beginner in C++.

How I would set about it would involve the following things:

1. A structure that defines a menu entry, including pointers to one of: sub-menu array, numeric variable (including max/min limits), option array, function to execute.
2. Arrays of the above structure to define each menu
3. Array or linked list of "breadcrumbs" through the menu to track where you are and go back up properly
4. Functions to display and navigate the menu arrays on an LCD.

All of that uses fairly advanced C coding techniques, especially when it comes to managing all the pointers, etc.

The "simpler", though more long winded way, would be to write individual functions for each menu and sub-menu, but that would make your program incredibly long and prone to have errors when duplicating (copy/paste) code.

---
Tags: arduino-uno, c++
---


# Question
Title: How can I use arduino board for AC mains?
I want to use LDR to control a light bulb (12W) which runs on AC supply using Arduino.

Is it possible to do this?

If yes, how?

# Answer
> 2 votes
Try the PowerSwitch Tail II.

This is suitable if you are living in the USA (120VAC power). You will find 240VAC versions as a kit on that web page as well.

# Answer
> 1 votes
The quick and dirty answer is that you need something that will safely handle the mains voltage that you can control with the Arduino (which is running at 5 (or 3.3) volts). There are two issues you need to consider:

1. Safety – keeping the mains voltage separate from the Arduino and the other low voltage components so that nobody gets hurt.
2. Capability of components – avoiding damage to the Arduino and related components due to the mains voltage.

A common way of achieving the second goal is with either a relay or a solid-state component like a triac.

The first goal is often accomplished by using an optocoupler – a device that isolates the low-voltage circuitry from the higher mains voltage by means of an LED and a photo transistor in a common housing.

The circuitry around the relay and optocoupler aren't all that complicated but it isn't trivial either. You might look on e-bay – a search for "arduino relay" will find you lots of modules that will do the job for you.

# Answer
> 0 votes
You can use a relay shield like these: Relay Boards - eBay

Be sure to check the amp draw of the relays. Sometimes you need a transistor, but I don't think you should for these shields. Just be careful working with mains voltage.

# Answer
> 0 votes
If you want to switch it on/off, there is a simple solution using a relay and an optocupler (safer option) or transistor. Here is a schematic:

but if you want to control intensity of light, then you have to use triac control, which you have explained here: AC Phase Control.

---
Tags: photoresistor
---


# Question
Title: Which Bluetooth Module can I use with Arduino Micro/Mini?
I need to use a Bluetooth module with an Arduino Micro/Mini.

Please suggest which one would be the best, HC 05/06, or any other?

# Answer
I have had good results using the Bluefruit LE UART Friend module from Adafruit with a 32u4 micro Arduino type module, there are only a few pins to connect up to get things going (do remember to follow the instructions to pull the CTS pin to ground).

As per the previous answer it really does depend on what you want to do with it - but this module does Low Energy, can be configured as a "Beacon" and there is a companion App for Android/iOS.
> 2 votes

# Answer
Do you require slaves or masters?

Both modules are actually the same, it is just the firmware that is different, and in turn that changes how they use the pins. HC05 can be both Master and Slave, and has a full set of AT commands, whereas HC06 can only be a slave, and has a more limited set of AT commands at its disposal.

Otherwise, for low power projects, then BLE modules, such as HC-10 or HC-11 might be worth considering.

Really, it all depends on what you want to do with them, what is the overall project? You could get away with one HC-05 and one HC-06, but it is really task dependant. It is probably worth you having a read up of some articles on the web, and looking at some example projects to see other people's configurations. This will hopefully help you to see what you actually require for your project.

FWIW, I looked into this a few months back and wrote a short blog, BlueMoon, on it, which contains some example projects and links to video tutorials - this may help give you an insight...
> 1 votes

---
Tags: bluetooth, arduino-micro, arduino-mini
---


# Question
Title: CC3000 - Send GET request to an app, or sub-domain, on Heroku
I am working with Arduino UNO + AdaFruit CC3000 Wi-Fi shield. I ran it with a lot of websites and webpages, but for now I am going to get sub-domain from Heroku, and it has no IP address. The sub-domain is `myapp.herokuapp.com`.

So, how can I send a GET request to such an application like that?

Here's the code :

```
 // Library headers section
 #include <Adafruit_CC3000.h>
 #include <ccspi.h>
 #include <SPI.h>
 #include <string.h>
 #include "utility/debug.h"

 // Constants area
 #define ADAFRUIT_CC3000_IRQ  3 // must be an interrupt pin (2 or 3)
 #define ADAFRUIT_CC3000_VBAT  5 // any pin
 #define ADAFRUIT_CC3000_CS  10 // any pin

 //use hardware SPI for remaining pins
 // Uno: SCK=13, MISO=12, MOSI=11
 Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,      ADAFRUIT_CC3000_IRQ,
                                          ADAFRUIT_CC3000_VBAT,      SPI_CLOCK_DIVIDER);
 #define WLAN_SSID  "Ibtikar.AP2"
 #define WLAN_PASS  "#ibtik@r#"
 // set security type
 // WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA, WLAN_SEC_WPA2
 #define WLAN_SECURITY  WLAN_SEC_WPA2
 #define IDLE_TIMEOUT_MS  3000 // amount of time to wait with no date      recieved
                               // before rejecting/closing the collection
 #define WEBSITE  "myapp.herokuapp.com"
 uint32_t ip;
 void setup() {
   // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
/* Initialise the module */
    Serial.println(F("\nInitializing..."));
    delay(100);
    if (!cc3000.begin())
    {
      Serial.println(F("Couldn't begin()! Check your wiring?"));
      while(1);
    }
    Serial.print(F("\nAttempting to connect to "));           Serial.println(WLAN_SSID);
     if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
       Serial.println(F("Failed!"));
       while(1);
     }
    Serial.println(F("Connected!"));
    /* Wait for DHCP to complete */
    Serial.println(F("Request DHCP"));
    while (!cc3000.checkDHCP())
    {
       delay(100); // ToDo: Insert a DHCP timeout!
    }

   /* Display the IP address DNS, Gateway, etc. */
   while (! displayConnectionDetails()) {
     delay(1000);
   }

    ip = 0;
   // Try looking up the website's IP address
   Serial.print(WEBSITE); Serial.print(F(" -> "));
   while (ip == 0) {
     if (! cc3000.getHostByName(WEBSITE, &ip)) {
       Serial.println(F("Couldn't resolve!"));
     }
     delay(500);
   }
   cc3000.printIPdotsRev(ip);

   // Optional: Do a ping test on the website
   Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip);      Serial.print("...");
   int replies = cc3000.ping(ip, 5);
   Serial.print(replies); Serial.println(F(" replies"));
 }

 void loop() {
    /* Try connecting to the website.
      Note: HTTP/1.1 protocol is used to keep the server from closing the           connection before all data is read.
   */
    Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
   if (www.connected()) {
     www.fastrprint(F("GET "));
     www.fastrprint(F(" HTTP/1.1\r\n"));
     www.fastrprint(F("Host: myapp.herokuapp.com"));
     //www.fastrprint(WEBSITE);
     www.fastrprint(F("\r\n"));
     www.println();
   } else {
     Serial.println(F("Connection failed"));
     return;
   }
   Serial.println(F("-------------------------------------"));
   unsigned long lastRead = millis();
   while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
     while (www.available()) {
       char c = www.read();
       Serial.print(c);
       lastRead = millis();
     }
   }
   www.close();
   Serial.println(F("-------------------------------------"));

   /* You need to make sure to clean up after yourself or the CC3000 can           freak out */
   /* the next time your try to connect ... */
        Serial.println(F("\n\nDisconnecting"));
   cc3000.disconnect();
   delay(1000);
 }

 /**************************************************************************/
 /*!
     @brief  Begins an SSID scan and prints out all the visible networks
 */
 /**************************************************************************/

 void listSSIDResults(void)
 {
   uint32_t index;
   uint8_t valid, rssi, sec;
   char ssidname[33];

   if (!cc3000.startSSIDscan(&index)) {
          Serial.println(F("SSID scan failed!"));
          return;
   }

   Serial.print(F("Networks found: ")); Serial.println(index);
   Serial.println(F("================================================"));

   while (index) {
     index--;

     valid = cc3000.getNextSSID(&rssi, &sec, ssidname);

     Serial.print(F("SSID Name    : ")); Serial.print(ssidname);
     Serial.println();
     Serial.print(F("RSSI         : "));
     Serial.println(rssi);
     Serial.print(F("Security Mode: "));
     Serial.println(sec);
     Serial.println();
   }
   Serial.println(F("================================================"));

   cc3000.stopSSIDscan();
 }

      /**************************************************************************/
 /*!
     @brief  Tries to read the IP address and other connection details
 */
 /**************************************************************************/
 bool displayConnectionDetails(void)
 {
   uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

   if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv,      &dnsserv))
   {
     Serial.println(F("Unable to retrieve the IP Address!\r\n"));
     return false;
   }
   else
   {
     Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
     Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
     Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
     Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
     Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
     Serial.println();
     return true;
   }
 }

```

# Answer
> 1 votes
You don't need to know the IP address; the `getHostByName()` method takes care of resolving the website to an address. It seems 2 lines are missing from your code:

```
    #define WEBPAGE "/index.html"  // change the string to the webpage you want

```

at the top, and:

```
   www.fastrprint(WEBPAGE);

```

right after `www.fastrprint(F("GET "));`. Without these lines, you've failed to indicate the specific webpage you wish to GET. Anyways, when i tried to open `myapp.herokuapp.com`, I got a message saying that its offline for maintenance, so you'll most likely fail to retrieve anything.

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


title: Explanation for micros function

text:
# Question
Title: Explanation for micros function
I was trying to understand the working of micros() function internally and I had a look at the function in Arduino.h

This is the code:

```
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;

    cli();
    m = timer0_overflow_count;
 #if defined(TCNT0)
    t = TCNT0;
 #elif defined(TCNT0L)
    t = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#ifdef TIFR0
        if ((TIFR0 & _BV(TOV0)) && (t & 255))
        m++;
#else
        if ((TIFR & _BV(TOV0)) && (t & 255))
        m++;
#endif

    SREG = oldSREG;

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

```

Can someone please explain me what this line is doing :

```
  if ((TIFR0 & _BV(TOV0)) && (t & 255))
   m++;

```

# Answer
If the timer 0 has overflowed (`TIFR0 & _BV(TOV0)`) and there is at least a count of 1 in the timer count register (`t & 255`) then increment the local copy of the overflow count.

That overflow count is used later on to add an upper 8 bits to what is basically an 8 bit counter to turn it into a 16 bit one (`(m << 8) + t`).
> 5 votes

# Answer
Since at the start of this function interrupts have been disabled by the `cli()` function it is possible that the timer `TCNT0` has overflowed yet this *event* has not been processed and included in the value of `timer0_overflow_count` that has been read into `m`. Therefore the line that you are asking about is checking for this condition and incrementing the local copy `m` if necessary before using it to calculate the number of microseconds since startup.
> 4 votes

---
Tags: programming
---


# Question
Title: What sensor would detect the black stripe on an analog electricity meter?
I have an analog electricity meter (AEM) and I would like to track my usage of electricity. I've attempted to use the EE-SY310 photo sensor, but that's not sensitive enough it seems. I suspect the black stripe on the dial is too thin to be picked up. The other concern on using any photo sensor is its dependance on light (obviously) hence no reading would be picked up during the night.

Other: I've also found that AEMs work by using magnetic fields to move the dial. The magnetic field detector I used did not show much fluctuation when turning appliances on/off. The dial was pegged at the max. Therefore, I'm not so confident that a sensor to measure magnetic fields would work here, but I'm open to suggestions.

So, would anyone know what sensor would be good to detect the black stripe on AEMs? Preferably to also work without light.

I know there are off-the-shelve products that do this already, but where's the fun in that?

# Answer
> 3 votes
A low cost option is the TCRT5000 infrared proximity sensor. While this is designed to sense objects coming close to the sensor, by reflection of the infrared light emitted by the integrated IR LED, it also does very well in detecting black versus reflective surfaces placed near it.

There are two parts to making this work:

1. Reduce the drive current for the IR LED of the TCRT5000 to the bare minimum which causes detection of the non-black portion of the electricity meter disc. While the datasheet specifies a forward current of up to 60 mA absolute maximum, a quick experiment I conducted shows appreciable detected signal at as little as 4 mA forward current, for a metallic target surface 2 mm away. Tune the forward current to work with the actual distance and reflectivity of your particular electricity meter wheel.
2. Place a black piece of card or plastic in front of the detector part of the TCRT5000, with a thin slit cut in it to align with the black strip on the electricity meter wheel. I am getting good results using a 1.2 mm plastic sheet with a 0.3 x 1.5 mm slit cut in it.
Note that the two hemispherical plastic parts of the TCRT5000 look more or less the same, so you will have to identify which one is the detector, and ensure that you do not obstruct the emitter by mistake. The side with the angled vertical edges (right side of image below) is the emitter and must not be obstructed.

With this arrangement, the collector current through detector will dip significantly each time the black stripe passes in front of the detector.

# Answer
> 1 votes
On ALL mechanical watt-hour meters (those with a rotating disk), the disk will have either one or two holes, typically in the mid section or outer edge of the aluminum disk. Utilities used these holes to pass a light beam through (from the top of the meter to the bottom of the meter) to detect and count disk rotations. A simple light source and photo-transistor can be used to detect the presence of the disk hole to sense disk rotations.

---
Tags: sensors, electricity
---


title: Control Brushless ESC From Arduino

text:
# Question
Title: Control Brushless ESC From Arduino
I am trying to build a quadcopter using an arduino. I Bought 4 30A ESC's from Ebay the link is http://www.ebay.co.uk/itm/4pcs-Brushless-speed-controller-ESC-MultiCopter-KK-Quad-rotor-X-copter-30A-S-/310950293677?pt=LH\_DefaultDomain\_3&hash=item486614f0ad and a A2212 2200KV motor, im also using a sparkfun arduino uno. I have connected the white (data) servo wire of the ESC to pin 9 of my arduino and the black (ground) servo wire of the ESC to gnd of the arduino. When i connect the battery to the esc i get the 3 beeps because of my 3 cell battery regardless of what code is on the arduino even if the arduino is not present. the code that is on the arduino is.

```
#include <Servo.h>

Servo motor;

void setup()
{
  Serial.begin(9600);
  motor.attach(0);
}
void loop()
{
  motor.write(100);
}

```

I'm not sure what is wrong. Can someone please help me.

# Answer
> 2 votes
I had a similar problem. I solved it by using an oscilloscope to measure the arming sequence of an out-of-the-box RC remote controller and receiver.

The arming sequence through the controller-receiver was like this:

1. Connect ESC to battery (arduino is connected to signal and ground prior to this)
2. Wait for 3 beeps
3. Set the throttle to the lowest possible
4. Wait for another beep

I then adjusted my arduino code to output the same(similar) sequence.

Here is the code:

```
#include <Servo.h>
#define POT A0

Servo m1;

void setup() {
  m1.attach(6);
  Serial.begin(9600);
  delay(50);
  Serial.println("Serial ready:");
  arm(m1);
}

void loop() {
  int potValue = analogRead(POT);
  int s = map(potValue,60,930,1200,1700); //Map the pot values to motor values

  m1.write(s);
  Serial.println(s);
}

void arm(Servo m){
  Serial.print("Arming.");
  m.write(0);
  delay(100);
  m.write(1224); //A value at which the motor starts turning
  delay(2000);
  m.write(1024); //A value at which the motor stands still
  delay(3000);
  Serial.println(" Armed!");
}

```

You can also see a video of the whole thing in action here: A2212/13T brushless motor on a pivoting arm

**EDIT:** Further testing shows, that it suffices to output a low non zero value to arm this ESC. Simply doing Servo.write(1024); until you hear the confirmation beep seems to work.

---
Tags: motor
---


# Question
Title: Is it possible to reduce the size of this program to 1KB
I want to use attiny13 in my project but this program is going over 1KB

```
void setup()
{
  Serial.begin(9600);
  delay(2000);
  Serial.println("AT+CMGF=1");
  delay;
}
void loop()
{
  for (int i=0 ;i < 1 ;i++)
  {
    delay(1500);

    Serial.print("AT+CMGS=\"");
    Serial.print("+918269394684");
    Serial.println("\"");
    while(Serial.read()!='>');
    {
      Serial.print("22.7010709,75.9372517");
      delay(500);
      Serial.write(0x1A);
      Serial.write(0x0D);
      Serial.write(0x0A);
      delay(5000);
    }
  }
}

```

# Answer
There are several problems with your program as shown that make a good answer impossible. After I list those problems, I'll then proceed to give an answer, partly good, partly bad. The good part is that the 432-bytes-of-code program shown below should send all the indicated text strings, in the proper order and separated by appropriate delays. The bad part is that it sends at 115200 bps instead of 9600. Depending on point of view, it may be good or may be bad that the code doesn't look for absence of `'>'` on Serial input; as I note in discussion of problems, the original code's unclear.

As promised, here are several problems with your program as shown, and how to fix them:

* The statement `delay;` is a constant expression \[address of the `delay()` function rather than a call to `delay()`\] so take it out.
* The statement `for (int i=0 ;i < 1 ;i++)` is a do-nothing so take it out.
* The sequence `while(Serial.read()!='>'); {` is confusing – it compiles but isn't something a rational programmer would write – so take it out. (As written, with a semicolon directly between the right parenthesis and the left brace, it busy-waits until it reads `'>'` on Serial input. Then the unnecessarily-blocked block of statements within the matched braces executes one time and `loop()` exits its current pass. If the semicolon weren't there, the statements within the braces would execute repeatedly until a `'>'` appears on Serial input.)

Anyhow, with the minor fixes outlined above, and using the `BasicSerial` library from nerdralph's writing AVR assembler code with Arduino page, we get the following message for the program shown below.

> Sketch uses 432 bytes (42%) of program storage space. Maximum is 1,024 bytes. Global variables use 68 bytes of dynamic memory.

```
#include <BasicSerial.h>
char *text = "AT+CMGF=1\n\0"    "AT+CMGS=\"+918269394684\"\0"
  "22.7010709,75.9372517\0" "\033\r\n";
#define send(item) while (*item) TxByte (*item++)
void setup() {
  //Serial.begin(9600);
  delay(2000);
  //Serial.write("AT+CMGF=1\n");
  send(text);
  //delay;
}
void loop() {
  char *msg = text;
  delay(1500);          // took out `for`
  //Serial.write("AT+CMGS=\"+918269394684\"");
  send(msg);
  //while(Serial.read()!='>'); {
  //Serial.write("22.7010709,75.9372517");
  send(msg);
  delay(500);
  //Serial.write("\033\r\n");
  send(msg);
  delay(5000);
  //}
}

```

*Program Notes:*

1. The string `text` contains all the text from your original `Serial` prints and writes. With the text organized as a single string, the program only needs to set its character pointer `msg` once per loop, saving perhaps half a dozen bytes of code.
2. The commented-out `Serial.write` statements are equivalents of your various `Serial.println`, `Serial.print`, and `Serial.write` statements, with adjacent strings lumped into single writes, thus for example using one write instead of three to write the Esc, CR, LF sequence just before `delay(5000)`. Just changing those printlns, prints and writes all to writes reduces code size by about 150 bytes, which might be enough of a reduction to get you by, depending where you start from. But in my tests, substituting `BasicSerial` in place of `Serial` saves over a thousand bytes so is likely to be a requirement.
3. You probably can modify the code in `BasicSerial.S` for other data rates, or perhaps can substitute one or another of the small `Serial` replacements listed in ernstc's Serial communication with the Tiny's webpage, to get different data rates and/or receive as well as transmit.

*Edit:* As Edgar Bonet noted in a comment, an ATtiny13 has 64 bytes of RAM, so the above program (using 68 bytes of RAM) will fail. RAM usage can be reduced by copying string characters individually from program memory, instead of copying the string into RAM (per Arduino default). See the following revision of the program, which also corrects a problem (leaving `msg` pointed at a null byte) that would keep the former program from working. Note, with these changes, we have:

> Sketch uses 456 bytes (44%) of program storage space. Maximum is 1,024 bytes. Global variables use 6 bytes of dynamic memory.

```
#include <BasicSerial.h>
#include <avr/pgmspace.h>
const char text[] PROGMEM = "AT+CMGF=1\n\0"
  "AT+CMGS=\"+918269394684\"\0"
  "22.7010709,75.9372517\0" "\033\r\n";
char *front = (char*)text;
#define send(item) while (pgm_read_byte(item)) TxByte (pgm_read_byte(item++))

void setup() {
  delay(2000);
  send(front);  ++front;
}
void loop() {
  char *msg = front;
  delay(1500);
  send(msg);   ++msg;
  send(msg);   ++msg;
  delay(500);
  send(msg);
  delay(5000);
}

```
> 5 votes

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


title: LCD does not work with if condition

text:
# Question
Title: LCD does not work with if condition
```
#include <LiquidCrystal.h>
#include <Wire.h>

LiquidCrystal lcd(2, 3, 4, 5, 11, 12);// initialize the library with the numbers of the interface pins

int pirPin = 7; //Variable that will receive the digital signal from the sensor
int LEDgreen = 6; //LED addressed to the digital pin 6
int speaker = 8; //speaker addressed to the digital pin 7
int buttonPin = 9; // the pin that the pushbutton is attached to

void setup(){
  pinMode(buttonPin, INPUT);// Initialize the button pin as an input:
  pinMode(pirPin, INPUT);  // declares variable pirPin as an input
  pinMode(LEDgreen, OUTPUT); // declares variable LEDgreen as an output
  pinMode(speaker, OUTPUT); // declares variable speaker as an output
  lcd.begin(16, 2);
  // turn on the cursor:
  lcd.cursor();
  Serial.begin(9600);
}

void loop(){
  int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
  int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal
  if(buttonState == LOW){
    if(digitalRead(pirPin) == LOW){
      /*The LED Blinks once with the command digitalWrite
      the LED keeps turned on after blink during the motion cycle*/
      digitalWrite(LEDgreen, HIGH);
      delay(1000);
      digitalWrite(LEDgreen, LOW);
      delay(500);
      digitalWrite(LEDgreen, HIGH);
      /*speaker plays frequency, the number 7 is the digital pin,
      the second number is the frequency played and the third number is the sound duration
      we repeated this command with different frequency and varying the time in order to create a
      pleasant sound */
      tone(4,261,300);
      delay(200);
      tone(4,329,300);
      delay(200);
      tone(4,392,600);
      delay(200);
      tone(4,329,300);
      delay(200);
      tone(4,392,300);
      delay(200);
      tone(4,493,600);
      delay(200);
      tone(4,392,300);
      delay(200);
      tone(4,493,300);
      delay(200);
      tone(4,294,600);
      delay(200);
      lcd.setCursor(0,0);
      lcd.print("  Motion  ");  // Print a message to the LCD.
      lcd.setCursor(0,1);
      lcd.print(" Detected ");
    } else if(digitalRead(pirPin) ==  HIGH) {
       digitalWrite(LEDgreen, LOW); // Turn off the LED in the case where no motion is detected
       lcd.setCursor(0,0);
       lcd.print("No Motion  ");
       lcd.setCursor(0,1);
       lcd.print(" Detected ");
     }
   } else if(buttonState == HIGH) {
     if(digitalRead(pirPin) == LOW) {
       digitalWrite(LEDgreen, HIGH);
       delay(1000);
       digitalWrite(LEDgreen, LOW);
       delay(500);
       digitalWrite(LEDgreen, HIGH);
       tone(4,261,300);
       delay(200);
       tone(4,329,300);
       delay(200);
       tone(4,392,600);
       delay(200);
       tone(4,329,300);
       delay(200);
       tone(4,392,300);
       delay(200);
       tone(4,493,600);
       delay(200);
       tone(4,392,300);
       lcd.setCursor(0,0);
       lcd.print("  Motion  ");
       lcd.setCursor(0,1);
       lcd.print(" Detected & door ");
     } else if(digitalRead(pirPin) ==  HIGH) {
       digitalWrite(LEDgreen, LOW);
       // Turn off the LED in the case where no motion is detected
       tone(4,329,300);
       delay(200);
       tone(4,392,300);
       delay(200);
       tone(4,493,600);
       delay(200);
       tone(4,392,300);
       lcd.setCursor(0,0);
       lcd.print("No Motion  ");
       lcd.setCursor(0,1);
       lcd.print(" Detected but door ");
     }
   }
   delay(2000); // wait for 1 seconds before compare again
 }

```

# Answer
> 1 votes
This is a summary of your basic loop logic:

```
void loop() {
  int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
  int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal
  if (buttonState == LOW) {
    if (digitalRead(pirPin) == LOW) {
        // buttonState is LOW
        // pirPin is recently read as LOW
        // ... Motion Detected ...
    }
    else if (digitalRead(pirPin) ==  HIGH) {
        // buttonState is LOW
        // pirPin is recently read as HIGH
        // ... No Motion Detected ...
    }
  }
  else if (buttonState == HIGH) {
    if (digitalRead(pirPin) == LOW) {
        // buttonState is HIGH
        // pirPin is recently read as LOW
        // ... Motion Detected & Door ...
    }
    else if (digitalRead(pirPin) ==  HIGH) {
        // buttonState is HIGH
        // pirPin is recently read as HIGH
        // ... No Motion Detected but Door ...
    }
  }
  delay(2000); // wait for 1 seconds before compare again
}

```

However, this is bad code:

```
if (digitalRead(pirPin) == LOW) {
    // ... Motion Detected ...
}
else if (digitalRead(pirPin) ==  HIGH) {
    // ... No Motion Detected ...
}

```

because each time the digitalRead(..) function is called, it can give a different value. So even though your intention is clear, this code won't work the way you expect. Consider what happens if the first digitalRead(pirPin) is high, so digitalRead(pirPin)==LOW is false, but then the second digitalRead(pirPin) is low, so digitalRead(pirPin)==HIGH is also false. Then neither block of code runs. Instead, use:

```
if (digitalRead(pirPin) == LOW) {
    // ... Motion Detected ...
}
else {
    // ... No Motion Detected ...
}

```

Or since you already sampled it at the start of the loop with `int pirVal = digitalRead(pirPin);`, simplify the logic as:

```
void loop() {
  int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
  int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal

  if (buttonState == LOW) {
    if (pirVal == LOW) {
        // buttonState is LOW
        // pirPin is LOW
        // ... Motion Detected ...
    }
    else {
        // buttonState is LOW
        // pirPin is HIGH
        // ... No Motion Detected ...
    }
  }
  else {
    // buttonState is HIGH
    if (pirVal == LOW) {
        // buttonState is HIGH
        // pirPin is LOW
        // ... Motion Detected & Door ...
    }
    else {
        // buttonState is HIGH
        // pirPin is HIGH
        // ... No Motion Detected but Door ...
    }
  }
  delay(2000); // wait for 1 seconds before compare again
}

```

By the way, if you're using the Arduino IDE, you can easily clean up the indentation to make these control structures easier to see, by using Tools | Auto Format.

---
Tags: arduino-uno
---


# Question
Title: How to send an email via Arduino without an email account?
Assuming I have all the necessary hardware... I want to develop a system where you type in an email address and the Arduino will send hourly updates on attached sensors to the provided email address.

I can only get this to work if I enter my email account's username and password and send the email from the authenticated account. There's tons of examples online of this. However, I want to share it with others and I do not want my email authentication to be accessible or be attached with sending the emails. For example, I want the email to be from a generic service like email@web-mail.com that no one can sign into and not my personal email or a Gmail account I made for the project.

Anonymous email senders have the right method, but they require human interaction to bypass Captcha or similar.

Does anyone have an idea of how to do this? Or should I make a separate webserver that handles the requests made by the Arduino and send emails through a Gmail account I made for the project?

# Answer
You may be able to do this by running the SMTP transaction yourself. You don't actually need a valid from address (though I probably shouldn't be saying that). There are a number of resouces for how to do this, here's a quick list:

If you read an article telling you how to do SMTP in a generic sense (not using a particular provider's infrastructure) and it looks like they want a "real" e-mail address, you can try with a fake one. Chances are decent that it may work.

There are some fine points that may cause you grief if you go for the most simple of implementation (for example, just because my e-mail address is foo@bar.org doesn't mean that bar.org will accept an SMTP connection, the "right" way to do it is to check DNS for an MX record for bar.org).

It would be best to do (and log) any errors that you encounter. There are plenty of things that can go wrong, so tracking where it blows up will help you – or anybody who's trying to help you debug.

If you don't want to roll your own SMTPClient and FullIP look worth checking out.
> 1 votes

# Answer
I am thinking that you will have a few issues in doing this,

If you wish to, as mentioned by *dlu*, run the SMTP Transaction from the device yourself, you are free to do that, however, most SMTP Relays will require some sort of authentication; this is to prevent me from using a random relay to send out millions of messages.

Another issue may be that if you do setup a local relay, your ISP will block traffic on port 25, which is common; this means your mail can never be delivered to an external server.

My thoughts on the *simplest* way to do this would be getting a Virtual Private Server that will run the mail service and a webserver; you could then make a simple PHP script that will accept a few parameters, and send an email.

Following the above, you would only need to make an HTTP request to your server for the mail to be sent,

```
http://web-mail.com/sendmail.php/?to=someone@somewhereelse.com&subject=Wooo&Message=This%20is%20a%20message.

```
> 1 votes

---
Tags: communication
---


title: PID and pulseIn()

text:
# Question
Title: PID and pulseIn()
I am making a system of regulation of the temperature using PID. I want to keep my temperature in 37 celsius. in order to understand the stability of my system easily, I want to see the fuction of temperature in terms of time. I found a function pulseIn() who Read a pulse (either HIGH or LOW) on a pin. But I don't know how to do it into my program. this is the program of my PID system:

```
#include <PID_v1.h>
#include "math.h"
int c=0;
int  i=0, output2 = 0, output3 = 0;
double val=0.0;
double val2 = 0.0;
//Define Variables we'll be connecting to
double Setpoint, Input, Input2, Output=0;
double tOnMax = 50.0;

//Specify the links and initial tuning parameters
PID myPID( &Input, &Output, &Setpoint,10,20,20, DIRECT);

void setup()
{
  //initialize the variables we're linked to
  Setpoint = 37; //temperature a reguler

  //turn the PID on
  pinMode(9, OUTPUT);
  myPID.SetOutputLimits(-100, 100);
  myPID.SetMode(AUTOMATIC);
  Serial.begin(19200);
  while (!Serial);
}

void loop()
{
  // phase haute
  digitalWrite(9,HIGH);
  delay(output2);
  // phase basse
  digitalWrite(9,LOW);

  for (i = 0; i < 64;i++)
      val += analogRead(0);
  val /= 64.;

 for (i = 0; i < 64;i++)
      val2 += analogRead(1);
  val2 /=64.;

  float mv = round (( val/1024.0)*5000);
  float mv2 = round (( val2/1024.0)*5000);
  Input = mv/10;
  Input2 = mv2/10;
//  Serial.println(Input);
  myPID.Compute();
  output2 = map(Output, -100, 100, 0, tOnMax);
  output3 = map(Output, -100, 100, 0, tOnMax);
//  Serial.print("output is :");
//  Serial.println(output2);
//  Serial.print("Input: ");
for (c=0; c < 500; c++) {}
Serial.println(Input);

}

```

thnak you in advance

# Answer
> 1 votes
> I want to see the evolution of the function tempertaure (t), in other words, i want to see in my screen for exemple: 24.1C -\> 20ms ; 25C-\> 200ms; 26 -\> 500ms

Quite apart from managing the heater, it sounds as if you need to sample the temperature at a constant rate, compare its value to any of several temperature-intervals, and, when it moves out of one interval into another, report the time it spent within the previous one. This will require saving which interval the temperature was last observed in, and the time it entered that interval, re-saving both when it moves into a new one. You may need to apply some smoothing to the temperature data to if there is any noise in the temperature data to prevent it appearing to jitter back and forth between intervals during interval edge crossings.

# Answer
> 1 votes
OK, with such a slow heater as compared to the calculation time of the arduino, you likely want to use a much longer sampling time. One could disconnect the PWM time and the sampling time from the loop() time by replacing the delay() with millis() as in Using Arduino for simultaneous lighting effects and below, and with a sampling time of 1s, 10s or 60s, the parameters of the PID and the integral and derivative terms could start making sense. i.e. the D term would conform to watts/(degreeError/minute), the I term to Watts/(degreeError\*minutes) and P to watts/degreeError.

One nice way to think of a PID controller is that it converts process errors into a control variable. If you want to convert "degrees below setpoint" into "milliseconds of heat per tOnMax second cycle", set that directly:

```
// Tuned for full power (1000ms/sec) up to 35C: P=1000/2
PID myPID( &Degrees, &millisecondsOn, &Setpoint,500,0,0, DIRECT);
myPID.SetOutputLimits(0, tOnMax);
...

```

Or "duty cycle of heater"

```
// Tuned for full power (100%) up to 35C: P=1.0/2
PID myPID( &Degrees, &millisecondsOn, &Setpoint,0.5,0,0, DIRECT);
myPID.SetOutputLimits(0, 1.0);
...

```

I didn't want to edit your code too much, but went for a 1s PWM frequency, 10s sampling or PID cycle time. The 1sec PWM/cycle time is the minimum most commercial PID controllers work with (typically 1s-999s to handle a range from solid-state-relay controlled resistive heating elements to relay controlled mechanical systems like pilot light heaters or fan/pump systems) and should be plenty fast enough for your system. Slower PWM times are better for mechanical systems, and faster times are better for thermal cycling of resistive elements.

The 10s cycle time is ~200x slower than your initial code looks like it is sampling, but the 10s time might be more in keeping with the physical changes in your system as compared to your resolution. I can't tell the temperature resolution of your sensor for your code, but assuming it is 0.1C, taken with a (37C-20C)/30m=0.0094C/s rate of change, it would take about 10s to make 1 bit of detectable change. If you sample faster than that, all you will be getting is noise or no change. Sampling significantly faster than the physical process changes can serve to confuse a PID in the integral and derivative terms--Derivative because the derivative of error is mostly zeros or noise, and Integral because the integral accumulator can wind up before the system even begins to move. Looking at the Arduino PID library code at https://github.com/br3ttb/Arduino-PID-Library/blob/master/PID\_v1.cpp#L57 with a I=20, output limits of (-100,100), a t0=20C, a setpoint of 37, sampling time of 50ms, and a temperature rate of change of 0.0094C/s, the Iterm accumulator would be wound up to 100 in just 0.300 seconds. The wound-up integral would guarantee an overshoot until the integral accumulator erodes afterwards (For example: 37.5C for 10s? 37.1C for 100s? ???)

With a 1000ms PWM and 10s sampling time base, you would need to reconsider your PID settings. In particular, the I and D terms strongly sensitive to the sampling time and the output range. As a start, PID myPID( &Input, &Output, &Setpoint,500,0,0, DIRECT); would start to proportionally turn the heater off at 37-1000/500)=35C, which might be good enough for your needs. If that isn't close enough, you could increase P more to tighten the proportional band. ("Proportional band" is error band where the P\*error term of the PID doesn't saturate the output limits, i.e., PropBand = +/-(tOnMax/P) ) Alternately, you could fiddle with the I term to completely eliminate the droop.

```
#include <PID_v1.h>
#include "math.h"
int c=0;
int  i=0, output2 = 0, output3 = 0;
double val=0.0;
double val2 = 0.0;
//Define Variables we'll be connecting to
double Setpoint, Input, Input2, Output=0;
double tOnMax = 1000.0; // 1 second PWM controlling 10w heater
unsigned long sampleTime, heaterTime;

//Specify the links and initial tuning parameters
// Process takes 30m to come to 37C from 17C at 10W
// Proportional: Full power to setpoint-2C, then proportional taper: P= tOnMax/2
// Integral: 30m = 300 samples, so area under curve = 20*300/2=3000
// so for integral to roll up to 50% power (1/2 tOnMax) in 30m:
// I = tOnMax/2/3000 = 1000/2/3000 = 0.15
// Derivative: Max slew rate of 20C/30m = 20C/300 10sSamples = 0.067C/sample
// Ignore the derivative for now to avoid potential noise problems,
// but D=tOnMax/0.067=15000 would anticipate and counteract the maximum slewing rate
PID myPID( &Input, &Output, &Setpoint,tOnMax/2,0.15,0, DIRECT);

void setup()
{
  //initialize the variables we're linked to
  Setpoint = 37; //temperature a reguler

  //turn the PID on
  pinMode(9, OUTPUT);
  myPID.SetOutputLimits(0, tOnMax);
  myPID.SetMode(AUTOMATIC);
  Serial.begin(19200);
  while (!Serial);
  heaterTime=sampletime=millis();
}

void loop()
{
  unsigned long now = millis();
  if(heaterTime < now){
     if(digitalRead(9)) {// phase haute -> basse
        heaterTime += tOnMax-output2; // schedule on
        digitalWrite(9,LOW);}
     } else {  // phase basse -> haute
       heaterTime += output2);  // schedule off
       digitalWrite(9,HIGH);
     }
  if (sampleTime < now ) {
      sampleTime = sampleTime + 10000;  // every 10 seconds
      val=0=val2=0;
      for (i = 0; i < 64;i++)
          val += analogRead(0);
      val /= 64.;

      float mv = round (( val/1024.0)*5000); // convert to degrees*10?
      Input = mv/10;        // degrees
      myPID.Compute();
      output2 = Output;
      Serial.print(Input);
      Serial.print("C -> ");
      Serial.print(output2);
      Serial.print("ms / ");
      Serial.println(tOnMax);
   } // end sample
}

```

---
Tags: arduino-uno
---


# Question
Title: Why does my Arduino freezes when i turn a servo
I have a Servo Motor and an Arduino Uno.

I used the Arduino to run a servo motor. The code was very simple. It was to just Turn it 90 Deg Anti-Clockwise when a switch is pressed and Turn back to its original position (90 Deg Clockwise).

The servo had 3 pins. 1. V+ 2. Ground 3. Data

I connected the V+ to the Arduino's 5v Output. And the Ground to the Arduino's GND pin. I connected the Data to Digital Pin 3.

When ever this script runs, The servo turns a little and then stops. It stops because the arduino froze and It wont do anything. I pressed the Reset button and it does nothing. I plugged off the Servo and the Power Supply and replugged the Power and it works.

The power source was a battery pack with 4x 1.5 Volts batteries in it. Maybe there was a problem with this?

Do anyone know what might be the problem here? Any Answer will be Appriciated. Thanks.

# Answer
> 2 votes
You said that you were using 4x 1.5v batteries. That would make a total of 6 volts. The current that those batteries can supply is also little.

The Recommended Input Range is 7-12 volts. And the Limit is 6-20 volts.

You were supplying it with 6 Volts which is at the very limit of the Input Voltage Range. When the motor runs, the Voltage might have dropped and made the arduino freeze.

The fix is to supply the arduino with another source such as a benchtop supply that can supply more than 8 volts.

# Answer
> 1 votes
Connect your servo V+ to your battery stack and the servo data input to your Arduino. I suspect that the servo is causing the Arduino to reset when the servo draws too much current through the Arduino's voltage supply circuitry.

# Answer
> 1 votes
My first response would be a brown out reset. Because of the load the voltage will sag and drop below a certain voltage so the microcontroller will reset. Try to put a big buffer capacitor on the power supply.

Other possible cause could be inductive spiking, but I dont expect this to be the cause of your problem.

---
Tags: servo
---


title: Amplification of microphone circuit

text:
# Question
Title: Amplification of microphone circuit
I am getting constant values and I need to know the amplification of the circuit. I believe that amplification = R8/R6 though I am not sure.

# Answer
You are mostly correct Diana. The gain of an OP-Amp would normally be R8 divided by R6.

However, what needs to be recognized is that in your circuit, the resistance of R3 and the microphone get entangled with your R6.

The resistance (impedance of your microphone) is in series with R6. R3 also comes into play, but I will ignore it here (subject of another question on amplifiers).

So, since R of microphone is in series with your R6, your gain (amplification) will be slightly less than you have calculated.

The old 741 Op-Amp won't work very well (probably not at all) with a single ended power supply of 5 volts. Although you have done a good job of biasing the non-inverting input (+) at 2.5 volts.

The 741 output can't get near the +5 volts, nor can it get near ground. Try a better Op-Amp such as MCP6002. Look at how the output of the MCP6002 can approach the rails (your power supply and ground).
> 2 votes

---
Tags: arduino-micro, op-amp
---


title: I2C send and read 2 bytes many slave

text:
# Question
Title: I2C send and read 2 bytes many slave
I've already sent you the code but you told me to format it, so I tried this way ..

the problem I got is it doesn't read good the 2 slave (sender) to the master

(reader) ...you told me LAST TIME (DON'T DO SERIAL PRINTLN IN THE CALLBACK

ROUTINE) so I tried this code (I've got some data from both but not in order)

here's the slave 1 and 2 code (I only change the `slavedeviceId` address)

```
#include "Wire.h"

//
// i2c_test_01

//
// This demonstrates a master transmitting to a slave.
//

// The master transmits a value read from an analogue port.

// The slave sends the value to the serial device.
//

byte x = 0;
//
const byte AnalogueInputPin = 0;

const byte SlaveDeviceId = 2;

void setup() {
  // Start I2C bus as master
  Wire.begin();
}

void loop() {
  int input0 = analogRead(x);
  // Send two bytes to slave.
  Wire.beginTransmission(SlaveDeviceId);
  Wire.write(input0 >> 8);
  Wire.write(input0 & 255);
  Wire.endTransmission();

  delay(10);

  x++;
  if (x == 4) {
    x = 0;
  }

  delay(40);

}

```

here's the master (reader)

thanks for your time it is realy intructive for me !!!

```
#include "Wire.h"

const byte SlaveDeviceId = 1;
const byte SlaveDeviceId2 = 2;
int S1;
int S2;
int c;
int cc;

void setup() {
  // Start I2C bus as a slave
  Wire.begin();
  Wire.onReceive(receiveCallback);
  Serial.begin(9600);
}

void SLAVEone() {
  Wire.begin(SlaveDeviceId);
  delay(5);
  Wire.onReceive(receiveCallback);
  delay(5);
}

void SLAVEtwo() {
  Wire.begin(SlaveDeviceId2);
  delay(5);
  Wire.onReceive(receiveCallback2);
  delay(5);
}

void receiveCallback(int aCount) {
  if(aCount == 2) {
    int receivedValue  = Wire.read() << 8;
    receivedValue |= Wire.read();
    //Serial.print(c);
    //Serial.print(" S1 = ");
    //Serial.println(receivedValue);
    S1 = receivedValue;
  } else {
    Serial.print("Unexpected number of bytes received: ");
    Serial.println(aCount);
  }
  c++;
  if (c == 4) {
    c = 0;
  }
}

void receiveCallback2(int aCount2) {
  if (aCount2 == 2) {
    int receivedValue2  = Wire.read() << 8;
    receivedValue2 |= Wire.read();
    // Serial.print(cc);
    //Serial.print(" S2 = ");
    //Serial.println(receivedValue2);
    S2 = receivedValue2;
  } else {
    Serial.print("Unexpected number of bytes received: ");
    Serial.println(aCount2);
  }
  cc++;
  if (cc == 4) {
    cc = 0;
  }
}

void loop() {
  for(int y = 0; y <= 3; y++) {
    SLAVEone();
    Serial.print(c);
    Serial.print(" = S1 = ");
    Serial.println(S1);
    delay(10);
  }
  for(int y = 0; y <= 3; y++) {
    SLAVEtwo();
    Serial.print(cc);
    Serial.print(" = S2 = ");
    Serial.println(S2);
    delay(10);
  }
}

```

# Answer
There are so many mistakes in your code. I'll do my best to correct them using comments. The code for the slaves should be as follows:

```
#include "Wire.h"

//
// i2c_test_01

//
// This demonstrates a master transmitting to a slave.
//

// The master transmits a value read from an analogue port.

// The slave sends the value to the serial device.
//

int inp = 0;  // input pin

const byte SlaveDeviceId = 2;

void setup() {
  Wire.begin(SlaveDeviceId);  // here the slave joins the bus, with its address as argument to begin()
  Wire.onRequest(callback);  // here you indicate what the slave should do if a bus master queries it
}

void callback() {
  int input0 = analogRead(inp);
  // Send two bytes to master
  Wire.write(input0 >> 8);
  Wire.write(input0 & 255);

  inp++;
  if (inp == 4) {
    inp = 0;
  }

}

void loop(){}

```

This is the master's code:

```
#include "Wire.h"

const byte SlaveDeviceId = 1;
const byte SlaveDeviceId2 = 2;
char inputDev = 4;  // number of devices connected to slave analog inputs

void setup() {
  Wire.begin();   // no argument here since its a master
  Serial.begin(9600);
}

//the onReceive() method is for slaves receiving from a master, so we dont use it here

void loop() {
  Serial.println("\r\nSlave 1: ");
  for (char i = 0; i < inputDev; i++){
    Wire.requestFrom(SlaveDeviceId, 2);
    delay(1);  // more than enough time for all the data to come in
    int val = Wire.read() << 8;
    val |= Wire.read() & 0xFF;
    Serial.print(val);
    Serial.print(",");
  }
  Serial.println("\r\nSlave 2: ");
  for (char i = 0; i < inputDev; i++){
    Wire.requestFrom(SlaveDeviceId2, 2);
    delay(1);  // more than enough time for all the data to come in
    int val = Wire.read() << 8;
    val |= Wire.read() & 0xFF;
    Serial.print(val);
    Serial.print(",");
  }

}

```
> 2 votes

# Answer
I don't quite see how your code is supposed to work. It seems like your "slave" devices are trying to write to your "master" as if they were master devices not slaves, and your "master" is rapidly switching between thinking it is one of two slaves. The whole methodology is backwards. The "master" should connect to a "slave" and request the data not wait for a "slave" to randomly throw data at it.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino thermometer and humidity display with 7 segment LED display
I want to use an Arduino Uno, a seven segment LED display (four digits) and the SevSeg library, to see temperature and humidity (alternatively).

First of all I try this code:

```
  #define COMMON_ANODE 1
  #define COMMON_CATODE 0
  #include "DHT.h"
  #define DHTPIN A5     // pin analogico che legge i dati
  #define DHTTYPE DHT22   // DHT 22  (AM2302)
  #include "SevSeg.h"

  // Crea un'istanza dell'oggetto
  SevSeg sevseg;
  DHT dht(DHTPIN, DHTTYPE);
  unsigned long timer; // the timer
  unsigned long INTERVAL = 5000; // the repeat interval (30 seconds)

  int segA = 6;   // Undicesimo PIN del display 7Segment x 4
  int segB = 2;   // Settimo PIN del display 7Segment x 4
  int segC = 10;  // Quarto PIN del display 7Segment x 4
  int segD = 12;  // Secondo PIN del display 7Segment x 4
  int segE = 13;  // Primo PIN del display 7Segment x 4
  int segF = 5;   // Decimo PIN del display 7Segment x 4
  int segG = 9;   // Quinto PIN del display 7Segment x 4
  int segDP = 11; // Terzo PIN del display 7Segment x 4

  int digit1 = 7; // Dodicesimo PIN - PWM che Accende il primo digit
  int digit2 = 4; // Nono PIN - PWM che Accende il secondo digit
  int digit3 = 3; // Ottavo PIN - PWM che Accende il terzo digit
  int digit4 = 8; // Sesto PIN - PWM che Accende il quarto digit

  void setup()
  {
    dht.begin();
    int numberOfDigits = 4; //Numero di cifre del display

    // Inizializzo i PIN
    sevseg.Begin(COMMON_CATODE,digit1,digit2,digit3,digit4,segA,segB,segC,segD,segE,segF,segG,segDP);
    // Imposto la luminosità (valore da 0 a 100)
    sevseg.Brightness(90);
    timer = millis(); // start timer
  }

  void loop()
  {
    if ((millis()-timer) > INTERVAL) {
      // Reset the timer and get/display the current temperature
      timer += INTERVAL;
      // Leggo dal sensore la temperatura
      float t = dht.readTemperature();
      float h = dht.readHumidity();
      //La converto in un numero intero a 4 cifre
      int a=t*100;
      sevseg.NewNum(a,2);
    }
        sevseg.PrintOutput();
  }

```

And it works very well!

But I cant see temperature (first) AND humidity (after) and again temperature (first) AND humidity (after)...

I have tried many ways but... nothing!! Can you help me?

# Answer
You need to maintain a *state* which tells your program whether you are displaying the temperature or the humidity. Every time the timer expires you need to change from one state to the other, and then display the relevant value depending on what the state is.

Something like:

```
bool displaying = false; // false = temperature, true = humidity

void loop() {
    if ((millis()-timer) >= INTERVAL) {
        timer = millis();
        display = !display; // Switch between display values

        if (display) {
            float h = dht.readHumidity();
            sevseg.NewNum(h * 100, 2);
        } else {
            float t = dht.readTemperature();
            sevseg.NewNum(t * 100, 2);
        }
    }
    sevseg.PrintOutput();
}

```
> 1 votes

---
Tags: arduino-uno
---