# Question
Title: Bootloader on Atmega328p overwrites whenever it gets programmed
I built my first custom circuit board with an Atmel ATMega328p-AU the tqfp-32 form factor. I connected xtal1 and xtal2 to an external 16mhz crystal to 22pf caps tied to ground. It seems to work great, I load the Arduino Bootloader using AVRDude and an arduino as an isp. As soon as I load a sketch on using the ftdi it blows out the bootloader and I can't upload a new sketch until reloading the bootloader. The sketch works as expected, my board has an on board relay and an onboard mosfet I've programmed various blink patterns on both the mosfet and relay.I just don't want to have to reload the bootloader everytime I want to make a change, my sketch is an evolving piece of work and it's frustratinf to take these steps. So far I've tried changing the lock bits to 0x0F 0xEF 0xFF and 0X2F. I've tried various fuse bits, I've changed the signature 0x1e 0x95 0x14 to 0x1e 0x95 0x0F. Nothing seems to change the results, the only thing I've managed to do is one upload caused the chip to run at 8mhz instead of 16mhz, oops. That was easily fixed though. Please if someone can help that would be great, unfortunately the fuse bit calculators I have found don't have the 16mhz crystal as an option even though it's clearly functional.

In Summary

Sketches overwrite my bootloader and I want my bootloader locked but I can't find a solution after nearly a full day of googling and experimenting

# Answer
> 1 votes
Almost certainly your fuses are wrong. The fuses tells it whether or not to run the bootloader. With an empty PROGMEM (ie. no sketch) the processor probably skips over all the 0xFF bytes until it hits the bootloader. Once you have a sketch there it will run the sketch.

On my Uno (which is an Atmega328P) running at 16 MHz from a crystal, my fuses are:

```
Low = FF High = DE Ext = FD Lock = EF

```

I suggest you visit http://www.engbedded.com/fusecalc to work out fuse settings.

You want the BOOTRST fuse set (that is, the high fuse should be 0xDE or something with the low-order bit **clear**). On the AVR chips, having a bit clear (0) means the fuse is **set**.

I have a bootloader programmer sketch which not only puts the bootloader there, it sets the correct fuse bit.

I also have a chip detector sketch which will tell you the current fuse settings.

# Answer
> 0 votes
I suspect you aren't writing the fuses on the AVR correctly in some way (or at all?). Try using the "Tools \> Burn Bootloader" functionality of the IDE itself (which will set the fuses as well as loading the flash). You have to make sure you pick your ISP programmer under tools as well for this to work (e.g. Arduino as ISP). See if that works any better for you.

As an aside, there are a variety of AVR online fuse calculators if you're not into reading the datasheet. For example, http://www.engbedded.com/fusecalc. I seem to remember some rumblings in recent history that full swing external crystal configurations wouldn't be supported in new silicon for the ATmega328p, but that's what I always used to pick, and I think it probably still works as a setting.

Honestly, though, the easiest thing to do is to run Arduino in verbose (check the boxes in Preferences) and borrow their avrdude commands that get displayed when you run Burn Bootloader.

**Continuations...**

If *that* (Burn Bootloader) doesn't work for you, we're going to need to see some schematics, and I'd be staring pretty hard at your reset sub-circuit and FTDI sub-circuit.

Arduino Uno bootloader wants you to talk to it at 115200 baud... see the boards file.

What do you mean "My IDE doesn't hae a 328p UNO"? Download the latest Arduino from https://www.arduino.cc/en/Main/Software and choose Genuino Uno.

---
Tags: programming, bootloader, avrdude
---


title: Arduino Skill Stop Push button error

text:
# Question
Title: Arduino Skill Stop Push button error
I made a skill stop game from Arduino Uno and a pushbutton.Here is the code:

```
byte led_one=2;
byte led_two=3;
byte winner_led=4;
byte led_four=5;
byte led_five=6;
byte pushbutton=12;
byte score=0;
int pushbutton_value=digitalRead(pushbutton);

void setup()
{
// put your setup code here, to run once:
   pinMode(led_one,OUTPUT);
   pinMode(led_two,OUTPUT);
   pinMode(winner_led,OUTPUT);
   pinMode(pushbutton,INPUT_PULLUP);
   pinMode(led_four,OUTPUT);
   pinMode(led_five,OUTPUT);
   Serial.begin(9600);
  }

void loop()
{
// put your main code here, to run repeatedly:

  for (int x=1;x<=6;x++)
  {
    digitalWrite(x,HIGH);
    delay(250);
    digitalWrite(x,LOW);
    delay(250);
    if(pushbutton_value==HIGH && x==winner_led)
    {
       score+=500;
    }
    else if(pushbutton_value==HIGH && x==led_one)
    {
       score+=100;
    }
  }
 Serial.println(score);
}

```

My Problem is that Whenever I push the button The Serial Monitor is printing out the wrong score

# Answer
> 0 votes
I wonder why you initialized `score` as byte! Change it to `int`. As you can see when you `Serial Print` your `score` value doesn't cross 256 because the largest value a `byte` can have is 256 but you are summing `score` to 500

---
Tags: arduino-uno, programming, button
---


# Question
Title: How much ohm resistance I should put between tp120 base and uno?
I have set up solenoid on of based on soil moisture, The solenoid is powered by 24 volts, so I power solenoid by 24 volt and Arduino uno by stepping down to 6 volt powering through Vin and gnd.

I have used resistance of 10k ohm but I have twice burnt em. Not sure how should calculate resistance required of signal coming out from D6 pin to TP120 base !

# Answer
To calculate you need to know the maximum current the solenoid uses. The TP120 has a gain of around 500-1000. So the current going into the base needs to be 1/500th of the current going through the solenoid.

So now you know the current needed. Then you can calculate the resistance value you need with `R = V/I`. So `R = 5 / ( <solenoidcurrent> / 500 )`.

So with e.g. a 2A solenoid, you get a value of 1.2kOhm.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Is it possible to detect host usb device connected to arduino? and how?
let's say that I've connected an arduino uno to a pc, or to a mobile phone via usb .. how can I detect the device type and the running operation system if it's possible?

# Answer
You can't, using stock firmware. And with custom firmware it's still very difficult.

The USB communication chip on the Uno has no out-of-band means of telling the main MCU that it is connected to a host. You might be able to rewrite the communication firmware on the R3 to tell the main MCU over serial that it is connected, but the firmware on the main MCU will need to be written in such a manner that it will anticipate this.

If you want this to work then you should consider using one that has a native USB connection, such as the Leonardo. You will then be able to query the USB facility directly to know whether or not you are connected to a host.
> 3 votes

# Answer
No. The arduino sees usb through a USB-\> UART converter (typically FTDI). UART doesn't allow you to do anything other than listen on the RX line and throw bits at the TX line.
> 2 votes

# Answer
I did not try to go further, but I know there is some information passing on *Serial1* when you plug a device.

```
void setup() {
  Serial.begin(115200);
  Serial1.begin(250000);
}

void loop() {
  if(!Serial1.available()) {
    Serial.println("OFF");
    delay(500);
  }
  else {
    Serial.println("ON");
    Serial1.end();
    delay(500);
    Serial1.begin(250000);
  }
}

```

Maybe you can try to see if depending on the device, information is persistent, in which case you should be able to detect a specific device / kinf of device ? I'll look at it tomorrow, maybe will have more code to show...
> -1 votes

---
Tags: usb
---


# Question
Title: Arduino Leonardo - disabling the debugger port
My Sketch program is working perfectly as a specialized keyboard application on the Leonardo. I want to disable the development tools drivers from the USB, (COM PORT) leaving only the HID Keyboard drivers. I understand I will need to use the Arduino ISP or other method to load my code.

Is there any way to disable the drivers for the development tools from the on board USB, leaving just the HID drivers?

# Answer
There is no easy way, no. You have to reprogram the core to break the connection between the USB interface and the CDC/ACM driver. That means working out a new set of descriptors, deleting chunks of code, patching around the newly created holes, etc.
> 1 votes

---
Tags: usb, arduino-leonardo, keyboard
---


# Question
Title: How convert eight hex characters to uint32_t using strtol() function?
I want to control 4 pins using hexa code like this ff00ff00 (255, 0, 255, 0).

strtol() function works fine with three pins like 00ff00, but when i add two extra caracters to &payload\[1\] variable like this ff00ff00. ((rgba \>\> 24) & 0xFF) is equal to 127 when it should be 255. How to make this work?

each analog pin should be set from 0 to 255

```
    analogWrite(LED_WHITE,  ((rgba >> 24) & 0xFF));
    analogWrite(LED_RED,    ((rgba >> 16) & 0xFF));
    analogWrite(LED_GREEN,  ((rgba >> 8) & 0xFF));
    analogWrite(LED_BLUE,   ((rgba >> 0) & 0xFF));

    uint32_t rgba = (uint32_t) strtol((const char *) &payload[1], NULL, 16);

```

# Answer
> 5 votes
The function strtol() is not able to convert numbers that are larger than LONG\_MAX and smaller than LONG\_MIN as it uses signed numbers.

You should use the function strtoul() instead (for unsigned long integers).

Cheers!

---
Tags: programming
---


title: Arduino RGB component identification

text:
# Question
Title: Arduino RGB component identification
Can someone help me identify this component?

Thanks in advance.

# Answer
> 2 votes
It's a common-cathode RGB LED module. The LED package itself has 3 independent LEDs, but the board ties the cathodes together.

---
Tags: components
---


# Question
Title: Using SPI Interrupt causes two servos to lose functionality
My Arduino MEGA clone (ATMEGA 2650) reads SPI data as a slave using an interrupt.
There are also two servos that make an arm (shoulder and elbow).

* When I comment out the line that attaches the SPI interrupt, the servos work properly.
* When the SPI interrupt is attached, three strange things happen:

1) The PWM of the elbow remains at a fixed duty cycle. The shoulder works fine.

2) The shoulder PWM is somewhat jittery time-wise, I assume though that this is unavoidable with interrupts.

3) Writing an angle to either servo, (appears to) write to *both* servos! (In the software anyway.) So if I only write to the elbow, the shoulder will have the same value ( printed with shoulder.read() ). And vise-versa.

Again, none of those problems occur when I comment out the SPI interrupt attach.

It doesn't make sense to me though. Why would attaching an interrupt make two servos have the same value? And how can the values of the servos be the same, when only one PWM duty cycle actually changes!?

I wonder if this is a timer issue. Maybe the SPI interrupt interferes with the servo timers or something.

*How can I receive SPI messages while also controlling two servos?*

```
#include <Servo.h>
#include <SPI.h>

const float pi = 3.14159;
const float L1 = 27;
const float L2 = 27;
float c2;
float s2;
float psi;
float theta;

float angle_shoulder = 90;
float angle_elbow = 90;

volatile int arm_x;
volatile int arm_y;
volatile int puck_x;
volatile int puck_y;

Servo shoulder;
Servo elbow;

int sweepDir = 0;
int sweep1 = 0;

unsigned char spiBuffer[5];
volatile byte buffPos;
volatile bool process_spiBuffer;

void setup()
{
    Serial.begin(115200); //Initialize serial communication
    Serial.println("### SETUP ###");

    shoulder.attach(25); //5
    elbow.attach(43); //3

    // BEGIN SPI SETUP
    // Turn on SPI in slave mode
    SPCR |= bit(SPE);

    // Send on master in, *slave out*
    pinMode(MISO, OUTPUT);

    // Get ready for an interrupt
    buffPos = 0;   // buffer empty
    process_spiBuffer = false;

    // Turn on interrupts
    SPI.attachInterrupt();

    // END SPI SETUP
} // END SETUP()

void loop()
{
    arm_y = 30;

    if (process_spiBuffer)
    {
        spiBuffer[buffPos] = 0;
        // X is a two-byte value, SPI only sends one byte at a time, so merge the bits upon receipt
        puck_x = (spiBuffer[1] << 8) | spiBuffer[2];
        puck_y = spiBuffer[3];
        //Check if received message is acceptable, else throw warning and reject message
        if (spiBuffer[0] != '<' || spiBuffer[4] != '>' || puck_x < 0 || puck_x > 320 || puck_y < 0 || puck_y > 240)
        {   //Message received was corrupted
            Serial.print("SPI: Bad MSG Data!:\"");
            //Serial.print(spiBuffer);
        }
        else
        {   //Message received "OK"

            Serial.print("SPI MSG Received:\"");
            //Serial.print(spiBuffer);
            Serial.println("\"");

            Serial.print("SPI puck coords:(");
            Serial.print(puck_x);
            Serial.print(",");
            Serial.print(puck_y);
            Serial.println(")");

            // Decide on new paddle position. (x,y) of puck is 90degrees CW from AI (arm) POV, so x and y are swapped. Arm origin (0,0) is at bottom-right corner from the AI POV.
            arm_x = map((240 - puck_y), 1, 320, 5, 49); // map(value, fromLow, fromHigh, toLow, toHigh)

        }
        buffPos = 0;
        process_spiBuffer = false;
    }

    crunchAngles();
    moveArm();

} // END loop()

void crunchAngles()
{
    c2 = (sq(arm_x) + sq(arm_y) - sq(L1) - sq(L2)) / (2 * L1 * L2);
    s2 = sqrt(1 - sq(c2));

    angle_elbow = acos((sq(arm_x) + sq(arm_y) - sq(L1) - sq(L2)) / (2 * L1 * L2)) * (180 / pi); // theta?
    angle_shoulder = asin((arm_y * (L1 + L2 * c2) - arm_x * L2 * s2) / (sq(arm_x) + sq(arm_y))) * (180 / pi); // psi?

}

// Update the servos
void moveArm()
{
    // TODO: Clip servo output with serial warning
    if (angle_shoulder < -10) { angle_shoulder = -10; } // Actual min angle is about -18deg (Model HS-225BB)
    else if (angle_shoulder > 179) { angle_shoulder = 179; } // Actual max angle is about 181deg (Model HS-225BB)

    shoulder.write(180 - angle_shoulder + 2); // Shoulder increments clockwise, so subtract from 180

    if (angle_elbow < 0) { angle_elbow = 0; } // Actual max angle is about -5deg (Model SG90)
    else if (angle_elbow > 170) { angle_elbow = 170; } // Actual max angle is about 190deg (Model SG90)

    elbow.write(angle_elbow + 3); // Elbow increments clowise from

}

ISR(SPI_STC_vect)
{
    byte c = SPDR;

    if (buffPos < sizeof spiBuffer)
    {
        spiBuffer[buffPos++] = c;

        // End of message is ">"
        if (c == '>') // if (c == '\n')
            process_spiBuffer = true;

    }
}

```

# Answer
You have multiple issues here. For a start, you have a buffer (`spiBuffer`) of 5 bytes, into which you place `<Xxy>` (that's 5 bytes) and then finish off with:

```
    spiBuffer[buffPos] = 0;

```

That has now overwritten some other memory.

---

Next, you don't seem to be detecting the "\<" symbol and resetting to the start of the buffer, so if you ever get out of sync, you will stay out of sync. I suggest something like making `buffPos` equal to `0xFF` initially. Then in the ISR:

```
ISR(SPI_STC_vect)
{
    byte c = SPDR;

    // exit if haven't processed last one
    if (process_spiBuffer)
      return;

    if (c == '<')
      buffPos = 0;
    else if (buffPos == 0xFF)
      return;  // ignore until we get a '<'

    if (buffPos < sizeof spiBuffer)
    {
        spiBuffer[buffPos++] = c;

        // End of message is ">"
        if (c == '>')
            process_spiBuffer = true;

    }
}

```

Now we use 0xFF as a "flag" that we haven't received a "\<" yet. When we do, we reset `buffPos` to zero, ready to process the next 5 bytes. In the main loop, once we are done with processing the buffer we set `buffPos` to 0xFF again (rather than zero). Also you might have the ISR called before you have processed the previous one, so I put in a test to exit if `process_spiBuffer` is true when you enter the ISR.

---

I found your code to work out the arm positions confusing. For debugging this issue I would replace it with simply moving the servo to the position received by SPI, eg.

```
   // crunchAngles();
   // moveArm();

   elbow.write (puck_x);

```

Now just debug that rather than getting confused about the difference between interrupt issues and logic issues. I found once I had done that, that my servo responded without any major issues (there was a bit of jittering occasionally).

---

I found that I got a lot of data errors until I slowed down the **sender** (a few microseconds delay after each SPI.transfer) because sending SPI at high speed didn't give the receiving sketch time to put the data into the buffer.

---

The servo library is rather dependent on interrupts (it manually does the PWM duty cycles). I wrote a sketch a while back that controls one server by using the hardware timer (Timer 1) rather than interrupts:

```
const byte potpin = A0;  // analog pin used to connect the potentiometer

const unsigned long PRESCALER = 8;         // Timer 1 prescaler
const float PULSE_PERIOD = 0.020;          // 20 ms
const float ZERO_POSITION_WIDTH = 0.0005;  // 0.5 ms
const float FULL_POSITION_WIDTH = 0.0024;  // 2.4 ms

// how far apart the pulses are
const unsigned long PULSE_WIDTH_COUNT = F_CPU / PRESCALER * PULSE_PERIOD;
// minimum pulse width (-45 degrees)
const unsigned long ZERO_POSITION_COUNT = F_CPU / PRESCALER * ZERO_POSITION_WIDTH;
// minimum pulse width (+45 degrees)
const unsigned long FULL_POSITION_COUNT = F_CPU / PRESCALER * FULL_POSITION_WIDTH;

void setup()
  {
  TCCR1A = 0;          // disable all PWM on Timer1 whilst we set it up
  ICR1 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

  // Configure timer 1 for Fast PWM mode using ICR1, with 8x  prescaling
  TCCR1A = bit (WGM11);
  TCCR1B = bit (WGM13) | bit (WGM12) |  bit (CS11);  // fast PWM top at ICR1
  TCCR1A |= bit (COM1A1);  // Clear OC1A/OC1B on Compare Match,
  pinMode (9, OUTPUT);
  }   // end of setup

void loop()
{
  int val = analogRead(potpin);  // reads the value of the potentiometer (value between 0 and 1023)
  OCR1A = ZERO_POSITION_COUNT + (val * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;
  delay(15);                     // wait for the servo to get there
} // end of loop

```

That is for the Atmega328P, not the Mega, but you could adapt it easily enough. You could use Timer 2 for the other servo (I think).

Since it doesn't use interrupts, then having interrupts going off in the background won't affect the servo.

---

# Example code

After considerable mucking around, I've got a simpler case working reliably.

> Writing an angle to either servo, (appears to) write to both servos! (In the software anyway.) So if I only write to the elbow, the shoulder will have the same value ( printed with shoulder.read()

That's **exactly** what happened to me! Until ... I realized I should power the servos independently. As soon as I connected both servo's +5V and Gnd to an external power supply (and connected the ground of the power supply to the Mega) it all started working properly. So, lesson #1 is: power your motors properly!

I made up a test "driver" on my Uno using the code below:

```
#include <SPI.h>

void setup (void)
{
  digitalWrite(SS, HIGH);  // ensure SS stays high
  SPI.begin ();
  SPI.setClockDivider(SPI_CLOCK_DIV32);
}

void loop (void)
{
  int val;

  // enable Slave Select
  digitalWrite(SS, LOW);

  SPI.transfer ('<');
  val = analogRead (0);    // read A0
  SPI.transfer (highByte(val));
  SPI.transfer (lowByte (val));
  val = analogRead (1);    // read A1
  SPI.transfer (highByte(val));
  SPI.transfer (lowByte (val));
  SPI.transfer ('>');

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (100);
}

```

That reads a pot on A0 and A1 and sends the full value (2 bytes) over SPI (which is slightly different to what you are doing).

Then the receiving end (on a Mega2560) has this code:

```
#include <SPI.h>

const unsigned long PRESCALER = 8;         // Timer prescaler
const float PULSE_PERIOD = 0.020;          // 20 ms
const float ZERO_POSITION_WIDTH = 0.0005;  // 0.5 ms
const float FULL_POSITION_WIDTH = 0.0024;  // 2.4 ms

// how far apart the pulses are
const unsigned long PULSE_WIDTH_COUNT = F_CPU / PRESCALER * PULSE_PERIOD;
// minimum pulse width (-45 degrees)
const unsigned long ZERO_POSITION_COUNT = F_CPU / PRESCALER * ZERO_POSITION_WIDTH;
// minimum pulse width (+45 degrees)
const unsigned long FULL_POSITION_COUNT = F_CPU / PRESCALER * FULL_POSITION_WIDTH;

const byte NO_DATA_YET = 0xFF;

volatile unsigned char spiBuffer[6];  // '<' xH xL yH yL '>'
volatile byte buffPos = NO_DATA_YET;
volatile bool process_spiBuffer = false;

void setup()
  {
  Serial.begin (115200);   // debugging

  // Turn on SPI in slave mode
  SPCR |= bit(SPE);

  // Send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // Turn on interrupts
  SPI.attachInterrupt();

  TCCR1A = 0;          // disable all PWM on Timer1 whilst we set it up
  ICR1 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

  // Configure timer 1 for Fast PWM mode using ICR1, with 8x prescaling
  TCCR1A = bit (WGM11);
  TCCR1B = bit (WGM13) | bit (WGM12) |  bit (CS11);  // fast PWM top at ICR1
  TCCR1A |= bit (COM1A1);  // Clear OC1A/OC1B on Compare Match,

  #ifdef __AVR_ATmega2560__

    TCCR3A = 0;          // disable all PWM on Timer3 whilst we set it up
    ICR3 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

    // Configure timer 3 for Fast PWM mode using ICR3, with 8x prescaling
    TCCR3A = bit (WGM31);
    TCCR3B = bit (WGM33) | bit (WGM32) |  bit (CS31);  // fast PWM top at ICR3
    TCCR3A |= bit (COM3A1);  // Clear OC1A/OC1B on Compare Match,

    pinMode (11, OUTPUT);   // OC1A is D11 on Mega2560
    pinMode (5, OUTPUT);    // OC3A is D5  on Mega2560
  #else
    pinMode (9, OUTPUT);    // OC1A is D9  on Uno
  #endif
  }   // end of setup

int xValue,
    yValue;

void loop()
{

  if (process_spiBuffer)
    {
    if (spiBuffer [0] == '<' && spiBuffer [5] == '>')
      {
      xValue = makeWord (spiBuffer[1], spiBuffer[2]);
      yValue = makeWord (spiBuffer[3], spiBuffer[4]);
      }

    // ready for another interrupt
    buffPos = NO_DATA_YET;
    process_spiBuffer = false;

    }

  // adjust PWM amount
  OCR1A = ZERO_POSITION_COUNT + (xValue * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;

  #ifdef __AVR_ATmega2560__
    OCR3A = ZERO_POSITION_COUNT + (yValue * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;
  #endif

} // end of loop

ISR(SPI_STC_vect)
{
  byte c = SPDR;   // get byte from SPI hardware

  // exit if haven't processed last one
  if (process_spiBuffer)
    return;

  if (c == '<')
    buffPos = 0;
  else if (buffPos == NO_DATA_YET)
    return;  // ignore until we get a '<'

  if (buffPos < sizeof spiBuffer)
    {
    spiBuffer[buffPos++] = c;

    // End of message is ">"
    if (c == '>')
      process_spiBuffer = true;

   }  // end of room in buffer
} // end of ISR(SPI_STC_vect)

```

This incorporates my suggested use of the timer hardware to do the servo positioning, rather than the servo library. There are a couple of `#ifdef`s in there, so you can run it on a Uno as well (it just won't do the second servo).
> 2 votes

---
Tags: arduino-mega, programming, servo, interrupt, spi
---


# Question
Title: Need Help in circuit diagram of 8*8 reed switch matrix
I am designing 8\*8 reed switch matrix which will be connected to Arduino. I am using Arduino Duemilanove. I have completed the matrix portion but don't know how to connect and where to connect the other elements.

I decided to use the following items:

* Arduino (Duemilanove)
* 64x Reed Switch
* 64x Diode (1N4148)
* 20x Resistors (10K)
* 1x 74HC595
* 1x 74HC165

I don't know where to place the Resistors and shift Registers and connection from shift registers to arduino. I need help in the circuit diagram. Please help me out with the circuit diagram.

**Reference:** https://mtifall10.wordpress.com/2010/12/10/magnetic-sensing-chessboard/

# Answer
**This answer is based on a previous version of the question**

1. Not necessarily. You can use the internal pullups of the arduino if you're willing to accept that reading a "1" means that no piece is there and reading a "0" means a piece is there.
2. Connect each wire up to a pin on the arduino. If you do it wisely, step 3 becomes fairly easy.
3. You need to configure the pins connected to the letter wires as inputs with their pullups enabled. Set the number pins to inputs as well, but without the pullup enabled so that they are floating. The number pins will be each set as an output in sequence with the value being low (non-active number pins are set back to inputs). As you do so, you can read the pins on the letter wires and build a picture of the board.

**Example**

This is how I would do it just taking a naive stab at it. I'm sure there are more effective ways to do this.

Wiring:

Configure the outputs and inputs in `setup`:

```
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(6, INPUT_PULLUP);
pinMode(7, INPUT_PULLUP);
pinMode(8, INPUT_PULLUP);
pinMode(9, INPUT_PULLUP);
pinMode(10, INPUT);
pinMode(11, INPUT);
pinMode(12, INPUT);
pinMode(13, INPUT);
pinMode(14, INPUT); //A0
pinMode(15, INPUT); //A1
pinMode(16, INPUT); //A2
pinMode(17, INPUT); //A3
pinMode(18, INPUT); //A4

```

Make a function to scan the rows into an array of bytes:

```
void scan_rows(uint8_t *rows)
{
    uint8_t i, j;

    for (i = 0; i < 8; i++)
    {
        if (i)
        {
            pinMode(i+9, INPUT);
        }
        pinMode(i+10, OUTPUT);
        digitalWrite(i+10, LOW);
        for (j = 2; j <= 9; j++)
        {
            rows[i] <<= 1;
            if (digitalRead(j))
                rows[i] |= 1;
        }
    }
    pinMode(18, INPUT);
}

```

Now, just call that function with a pointer to an array with 8 bytes in it whenever you need to scan the board. Each byte in the array represents one of the rows and each bit represents a column.

<sub>\[moderator note: This answer appears in this thread as a result of a merge\]</sub>
> 2 votes

# Answer
Use 16 digital i/o pins on the Arduino. The ones connected to a-h should be configured as OUTPUT pins. The ones connected to 1-8 should be configured as INPUT pins. Start with all of the outputs (a-h) low.

You check for a closed switch at the lower left corner by making the output pin connected to 'a' HIGH then look at the value of the input pin connected to '1'. If it's high then that switch is closed. If it's low then that switch is open.

While the 'a' output is HIGH you can check the rest of the left column by looking at inputs '2' through '8'.

I don't see any need for the resistors or shift registers, but maybe your teacher had something in mind.

EDIT: I see that by using the shift registers you need only one INPUT pin and one OUTPUT pin on the Arduino. I'll leave that for you to figure out as I think I've given enough to get you started.
> 1 votes

---
Tags: switch, arduino-duemilanove
---


# Question
Title: Wifi networking with ESP8266 (NODEMCU version)
I am doing some experiments with nodemcu 12 (which has built in esp8266). There most of the tutorials I found by internet describe how to connect to home wifi connection using it.

But when I power on nodemcu, I can see wifi network called "ESPXXX" in my laptop's wifi connection list.

So is there a way to directly connect to the wifi nw of esp8266 by my laptop or via another esp8266 (so I don't have to switch on my home wifi router)?

If it is possible, is there is way to change ssid of esp8266's wifi connection and add password (again this is not about connecting to home wifi and this is about the wifi connection on esp8266 it self)? So we can make one esp8266 as a wifi host and connect other esp8266s as slave to it.

I am using arduino IDE to upload program into esp8266 and not Lua.

Thanks.

# Answer
> 2 votes
Here you are the working code allowing you to choose `SSID`, `password`, `network name` and `IP address` of your ESP8266 acting as an access point. In addition, you can specify `wifi channel` to avoid interference with other devices. A password must be at least 8 characters long or it wouldn't work.

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

IPAddress ip(192,168,1,81);         // choose IP address
IPAddress subnet(255,255,255,0);

ESP8266WebServer server(80);

void handleRoot() {
  String page = "<!DOCTYPE html>\n";

  page += "<html>\n<body>\n<h1>Some heading</h1><br>Generated by ESP8266\n</body>\n</html>";
  server.send(200, "text/html", page);
}

// what to do when accessed through http://ip_address/something_undefined
void handleNotFound(){
  String message = "File not found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void){
  Serial.begin(74880);                      // so you can see debug messages automatically sent by ESP8266
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(ip, ip, subnet);        // declared as: bool softAPConfig (IPAddress local_ip, IPAddress gateway, IPAddress subnet)
  WiFi.softAP("SOME_NAME", "password", 7);  // network name, network password, wifi channel

  IPAddress myIP = WiFi.softAPIP();
  Serial.println();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.on("/", handleRoot);               // what to do when accessed through browser using http://IP_address

  // what to do when accessed through http://ip_address/test
  server.on("/test", [](){
    server.send(200, "text/plain", "This is another page");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started...");
}

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

```

You can write something like:

```
server.on("/open_door", [](){
        // the code to switch on the relay to open the door
        // ... <-- put here the code
        server.send(200, "text/html", "Door: opened");
});

```

so you can open the door with `http://ip_address/open_door`.

You can try `http://ip_address/something_undefined?a=24&b=25` to get an idea how to process the parameters.

---
Tags: arduino-ide, esp8266, nodemcu
---


# Question
Title: Making WiFi hotspot for 3G network sharing controlled by Arduino
I am trying to make a WiFi internet network from 3G using Arduino as access control. I need the Arduino to act as server and control users, consumption, and connection speed. (When users connect to the WiFi, they have to enter a passcode in a webpage to use internet for a limited time, or limited data.)

So is this possible? I still did not try anything because I can not afford to buy many objects and fail to make it work.

I am thinking of using a 3G shield and a WiFi shield, or a router connected to 3G dongle connected to an Arduino via ethernet, or a 3G shield Arduino to ethernet shield to WiFi router.

I don't know if any of these can work, so I really appreciate any guidance.

# Answer
> 4 votes
Not a chance, I am afraid (you were right not to buy things yet). Things like the 3G shield and WiFi shield don't work in the way that is needed for a WiFi hotspot like that. You're better off with a Raspberry Pi and a 3G USB dongle and run `hostapd` along with the other software needed for your project - things like apache, etc.

You may be able to do it with the Linux portion (OpenWRT) of an Arduino Yun with a USB 3G dongle attached, but it would be sluggish. Best to stick to something with enough processing to do what you want, which means a Raspberry Pi or similar.

# Answer
> 0 votes
What you want (on at least an ARM board) is a captive portal, which catches and releases new users if and only if they pass the required challenge. There are numerous software packages for this. If you use a pi, and need to do something with the GPIO pons, have a look at the WiringPi project, which is much nicer than python's silliness. 'Inspired by Monty Python' ... indeed.

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


# Question
Title: I would like to add a RGB led strip to my arduino alarm system
I am new to programming and would be grateful for any helpful answer...Thank you I used a ping sensor, a piezo buzzer and an RGB strip. I used the Schematic from Adafruit Learning System.. Here is my code:

```
#define trigPin 5
#define echoPin 6
#define RED_PIN    10
#define GREEN_PIN   11
#define BLUE_PIN  9
int Buzzer = 3;

void setup() {
    //set pinModes for RGB strip
    pinMode(RED_PIN,OUTPUT);
    pinMode(BLUE_PIN,OUTPUT);
    pinMode(GREEN_PIN,OUTPUT);

    pinMode(Buzzer, OUTPUT);

    //reset lights
    analogWrite(RED_PIN,0);
    analogWrite(BLUE_PIN,0);
    analogWrite(RED_PIN,0);

    delay(5000);
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(Buzzer, OUTPUT);
}

void loop() {
    int duration, distance;
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(1000);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    if (distance >= 80 || distance <= 0){
        Serial.println("No object detected");
        digitalWrite(Buzzer, LOW);
    } else {
        Serial.println("Object Detected");
        tone(Buzzer, 1000); // play 400 Hz tone for 500 ms
        delay(500);
        tone(Buzzer, 10000); // play 800Hz tone for 500ms
        noTone(Buzzer);
    }
    delay(300);
}

```

# Answer
An interesting problem with the Arduino paradigm is that not only do you need basic programming knowledge but you also need basic electronics knowledge.

On the plus side, there are plenty of good tutorials where you can over look these issues if you follow the tutorials step by step. That is, get exactly the same parts and wire them up exactly the same way. Later, if you like, you can go over the tutorial, ask questions here and discover how and why what you did works.

In your diagram:

You are implying you are using ordinary Red, Green & Blue LEDs and are going to vary their brightness using the Arduino's Pulse Width Modulation feature.

Possible problems:

You are powering the LEDs from the 9 volt pin of the Arduino. And the LED strip in the diagram is clearly marked 12 volts. This may work. But is out of specification.

Also, this setup makes the assumption you are powering your Arduino with a 9 volt wall power supply. Are you? You could also power the Arduino with 5 volts using only the USB cable. There would then be no 9 volts available at the 9 volt pin. (I would avoid plugging in both power sources at the same time. I think the Arduino design has changed over time.)

You are using a strip of Red, Green & Blue LEDs. Which implies more than 1 of these Red, Green & Blue LEDs. There is an upper current limit on the outputs of the Arduino. More LEDs means more current. Too many LEDs will damage the Arduino. I would stick to 1 LED until you research the amount of current 1 LED takes verses the upper current limit of an Arduino output pin.
> 1 votes

# Answer
If you are not sure which LED lights you want to use, take a look at this tutorial and use these LED lights

No, I have no connection to this video or its author.
> 0 votes

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


# Question
Title: Where are the chip configurations stored in IDE 1.6.x? How to modify them?
With the new 1.6.x version of the Arduino IDE, obscurity of adding new chips has gained new level. It now seems you have to add HTTP links to some JSON files in single-line edit field in settings.

I did so and to add AtTiny to Arduino IDE, I used this JSON file: https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package\_damellis\_attiny\_index.json

I have AtTiny 13 however. It's same as the others, according to datasheet, but has different signature:

```
avrdude: Expected signature for ATtiny45 is 1E 92 06
         Double check chip, or use -F to override this check.
Wrong microcontroller found.  Did you select the right board from the Tools > Board menu?

```

I tried to search ATTiny45 and the signature over the files - no success.

What I need is to add the ATTiny13 to the list so that I can finally actually do some programming, instead of being completely helpless.

# Answer
This doesn't answer the original question (which was **how and where to modify the board configurations**) but at least solves the immediate problem.

This repository contains working and maintained profiles for Attiny13: https://github.com/MCUdude/MicroCore
> 0 votes

# Answer
You are importing a json file provided by someone for free.
The best thing you can do is contribute by adding ATTiny13 to this repository.
To do so:
So go to github (create a account if you do not have one);
create a fork of the repository.
Add your ATTiny13 board to the boards.txt file.
mod the json file to contain a new version and the attiny13.
Test and if everything works fine
Create a pull request
> 0 votes

---
Tags: arduino-ide, attiny, attiny13
---


title: manual square wave period is off

text:
# Question
Title: manual square wave period is off
I'm generating a square wave with my Arduino UNO using the following:

```
#define pin 10 // data pin to control servo

// pulse width (in microseconds)
int pulsewidth = 2500; // 400 Hz

// wave period in microseconds
int period = 20000; // 50 Hz

void setup() {
  pinMode(pin, OUTPUT);
}

void loop() {

  // turn pulse on for pulsewidth duration
  digitalWrite(pin, HIGH);
  delayMicroseconds(pulsewidth);

  // turn pulse off
  digitalWrite(pin, LOW);
  delayMicroseconds(period - pulsewidth);

}

```

When I check the wave freq on the scope it's reading something like 115Hz instead of 50Hz; however, the pulsewidth is correct (4Hz).

Why is this exactly? Is it because `digitalWrite()` is slow?

# Answer
> Why is this exactly? Is it because digitalWrite() is slow?

There is "hidden" code in the main() function which is calling loop(). Also digitalWrite() is slow compared to what is possible. Last, the millis() ISR is executing in the background.

Try the below:

```
void loop() {

  while (1) {
    // turn pulse on for pulsewidth duration
    digitalWrite(pin, HIGH);
    delayMicroseconds(pulsewidth);

    // turn pulse off
    digitalWrite(pin, LOW);
    delayMicroseconds(period - pulsewidth);
  }
}

```

And then try turning off interrupts.

Cheers!
> 1 votes

# Answer
From Arduino reference on `delayMicroseonds`:

> Currently, the largest value that will produce an accurate delay is 16383. This could change in future Arduino releases. For delays longer than a few thousand microseconds, you should use delay() instead.

Although the reference does not specify further what happens if `delay > 16383`, a look at the actual code explains this (in `wiring.c`):

```
/* Delay for the given number of microseconds.  Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */
void delayMicroseconds(unsigned int us)
{
...
#elif F_CPU >= 16000000L
    // for the 16 MHz clock on most Arduino boards

    // for a one-microsecond delay, simply return.  the overhead
    // of the function call takes 14 (16) cycles, which is 1us
    if (us <= 1) return; //  = 3 cycles, (4 when true)

    // the following loop takes 1/4 of a microsecond (4 cycles)
    // per iteration, so execute it four times for each microsecond of
    // delay requested.
    us <<= 2; // x4 us, = 4 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 19 (21) cycles above, remove 5, (5*4=20)
    // us is at least 8 so we can substract 5
    us -= 5; // = 2 cycles,
...

    // busy wait
    __asm__ __volatile__ (
        "1: sbiw %0,1" "\n\t" // 2 cycles
        "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
    );
    // return = 4 cycles
}

```

The line `us <<= 2;` explains why `us` should not exceed 16383, otherwise the left-shifted value will overflow (`unsigned int` is 16 bits on AVR).

In your situation, `(20000-2500) << 2` will not be `70000` or `0x11170` in hexa (that does not fit into `unsigned int`), hence the result will be truncated to `0x1170` i.e. `4464`, which will make the last part of the function (the busy wait) wait for the wrong duration.

In order to fix it, you have to split your second `delayMicroseconds` in one `delay` in milliseconds plus one `delayMicroseconds`:

```
delay(17);
delayMicroseconds(500);

```
> 4 votes

---
Tags: arduino-uno, pwm, digital
---


title: wire.h multiple slave addresses

text:
# Question
Title: wire.h multiple slave addresses
Is it possible to use wire.h on an Arduino Uno to act as a slave for more than one address? For example I'd like it to emulate two different devices, one at I2C address 23 and the other at address 57.

I'm either looking for a way to do this directly, or to run multiple instances (each would need a different onReceive handler).

# Answer
> 2 votes
> Is it possible to use wire.h on an Arduino Uno to act as a slave for more than one address?

The quick answer is: No!

The ATmega328 2-Wire Serial Interface has a special register for the address match in slave mode. This only allows a single address to be matched.

> 22.5.4 Address Match Unit
>
> The Address Match unit checks if received address bytes match the seven-bit address in the TWI Address Register (TWAR). If the TWI General Call Recognition Enable (TWGCE) bit in the TWAR is written to one, all incoming address bits will also be compared against the General Call address. Upon an address match, the Control Unit is informed, allowing correct action to be taken. The TWI may or may not acknowledge its address, depending on settings in the TWCR. The Address Match unit is able to compare addresses even when the AVR MCU is in sleep mode, enabling the MCU to wake up if addressed by a Master. Reference, pp. 213

On an ATtiny with USI it is actually possible to implement multiple address matching as this is controlled by software.

Last, a pure software approach could be used, i.e. implement the I2C protocol with external interrupt pin and fast pin access. See Amtel Application Note AVR154. The code for this app-note can be found on github. This could be modified to allow multiple slave addresses.

Cheers!

---
Tags: arduino-uno, wire-library
---


# Question
Title: First Serial.print voltage is wrong, way too low. Ruins average calculation
The first Serial.print voltage reading is so far off it really screws up the moving average calculation. For example, the first reading is like 0.00014981, which is wrong. From the second line on it prints the correct voltage, like 0.00475721. I don't know where this first line is coming from. How can I keep that first line from being used in the average calculation? Here are links to the sketch and adc.

https://github.com/Protocentral/ProtoCentral\_ads1262/tree/master/Libraries http://www.ti.com/lit/ds/symlink/ads1262.pdf

For the average calculation I added:

count = count + 1;

volt\_mV = ((count-1)/count)\*volt\_mV + (1/count)\*volt\_V;

# Answer
The code at the link is mediocre – it has dozens of unnecessary casts or declarations, dozens of superfluous statements, and numerous unused or unnecessary variables. Also, the code shown there has nothing about any averages, so evidently does not show whatever code you actually are running. You could revise your question and include the actual sketch within it.

Nevertheless, the code at the link looks like it will take a reading ok. Possibly your modifications, whatever they are, incorrectly initialize variables for the running average calculation, or incorrectly initialize some other variable not shown. Or there may be some hardware glitch that spoils the first reading.

Several fixes are possible. You could discard the first reading. You could discard the first reading of each set of readings. You could take readings in sets of three or five and only keep the median reading. You could take sets of readings and discard the highest and lowest readings. You could apply exponential smoothing or some other form of smoothing to the readings.

Note, the formula you show for averaging – `((count-1)/count)*volt_mV + (1/count)*volt_V` – has a number of problems. First, if `count` is an integer, both of `((count-1)/count)` and `(1/count)` will compute to zero values. Secondly, as `count` becomes large, you will be adding a tiny value to a much larger value, which is ill-conditioned arithmetic. Third, although the formula computes a *running* average, it does not compute a *moving* average. That is, your formula computes the average of all readings taken so far, with all readings equally weighted. A moving average, on the other hand, typically will weight recent readings more heavily than old readings, for example via a window technique or via an exponential smoothing formula like `movingAverage = (15*movingAverage + newReading)/16`.
> 3 votes

# Answer
If it is truly only the first reading that is bogus, you could take one or a few readings during `setup()` whose values you ignore, before your program starts collecting data. Or you could investigate why your first reading is bogus....
> 0 votes

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


title: Getting a reset error on a WEMOS D1

text:
# Question
Title: Getting a reset error on a WEMOS D1
As a learning effort, I am trying some sample code on my WEMOS D1, which is basically an Arduino compatible board with a built-in ESP8266 (Wi-Fi module).

This is the output of my Serial Monitor:

```
1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld
Initializing Wifi...
Start printMacAddress
 ets Jan  8 2013,rst cause:4, boot mode:(1,4)

wdt reset

```

It stops there and I see no more messages. Below is the code I am trying (from https://www.arduino.cc/en/Guide/ArduinoWiFiShield):

```
#include <SPI.h>
#include <WiFi.h>

void setup() {
  // initialize serial and wait for the port to open:
  Serial.begin(115200);
  // attempt to connect using WEP encryption:
  while(!Serial) ;
    Serial.println("Initializing Wifi...");
    printMacAddress();
    // scan for existing networks:
    Serial.println("Scanning available networks...");
    listNetworks();
}

void loop() {
  delay(10000);
  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void printMacAddress() {
  Serial.print("Start printMacAddress");
  // the MAC address of your Wifi shield
  byte mac[6];
  // print your MAC address:
  WiFi.macAddress(mac);
  Serial.print("MAC: ");
  Serial.print(mac[5],HEX);
  Serial.print(":");
  Serial.print(mac[4],HEX);
  Serial.print(":");
  Serial.print(mac[3],HEX);
  Serial.print(":");
  Serial.print(mac[2],HEX);
  Serial.print(":");
  Serial.print(mac[1],HEX);
  Serial.print(":");
  Serial.println(mac[0],HEX);
}

void listNetworks() {
  // scan for nearby networks:
  Serial.println("** Scan Networks **");
  byte numSsid = WiFi.scanNetworks();
  // print the list of networks seen:
  Serial.print("number of available networks:");
  Serial.println(numSsid);
  // print the network number and name for each network found:
  for (int thisNet = 0; thisNet<numSsid; thisNet++) {
    Serial.print(thisNet);
    Serial.print(") ");
    Serial.print(WiFi.SSID(thisNet));
    Serial.print("\tSignal: ");
    Serial.print(WiFi.RSSI(thisNet));
    Serial.print(" dBm");
    Serial.print("\tEncryption: ");
    Serial.println(WiFi.encryptionType(thisNet));
  }
}

```

I am not a hundred percent sure, but I think this started happening when I connected D8 (Digital Pin 8) to a relay. I later read that it has a specific use (to flash firmware I think). The error message appears to point to something called a "WatchDog Timer", but I am not even sure what to eat that with. :-)

There are no error messages in the IDE and it even uploads fine. So why is this happening and how do I fix it?

TIA!

# Answer
If Watchdog timer is the cause of reset that means there is at least one place in your code that runs too long without allowing subsystems to do the background tasks. It **might** be possible the part of your code causing the problem is:

```
while(!Serial) ;

```

Instead that loop use:

```
while(!Serial)
  delay(100);

```

so the background tasks will get the chance to be exectuted during the while loop.

**EDIT:**
In fact you can completely remove that while loop as it is not necessary. There is a possibility `!Serial` is **always** true so the loop never ends. And I suggest you using `74880` instead of `115200` so you can see the debug messages sent automatically by ESP8266.
**END OF EDIT**

However, if that is not the part of the code that causes the problem (and I think it is not) then the problem **might** be `for loop` where you list networks. You can check if that is the problem by adding a small delay inside the loop as follows:

```
for (int thisNet = 0; thisNet<numSsid; thisNet++) {
  delay(1);
  Serial.print(thisNet);
  Serial.print(") ");
  Serial.print(WiFi.SSID(thisNet));
  Serial.print("\tSignal: ");
  Serial.print(WiFi.RSSI(thisNet));
  Serial.print(" dBm");
  Serial.print("\tEncryption: ");
  Serial.println(WiFi.encryptionType(thisNet));
}

```

If the problem will still exist then you can add a few more `delay(1);` statements through the code.

Instead of `delay` you may use `yield();` which is the same as `delay(0);`.
> 1 votes

---
Tags: esp8266, wifi, reset
---


# Question
Title: Connection ESP8266 to ESP8266 Client Server can't Connect, Help me?
I have a project to connecting dual esp8266 using client server method, my expectation the server can get command from user from web request, and the request will be forward to client from server to turn on led. But the connection from server always failed

I'm using ESP-12F and programming using Arduino IDE

the code of server :

```
//--------------------------------------------------------------------------
  #include <ESP8266WiFi.h>
//--------------------------------------------------------------------------
// Membuat Variabel Autentikasi
//--------------------------------------------------------------------------
  const char* ssid = "master-sport";
  const char* password = "1234567890";
//--------------------------------------------------------------------------
// Mengatur IP Address
//--------------------------------------------------------------------------
  IPAddress CLIENTA(192,168,4,100);
//--------------------------------------------------------------------------
// Create an instance of the server
// specify the port to listen on as an argument
//--------------------------------------------------------------------------
  WiFiServer server(80);
  WiFiClient client;
//===========================================================================
  void setup() {
   Serial.begin(115200);
   delay(10);

  // Mengatur WiFi ----------------------------------------------------------
   Serial.println();
   Serial.print("Configuring access point...");

   WiFi.mode(WIFI_AP);
   WiFi.softAP(ssid, password);

  // Start the server -------------------------------------------------------
   server.begin();
   Serial.println("Server dijalankan");

  // Print the IP address ---------------------------------------------------
   Serial.println(WiFi.localIP());
 }

//===========================================================================

  void loop() {
  // Check if a client has connected ----------------------------------------
    client = server.available();
    if (!client) {
    return;
  }

  // Wait until the client sends some data ----------------------------------
   Serial.println("new client");
   while(!client.available()){
     delay(1);
  }

  // Read the first line of the request -------------------------------------
   String req = client.readStringUntil('\r');
   Serial.println(req);
   client.flush();

  // Match the request ------------------------------------------------------
   const char* host;
   int val;
   if (req.indexOf("/sr/0") != -1){
      host = "sa";
      val = 0;
    }
   else if (req.indexOf("/sr/1") != -1){
      host = "sa";
      val = 1;
    }
   else {
     Serial.println("invalid request");
     client.stop();
     return;
    }

   client.flush();
   Serial.println("Client disonnected");

  // Pengiriman data ke client -----------------------------------------------
   int value  = 0;
   delay(5000);
   ++value;

   Serial.print("connecting to ");
   Serial.println(CLIENTA);

  // Memebuat TCP Connection Menggunakan WiFiClient --------------------------
   const int httpPort = 80;
   if (!client.connect(CLIENTA, httpPort)) {
     Serial.println("connection failed");
     return;
   }

  // Membuat URL untuk dikirimkan -------------------------------------------
   String url = host;
   url += "/";
   url += val;

   Serial.print("Requesting URL: ");
   Serial.println(url);

  // Mengirimkan Request ke Client ------------------------------------------
   client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + CLIENTA + "\r\n" +
               "Connection: close\r\n\r\n");
   unsigned long timeout = millis();
   while (client.available() == 0) {
     if (millis() - timeout > 5000) {
       Serial.println(">>> Client Timeout !");
       client.stop();
       return;
    }
  }

  // Melihat semua line balasan dari server dan menampilkan di Serial -------
   while(client.available()){
     String line = client.readStringUntil('\r');
     Serial.print(line);
   }

   Serial.println();
   Serial.println("closing connection");
}
//=============================================================================

```

Client code :

```
//--------------------------------------------------------------------------
  #include <ESP8266WiFi.h>
  #include <Adafruit_NeoPixel.h>
  #ifdef __AVR__
  #include <avr/power.h>
  #endif
  #define PIN 13
//--------------------------------------------------------------------------
// Membuat Variabel Autentikasi
//--------------------------------------------------------------------------
  const char* ssid = "master-sport";
  const char* password = "1234567890";
//--------------------------------------------------------------------------
// Mengatur IP Address
//--------------------------------------------------------------------------
  IPAddress IP(192,168,4,100);
  IPAddress NETMASK(255,255,255,0);
  IPAddress NETWORK(192,168,4,1);
//--------------------------------------------------------------------------
// Create an instance of the server
// specify the port to listen on as an argument
//--------------------------------------------------------------------------
  WiFiServer server(80);
//--------------------------------------------------------------------------
// Menasukan LED RGB
//--------------------------------------------------------------------------
  Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800);
//===========================================================================
  void setup() {
   Serial.begin(115200);
   delay(10);

  // Connect to WiFi network ------------------------------------------------
   Serial.println();
   Serial.println();
   Serial.print("Connecting to ");
   Serial.println(ssid);

  // Mengatur WiFi ----------------------------------------------------------
   WiFi.mode(WIFI_STA);
   WiFi.begin(ssid, password);
   WiFi.config(IP, NETMASK, NETWORK);

   while (WiFi.status() != WL_CONNECTED) {
     delay(500);
     Serial.print(".");
   }
   Serial.println("");
   Serial.println("WiFi connected");

  // Start the server -------------------------------------------------------
   server.begin();
   Serial.println("Server dijalankan");

  // Menjalankan LED RGB ----------------------------------------------------
   strip.begin();
   strip.show();

  // Print the IP address ---------------------------------------------------
   Serial.println(WiFi.localIP());
 }

//===========================================================================

  void loop() {
  // Check if a client has connected ----------------------------------------
    WiFiClient client = server.available();
    if (!client) {
    return;
  }

  // Wait until the client sends some data ----------------------------------
   Serial.println("new client");
   while(!client.available()){
     delay(1);
  }

  // Read the first line of the request -------------------------------------
   String req = client.readStringUntil('\r');
   Serial.println(req);
   client.flush();

  // Match the request ------------------------------------------------------
   int val;
   if (req.indexOf("/sa/0") != -1){
      strip.setPixelColor(4,0x000000); //LED menjadi mati -------------------
      strip.show();
    }
   else if (req.indexOf("/sa/1") != -1){
      strip.setPixelColor(4, 0xFF0000); //LED menjadi merah -----------------
      strip.show();
    }
   else {
     Serial.println("invalid request");
     client.stop();
     return;
    }

   client.flush();
   Serial.println("Client disonnected");
}

//============================================================================

```

whats wrong that code ?

# Answer
You do not need 2 ESPs, one is enough. Here you are the code so you can turn on the NeoPixel using web interface:

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

IPAddress ip(192,168,1,81);         // choose IP address
IPAddress subnet(255,255,255,0);

ESP8266WebServer server(80);

void handleRoot() {
  String page = "<!DOCTYPE html>\n";

  page += "<html>\n<body>\n<h1>Some heading</h1><br>Generated by ESP8266\n</body>\n</html>";
  server.send(200, "text/html", page);
}

// what to do when accessed through http://ip_address/something_undefined
void handleNotFound(){
  String message = "File not found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void){
  Serial.begin(74880);                      // so you can see debug messages automatically sent by ESP8266
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(ip, ip, subnet);        // declared as: bool softAPConfig (IPAddress local_ip, IPAddress gateway, IPAddress subnet)
  WiFi.softAP("SOME_NAME", "password", 7);  // network name, network password, wifi channel

  IPAddress myIP = WiFi.softAPIP();
  Serial.println();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.on("/", handleRoot);               // what to do when accessed through browser using http://IP_address

  // what to do when accessed through http://ip_address/test
  server.on("/test", [](){
    server.send(200, "text/plain", "This is another page");
  });

  server.on("/sa/1", [](){
    // ... <-- put here the code for NeoPixel = on
    server.send(200, "text/html", "NeoPixel is now on");
  });

  server.on("/sa/0", [](){
    // ... <-- put here the code for NeoPixel = off
    server.send(200, "text/html", "NeoPixel is now off");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started...");
}

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

```

Now you can use `xx.xx.xx.xx/sa/1` and `xx.xx.xx.xx/sa/0` (where xx.xx.xx.xx is an IP address you've chosen) to turn on/off the NeoPixel.

Just add the Adafruit library for controlling NeoPixel and copy the NeoPixel setup and the code to turn it on/off from your code #2 to the appropriate places (I marked the place where to put the code to turn the NeoPixel on/off with the comments).

If you really want to add another ESP8266 then you have to set it up as a server using the same code - just change the `network name`, `password` & `IP address` and add sending GET request from your first ESP to the second.
> 1 votes

---
Tags: arduino-ide, esp8266, wifi, communication
---


title: What am I doing wrong with my millis()?

text:
# Question
Title: What am I doing wrong with my millis()?
Im new to Arduino and have been trying to use the millis() function for an assignment of mine. I have had a lot of trouble trying to get the millis() function to work but now it seems to be working properly as far as I can tell through the serial viewer but it wont stop my loop once it goes higher than the run time. Im trying to stop my loop after 10 seconds, but it continues going and I feel like it has something to do with my millis().

```
 // Pin 13 is the LED

 int led = 13;        // pin 13 on the board
 int ledOFF = 8;      //led off time delay
 int ledON = 5;            //led on time delay
 unsigned long Timer = 0;      // store time
 int runtime = 10000;      // run loop for 10s

 void setup() {
   pinMode(led, OUTPUT);

   Serial.begin(9600);
   delay(1000);
 }

 void loop() {
   Timer = millis();
   int state = 0;
   while(millis() - Timer <= runtime){
     Serial.println(Timer);
     if(state==0){
       digitalWrite(led,LOW);
       state = 1;
       delay(ledOFF);
     }
     else{
       digitalWrite(led,HIGH);
       state = 0;
       delay(ledON);
     }
    }
   }

```

# Answer
> 2 votes
as @Andre said on comment, you give variable 'Timer' a new value each loop. One of the solution is putting `Timer = millis();` on the `void setup` instead on `void loop`

# Answer
> 0 votes
You are always re-init Timer as millis on every loop. So millis() - Timer is probably always a few milisecond and never reaches your runtime value.

---
Tags: millis
---


# Question
Title: Arduino Uno and ESP8266 serial monitor issue
I plugged in the Arduino Uno and the ESP8266 following this schema:

When I enter "AT" in the serial monitor, I get an "OK". I can also connect to my wifi using typical ESP8266 commands.

What doesn't work is passing these commands using an Arduino Script. For example, if I use this script, I don't get an "OK" from the ESP8266.

```
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

 void loop() {
  // put your main code here, to run repeatedly:
 Serial.println("AT");
 delay(10000);
   if(Serial.find("OK")){
    Serial.println("OK");
     }
     else{
     Serial.println("NOT OK");
  }
}

```

I tried a bunch of different codes,and nothing works. What am I doing wrong?

# Answer
> 2 votes
What you are doing wrong is:

If sending AT commands from PC to ESP and receiving `OK` ,as you said, works - that means you connected TX output from USB --\> RS232 IC on the board to **both** RX pin of the ATmega328 and RX pin of the ESP8266 - **not as in your picture**. Similarly, you connected RX input of the USB --\> RS232 IC on the board to **both** ATmega328 TX and ESP8266 TX pin of the ESP8266. If communication between PC and ESP works, then you connected TX Arduino pin with TX ESP pin and RX Arduino pin with RX ESP pin and **not** as shown in the picture.

When you send AT command from PC both ATmega328 and ESP8266 are getting the signal from USB --\> RS232 IC in their RX pins. As your firmware in the first 10 seconds doesn't read the RS232 data, ATmega328 just ignores the packets sent by PC but ESP8266 receives the packets and responds with `OK`.

Since you shorted RX on ATmega328 and RX on ESP8266 and you shorted TX on ATmega328 and RX on ESP8266, ATmega328 can **not** send the data to ESP and vice versa so there is no `OK`.

In the other case, **if** you connected ATmega328 TX with ESP8266 RX and ATmega328 RX with ESP8266 TX (**as shown in the picture**) then you would have shorted USB --\> RS232 IC's TX with ESP's TX and you would have shorted USB --\> RS232 IC's RX with ESP's RX.

In that case ATmega328 **might** be able to send `AT` command to both ESP and PC at the same time and ESP would respond but now ESP's TX would be connected to ATmega's RX which is now shorted with USB --\> RS232 IC's TX so PC can't receive that packet. However, when ATmega328 responds with `OK`, the signal now goes from ATmega328 TX to USB --\> RS232 IC's RX (as always) and you might see the response in serial terminal.

So, you can't get the ESP to respond directly to PC **and** to ATmega328 without interchanging the TX/RX wires. Furthermore, as you may know RS232 is designed for communication between **two** devices, not three - and this is the case where three devices (USB --\> RS232 IC, ATmega328 and ESP8266) are connected to the same TX/RX pins at the same time in a rather unusual way. Because, devices are usually connected TX to RX and RX to TX. However, when using the Arduino's onboard USB --\> RS232 converter (by removing the microcontroller or holding it under reset) then you have to connect TX to TX and RX to RX. That is because there is one more TX/RX pair in between PC and the RX/TX pins on the board. The output of the USB --\> RS232 converter (TX) sends the data to RX pin on ATmega328 (and RX pin on the board) but if you want to send the signal further (to some other device), then the pin marked with RX is going to act as TX.

To summarize:

1. The schematics does **not** correspond to what you have written. Such a connection would not allow to send the AT commands from the PC to ESP and to receive response, meaning you connected the TX/RX the other way round.
2. You can not have both at the same time. You have to decide whether you want to send AT commands from the PC or from microcontroller and then connect the wires accordingly.

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


title: Arduino & ESP8266

text:
# Question
Title: Arduino & ESP8266
I connect my ESP to Arduino to my PC.

If I send AT commands from my serial monitor, I receive full response. I use 115200 and both NL & CR in my serial monitor.

ESP TX is connected to TX Arduino, same for RX.

The problem is when I try to send commands from my Arduino code. I don't receive any response. I use same 115200 both for serial and for ESP8266.

I user this code:

```
#include <SoftwareSerial.h>
SoftwareSerial esp8266(0,1);

void setup()
{
    Serial.begin(115200);
    esp8266.begin(115200);
}

void loop()
{
    sendCommand("AT+GMR\r\n");
}

String sendCommand(String command, const int timeout, boolean debug)
{
    String come = "";

    while(esp8266.available())
    {
        char c = esp8266.read(); // read the next character.
        Serial.write(c);
        come += c;
    }
    Serial.println(come);
    return come;
}

```

I can't see what is wrong here and why that works with just the Serial Monitor.

# Answer
When you are using Arduino board just as USB --\> RS232 converter then you have to, as you said, connect TX to TX and RX to RX. But when you want communication between microcontroler and ESP then you have to connect TX to RX and RX to TX. Here I explained that in details.
> 2 votes

# Answer
Make a choice:

1. Are you using pins 0 and 1 for communicating with the PC, or
2. Are you using pins 0 and 1 for communicating with the ESP8266?

**You cannot do both.**

Move the ESP8266 onto some other pins.
> 1 votes

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


# Question
Title: Unable to connect esp8266 12 module with arduino uno
Here is what I am doing

```
Arduino(UNO)--------Esp8266
3.3 v -- vcc
TX      -- RX
RX      -- TX
3.3 v  -- EN(ch_pd)
GND     -- GND

```

there is no blinking of LED on Esp8266, sometimes the LED is on and sometimes it is not. And when I send "AT" command using Serial of Arduino IDE, only RX light of Arduino blinks, TX is not blinking and there is no response of that command. I am having 3.3 voltage on my Vcc pin of Esp8266 but the voltage on the TX and RX pins of Esp8266 is 5 volts, I know that i can reduce this to 3.3 voltage by using a voltage regulator but my question is why there is no blinking on the module even when i have supplied the proper 3.3 voltage and GND? What's the difference between the blinking and a still LED on Esp8266? I have tried every tutorial on internet. No help at all. Right now I am so exhausted that I want to quit.If you can help in solving the problem, I would be very thankful to you sir.

# Answer
> 1 votes
When you are using Arduino board just as USB --\> RS232 converter to send AT commands from PC to ESP8266 you have to connect **TX to TX** and **RX to RX**. But when you want communication between microcontroler and ESP then you have to connect TX to RX and RX to TX. Here I explained that in details.

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


# Question
Title: Questions on how to connect Arduino to Matlab through the serial port
I have an Arduino board with Intel Edison on it. I have tried to read data in Arduino from MatLab through the serial port. I'm sure the Arduino board is working because when I use the serial monitor from Arduino, it shows the data read from the Arduino board. My command is like this in Arduino:

```
   reading = Wire.read();
   Serial.println(reading)

```

I got errors in Matlab when I tried to work with these piece of code:

```
   s=serial('COM4');
   set(s,'BaudRate',9600);
   fopen(s);

```

MatLab complains that "Port: COM4 is not available. No ports are available. Use INSTRFIND to determine if other instrument objects are connected to the requested device." I have tried with "instrfind()" in matlab and got this:

```
   Instrument Object Array

   Index:    Type:     Status:   Name:
   1         serial    closed    Serial-COM4
   2         serial    closed    Serial-COM4
   3         serial    open      Serial-COM4
   4         serial    closed    Serial-COM4
   5         serial    closed    Serial-COM4

```

I still can't get any clue on this. Can anybody help me?

# Answer
I might try to reboot with out the Arduino plugged into the USB port, bring up the device manager and open the COM section and watch which COM becomes available when you do plug in the Arduino's USB cable. Then try connecting to that COM with matlab. Don't use anything else that may connect to that COM port.
> 2 votes

---
Tags: matlab
---


# Question
Title: Most efficient method to turn a gear extremely slowly?
I have a gear that needs to have roughly one rotation per day. It does not have to be smooth or consistent. So far, the best I have come up with is to have a stepper motor with an arduino that sleeps, wakes up once an hour maybe and turns the stepper a little bit.

Which arduino should I use for this and is there perhaps a simpler method? Is there any way to fully cut power then when powered on the arduino advances the motor and then shuts off?

Any ideas?

I want to run off of a 9v battery and get as much time as possible.

edit: adding details as requested

the rotation needs to happen slowly over the 24 hour period. The tube being turned is a light plastic 1" diameter tube that weighs about 2 lbs.

# Answer
Steppers require current - and power, due to I^2\*R losses) to hold a position. Power off, they free-wheel. What kind of efficiency do you need? A stepper might not be the most power efficient.

An escapement permits or causes a gear to index one position and prevents it turning any farther. In a clock, it permits a weight-driven or spring-driven shaft to index. You'll probably want one that drives the shaft as well, probably with a solenoid.

Another option that comes to mind and doesn't need an Arduino, is a clock motor. Gear down the hour hand 2:1 and you're done. Find a 24-hour clock motor and even that gearing will have been done for you.
> 2 votes

# Answer
Turning of the stepper in between, will result in reduced holding torque. This might be a problem.

I'd suggest using a AA battery pack. 4 AA batteries will give you around 5V. The Arduino doesn't require a precise 5V, so you don't need a voltage regulator.

I'd suggest using something like a Arduino Pro Mini, or Arduino Micro, as those don't have USB-to-Serial chips on the board, using up power all the time. Remove the power led, and put the uC to sleep as much as possible.

If you want accurate timing, you'd want to add and RTC module.
> 0 votes

---
Tags: power, stepper
---


# Question
Title: File download from SD card hangs up my ESP-12E
I'm using ESP8266 Arduino for compiling and uploading my code to NodeMCU 1.0 (ESP-12E Module). Flash Size: 4M (3M SPIFFS) CPU frequency: 80 MHz Upload Speed: 115200

I'm using portable arduino-1.6.9-windows extracted in my D: drive. I'm using the latest ESP8266 Arduino image brought by git command.

I've written this basic code to download 'datalog.txt' file (stored in the root of my SD card).

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

const char *ssid = "tiny-esp";
const char *password = "password";

ESP8266WebServer server(80);

String home = "<h1>Hello! from ESP8266!</h1>"
                "<p><a href=\"down\"><button>Download</button></a>";

void handleRoot() {
    server.send(200, "text/html", home);
}

void handleDownload() {

    File dataFile = SD.open("datalog.txt");
    int fsizeDisk = dataFile.size();
    Serial.print("fsizeDisk: ");
    Serial.println(fsizeDisk);

    size_t fsizeSent = server.streamFile(dataFile,"text/plain");

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

    dataFile.close();
}

void setup() {
    delay(500);
    Serial.begin(115200);
    Serial.println();

    WiFi.softAP(ssid, password);

    IPAddress apip = WiFi.softAPIP();
    Serial.print("Please visit: \n");
    Serial.println(apip);

    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
        Serial.println("\nCard failed, or not present");
        // don't do anything more:
        return;
    }
    Serial.println("\nCard Initialized.");

    server.on("/", handleRoot);
    server.on("/down", handleDownload);
    server.begin();
    Serial.println("HTTP server started");
}

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

```

But, when I press the 'Download' button, the ESP hangs, dumps some errors and then restarts as displayed below (from my Serial Monitor):

```
Please visit:
192.168.4.1

Card Initialized.
HTTP server started
fsizeDisk: 28600

Panic D:\arduino-1.6.9-windows\arduino-1.6.9\hardware\esp8266com\esp8266\cores\esp8266\core_esp8266_main.cpp:98 __yield

ctx: sys
sp: 3ffffc80 end: 3fffffb0 offset: 01b0

>>>stack>>>
3ffffe30:  3ffefdf4 000003b9 000003b9 4010020c
3ffffe40:  00000000 3ffe9645 00000001 4020815d
3ffffe50:  3ffefdf4 00000481 3fff0d50 402077e5
3ffffe60:  3fff337c 00000b68 00000000 40207823
3ffffe70:  3fff3a74 3fff1480 3fff3a74 3fff1474
3ffffe80:  3fff337c 00000b68 3fff307c 40202a57
3ffffe90:  3fff3a74 00000b68 3fff2cfc 40202c07
3ffffea0:  00000000 3ffe9704 3fff337c 3fff1474
3ffffeb0:  3fff337c 3fff147c 3fff2cfc 40202d34
3ffffec0:  3ffeead0 0883f900 3fff1478 40202d54
3ffffed0:  3fff337c 3fff147c 3fff1478 4022670d
3ffffee0:  00000000 0104a8c0 00000010 00000000
3ffffef0:  00000000 00000010 3ffefe40 40221001
3fffff00:  40210000 00000000 0000007d 3fff151c
3fffff10:  3ffebae4 3fff1520 3fff3434 40224b39
3fffff20:  3fff1370 3fff1fac 3fff1fac 4021547e
3fffff30:  40215972 3ffed310 3ffebabc 3fff1fac
3fffff40:  3ffebad6 00000000 3fff3434 40223f35
3fffff50:  0204a8c0 3ffee318 02a93dee 00000000
3fffff60:  40104b62 02a93dee 3ffeead0 60000600
3fffff70:  4022d230 3ffeeaa8 3ffeead0 0884220c
3fffff80:  4022d256 3fffdab0 00000000 3fff2004
3fffff90:  3fffdc90 00000000 3fff3434 4022ce8b
3fffffa0:  40000f49 3fffdab0 3fffdab0 40000f49
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v00000000
~ld

Please visit:
192.168.4.1

Card Initialized.
HTTP server started

```

I tried updating the code by writing custom "server.streamFile()" function and adding

```
"Content-Disposition: attachment; filename=\"datalog.txt\"\r\n";

```

to the header to allow downloading the txt file as an attachment.

The modified code is \[Only handleDownload() function has been changed\]:

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

const char *ssid = "tiny-esp";
const char *password = "password";

ESP8266WebServer server(80);

String home = "<h1>Hello! from ESP8266!</h1>"
                "<p><a href=\"down\"><button>Download</button></a>";

void handleRoot() {
    server.send(200, "text/html", home);
}

void handleDownload() {

    int32_t time = millis();
    File dataFile = SD.open("datalog.txt");
    int fsizeDisk = dataFile.size();
    Serial.print("fsizeDisk: "); Serial.println(fsizeDisk);

    String WebString = "";
    WebString += "HTTP/1.1 200 OK\r\n";
    WebString += "Content-Type: text/plain\r\n";
    WebString += "Content-Disposition: attachment; filename=\"datalog.txt\"\r\n";
    WebString += "Content-Length: " + String(fsizeDisk) + "\r\n";
    WebString += "\r\n";
    server.sendContent(WebString);

    char buf[1024];
    int siz = dataFile.size();
    while(siz > 0) {
        size_t len = std::min((int)(sizeof(buf) - 1), siz);
        dataFile.read((uint8_t *)buf, len);
        server.client().write((const char*)buf, len);
        siz -= len;
    }
    Serial.print(siz);
    Serial.println(" Bytes left!");

    dataFile.close();
    time = millis() - time;
    Serial.print(time); Serial.println(" ms elapsed");
}

void setup() {
    delay(500);
    Serial.begin(115200);
    Serial.println();

    WiFi.softAP(ssid, password);

    IPAddress apip = WiFi.softAPIP();
    Serial.print("Please visit: \n");
    Serial.println(apip);

    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
        Serial.println("\nCard failed, or not present");
        // don't do anything more:
        return;
    }
    Serial.println("\nCard Initialized.");

    server.on("/", handleRoot);
    server.on("/down", handleDownload);
    server.begin();
    Serial.println("HTTP server started");
}

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

```

Now, when I press the Download button, a popup opens up in browser displaying "datalog.txt" has started downloading. But after about 20-30 seconds it says "Download failed". The esp freezes after printing the 'fsizeDisk'.

Meanwhile, the serial monitor reads:

```
Please visit:
192.168.4.1

Card Initialized.
HTTP server started
fsizeDisk: 28600

```

I don't understand what am I doing wrong. Please help!

**EDIT:** I added delay(2) and a Serial.println(cnt++) inside *while(siz \> 0)* in handleDownload() for debugging:

```
int cnt=1;
delay(10);
while(siz > 0) {
    delay(2);
    Serial.println(cnt++);
    size_t len = std::min((int)(sizeof(buf) - 1), siz);
    dataFile.read((uint8_t *)buf, len);
    server.client().write((const char*)buf, len);
    siz -= len;
}

```

What happens now is, I get

```
Please visit:
192.168.4.1

Card Initialized.
HTTP server started
fsizeDisk: 28600
1
2
3
4
5
6
7
8

```

The loop may hang up at any count(e.g. 10, 15, 17, 23, etc). Also, in my browser, it reads as 28% downloaded (for cnt=8) or so. So, file starts downloading but hangs up midway. I've tried increasing the delay upto 10 ms, but there has been no progress.

# Answer
try to add a yield() command in to your wihle-loop. With yield() the ESP hast time to do his background jobs.
> 1 votes

---
Tags: esp8266, wifi, sd-card, web-server, http
---


# Question
Title: Why do I get a compiler error when I'm pretty sure I have such method?
## Code

*(I've omitted much of the code, and left just the outline and code probably relating to the error.)*

`SelfDrivingCar.ino`

```
#include "JKMain.h"
void setup() { JKMain::setup(); }
void loop() { JKMain::loop(); }

```

`JKMain.h`

```
#include "JKMotors.h"
class JKMain
{
  static JKMotors motors;
public:
  static void setup();
  static void loop();
};

```

`JKMain.cpp`

```
#include "JKMain.h"
#include "JKPin.h"
const int leftMotorStraightSpeed = 100;
const int rightMotorStraightSpeed = 100;
const int leftMotorTurnSpeed = 150;
const int rightMotorTurnSpeed = 150;
const int turn90Time = 700;
void JKMain::loop() { }
void JKMain::setup()
{
  motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
    JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
    leftMotorStraightSpeed, rightMotorStraightSpeed,
    leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
}

```

`JKMotors.h`

```
class JKMotors
{
private:
  const int leftMotorSpeedPin;
  const int leftMotorDirectionBit1Pin;
  const int leftMotorDirectionBit2Pin;
  const int rightMotorSpeedPin;
  const int rightMotorDirectionBit1Pin;
  const int rightMotorDirectionBit2Pin;
  const int leftMotorStraightSpeed;
  const int rightMotorStraightSpeed;
  const int leftMotorTurnSpeed;
  const int rightMotorTurnSpeed;
  const int turn90Time;
  void setSideDirection(JKDirection _side, JKDirection _direction);
public:
  JKMotors(const int lmsp, const int lmdb1p, const int lmdb2p,
    const int rmsp, const int rmdb1p, const int rmdb2p,
    const int lmss, const int rmss, const int lmts, const int rmts, const int t90t);
};

```

`JKMotors.cpp`

```
#include "JKMotors.h"
#include "Arduino.h"
JKMotors::JKMotors(const int lmsp, const int lmdb1p, const int lmdb2p,
    const int rmsp, const int rmdb1p, const int rmdb2p,
    const int lmss, const int rmss, const int lmts, const int rmts, const int t90t):
      leftMotorSpeedPin(lmsp), leftMotorDirectionBit1Pin(lmdb1p), leftMotorDirectionBit2Pin(lmdb2p),
      rightMotorSpeedPin(rmsp), rightMotorDirectionBit1Pin(rmdb1p), rightMotorDirectionBit2Pin(rmdb2p),
      leftMotorStraightSpeed(lmss), rightMotorStraightSpeed(rmss), leftMotorTurnSpeed(lmts), rightMotorTurnSpeed(rmts), turn90Time(t90t)
{
  pinMode(leftMotorSpeedPin, OUTPUT);
  pinMode(leftMotorDirectionBit1Pin, OUTPUT);
  pinMode(leftMotorDirectionBit2Pin, OUTPUT);
  pinMode(rightMotorSpeedPin, OUTPUT);
  pinMode(rightMotorDirectionBit1Pin, OUTPUT);
  pinMode(rightMotorDirectionBit2Pin, OUTPUT);
}

```

`JKPin.h`

```
#include "Arduino.h"
struct JKPin
{
  // Ultrasonic
  static const int UltrasonicEcho = A4;
  static const int UltrasonicTrig = A5;

  // Servo
  static const int ServoSignal = 10;

  // Motor
  static const int LeftMotorSpeed = 5;
  static const int LeftMotorDirectionBit1 = 7;
  static const int LeftMotorDirectionBit2 = 6;
  static const int RightMotorSpeed = 3;
  static const int RightMotorDirectionBit1 = 8;
  static const int RightMotorDirectionBit2 = 9;
};

```

**Notes**

I wouldn't worry too much about the `SelfDrivingCar.ino` file. I had it "encapsulated" with `JKMain.h`. Also, don't concentrate on `JKPins.h`, as it is mostly "factual" information likely unrelated to the problem.

---

## Error

> sketch/JKMain.cpp: In static member function 'static void JKMain::setup()':
>
> JKMain.cpp:19: error: no match for call to '(JKMotors) (const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&)' leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
>
> exit status 1
>
> no match for call to '(JKMotors) (const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&)'

---

## Request

As far as I see, I do indeed have the constructor that the error claims I lack. **What's wrong with my code?**

---

## Update

*(reply to jantje)*

I when removing `static` from `motors`, I receive a new error:

In file included from sketch/JKMain.cpp:1:0:

> sketch/JKMain.h: In static member function 'static void JKMain::setup()':
>
> JKMain.h:10: error: invalid use of member 'JKMain::motors' in static member function
>
> JKMotors motors;
>
> JKMain.cpp:16: error: from this location
>
> motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
>
> exit status 1
>
> invalid use of member 'JKMain::motors' in static member function

# Answer
The idea to embed both `setup()` and `loop()` with an OOP instance is good, but why not pushing the use of `class JKMotors` and `class JKMain` deeper by removing `static` variables and functions.

**Step1** \- use a `JKMotors *` in a non-static `class JKMain`:

> The default constructor `JKMain()` is just used to initialize `motors`.

```
class JKMain
{
  JKMotors *motors;
public:
    JKMain() { motors = NULL; };
  void setup();
  void loop();
};

```

**Step2** \- create the `motors` instance in the `void JKMain::setup()` as proposed by **@Mikael Patel**

> But now, the `JKMotors *motors;` is accessible from the non-static `void JKMain::setup()`.

```
void JKMain::loop() { }
void JKMain::setup()
{
  motors = new JKMotors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
    JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
    leftMotorStraightSpeed, rightMotorStraightSpeed,
    leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
}

```

**Step3** \- declare a global `JKMain` instance and call `setup/loop` method from static `setup/loop` functions.

> The `JKMotors *motors;` is now accessible from both `JKMain::setup()` and `JKMain::loop()`functions.

```
JKMain glbMain;

void setup() { glbMain.setup(); }
void loop() { glbMain.loop(); }

```
> 2 votes

# Answer
I think the problem is related to the fact motors is declared as a static member which makes it a global variable. This means the constructor can not be in the setup method.
I'm not 100% sure about the format but you need something like

```
#include "JKMain.h"
#include "JKPin.h"
const int leftMotorStraightSpeed = 100;
const int rightMotorStraightSpeed = 100;
const int leftMotorTurnSpeed = 150;
const int rightMotorTurnSpeed = 150;
const int turn90Time = 700;
  JKMain::motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
    JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
    leftMotorStraightSpeed, rightMotorStraightSpeed,
    leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
void JKMain::loop() { }
void JKMain::setup()
{

}

```
> 1 votes

# Answer
> ```
> void JKMain::setup()
>
> {
>   motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
>     JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
>     leftMotorStraightSpeed, rightMotorStraightSpeed,
>     leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
> }
>
> ```

You can't call a constructor like that. A constructor is either implicitly called, eg. if `foo` is a class:

```
foo bar;   // constructor for foo called

```

Or:

```
foo bar (1, 2, 3, 4);  // pass arguments to the constructor

```

Or even as some people do:

```
foo bar = foo (1, 2, 3, 4);

```

The last example creates a temporary instance of foo that is then copied into bar.

But what you **can't** do is this:

```
foo bar;   // make an instance of the class
bar (1, 2, 3, 4);  // call the constructor later

```

It's too late! The instance already exists. In your case `motors` is the instance of the class `JKMotors`. You can't call the constructor later on in the code. It doesn't make sense.
> 1 votes

---
Tags: arduino-uno, programming, c++, arduino-ide, code-review
---


# Question
Title: Need to turn on project twice in order for screen to work!
This problem is really stumping me. I made a simple printed circuit board with an ATtiny85, a 128x64 I2C OLED display, and a Sharp IR analog distance sensor. You can view the circuit here: circuits.io.

If I turn the system on using the simple 3-pin slide switch that I put on the board, the screen does not turn on. I can see that the system is powered though, because I can see a little bit of red light escaping from the IR sensor where some of the IR light borders on the visible end of the spectrum. If I turn the board off then immediately turn it back on, the display powers up just fine. If I upload a new program to the board and use the programmer's 3.3v power I don't need to do it twice - the screen works first time.

I'm using a 3.7v LiPo battery, so I know power is not an issue (everything is 3-5v tolerant, and the LiPo battery can deliver plenty of current). Why do I need to turn it on twice in order for the screen to work? Thanks!

# Answer
> 1 votes
Adding a 100ms delay before calling `oled.init(0x3c); oled.clear(); oled.startScreen();` made this problem go away.

---
Tags: i2c, attiny, display, lipo
---


title: millis() vs creating a "long" variable

text:
# Question
Title: millis() vs creating a "long" variable
I think my issue is not fully understanding how the `millis()` function works;

I am wondering the difference between simply creating a variable such as

```
long fake_millis  ++ ;

```

vs using `millis()`?

# Answer
> 1 votes
`millis()` returns the **ACTUAL** time milliseconds since the start of the program. Wheter you put a delay, you do multiple tasks, `millis()` will still return the right time.

The other method that you mentionned will not work if, for example, you add a delay in the program. Then, for more complex tasks that might take more time, your "custom" counter will be very unacurate.

I short, just use `millis()`. It is easy to use and works great.

P.S. Use an `unsigned long` instead of a `long`.

---
Tags: arduino-ide, millis
---


title: ESP8266 Upload hex file Arduino IDE

text:
# Question
Title: ESP8266 Upload hex file Arduino IDE
I am using ESP12E Wifi module, using library based on Arduino. Is there any way I can upload hex file of the project to esp8266 using Arduino or any tool? I need to send hex file instead of code to my client. Is there any way?

# Answer
I see the main question you are asking is: "I need to send a hex file instead of code to my client. I want to keep my source code with me."

The mechanics of the final hardware solution aren't supplied but I will guess that your client is also using an Arduino or at least the same Atmel chip that you have in your Arduino, and will be using that chip to control the ESP8266.

When you build your sketch, there is a .hex file created that you can send to your client.

There are a few ways to keep the hex file around, and IDE 1.6.5 and up has a way to easily find this file:

Sketch \> Export Compiled Binary The sketch will compile.

Sketch \> Show Sketch Folder The .hex file will be in the sketch folder.

You can send this hex file to your customer.

If he is using an Arduino or ATMega-based solution to connect to the ESP8266, then the hex file can be loaded into his Arduino or to his Atmel chip. However, the Arduino IDE doesn't support *import* of hex files at this time.

Your client would have to load that hex file onto the Arduino with an ISP programmer of some sort. There are many ways to do this, and the best one for you will depend upon your circumstances and your client's skill set.

If the client is using an Arduino or has just embedded the same ATmel chip that is in your Arduino into his solution, you could also just program your Arduino, and then send him that chip.
> 2 votes

# Answer
Turn on `Show verbose output during compilation` in your Arduino IDE and press `Verify`. After compile you can examine the parameters sent to `esptool.exe` in the last line before `Sketch uses...`. You will see some `.elf`, `.bin` and `.text` files. These are the files you want to send.
> 1 votes

---
Tags: arduino-ide, esp8266
---


# Question
Title: Implementing interrupts and timers on an Arduino Uno board
I am trying to implement interrupts on an Arduino Uno board. My goal is to synthesize waves and play them via a 3.5 mm jack. This is what I have so far, based on some code I was provided. I have stripped it down to a somewhat barebones version in order to isolate what is wrong. I have the audio jack plugged in to pin 9, which is what I was told is the PWM pin for this board. However, nothing plays out of the audio jack at all. I would really appreciate any advice or help! :)

```
#include "avr/pgmspace.h"
#define NUM_OSC 1    // number of oscillators
#define MAXVOL 255   // maximum volume of each oscillator

const byte sine256[256] PROGMEM = {
  128,131,134,137,140,143,146,149,152,156,159,162,165,168,171,174,
  176,179,182,185,188,191,193,196,199,201,204,206,209,211,213,216,
  218,220,222,224,226,228,230,232,234,236,237,239,240,242,243,245,
  246,247,248,249,250,251,252,252,253,254,254,255,255,255,255,255,
  255,255,255,255,255,255,254,254,253,252,252,251,250,249,248,247,
  246,245,243,242,240,239,237,236,234,232,230,228,226,224,222,220,
  218,216,213,211,209,206,204,201,199,196,193,191,188,185,182,179,
  176,174,171,168,165,162,159,156,152,149,146,143,140,137,134,131,
  128,124,121,118,115,112,109,106,103,99, 96, 93, 90, 87, 84, 81,
  79, 76, 73, 70, 67, 64, 62, 59, 56, 54, 51, 49, 46, 44, 42, 39,
  37, 35, 33, 31, 29, 27, 25, 23, 21, 19, 18, 16, 15, 13, 12, 10,
  9,  8,  7,  6,  5,  4,  3,  3,  2,  1,  1,  0,  0,  0,  0,  0,
  0,  0,  0,  0,  0,  0,  1,  1,  2,  3,  3,  4,  5,  6,  7,  8,
  9,  10, 12, 13, 15, 16, 18, 19, 21, 23, 25, 27, 29, 31, 33, 35,
  37, 39, 42, 44, 46, 49, 51, 54, 56, 59, 62, 64, 67, 70, 73, 76,
  79, 81, 84, 87, 90, 93, 96, 99, 103,106,109,112,115,118,121,124
  };

const byte square256[256] PROGMEM = {
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255
  };

const byte* const wave_table[] = {sine256, square256, triangle256, sawtooth256};

// information about the current state of a single oscillator
struct OscillatorState
{
   unsigned int phaseStep;  // frequency of this oscillator
   unsigned int volume;     // volume multiplier for this oscillator
   unsigned int phaseAccu;  // accumulator that steps through this oscillator
                            // high byte = current sample index
   const byte* waveform;    // which waveform
};

volatile OscillatorState oscillators;
volatile byte valOut;

//********* interrupt routines ******

// set up timer 1 to do phase correct PCM at a nominal frequency of 31372.549
void setupTimer()
{
// Timer1 Clock Prescaler to : 1, set WGM22 to zero, and WGM12,13 for phase     correct PCM
  TCCR1B = (TCCR1B & 0b11100000) | 0b00001;

// set it to clear compare match mode on both pins, and phase correct PCM     (WGM21 and WGM20)
  TCCR1A = (TCCR1A &0b00001100)| 0b10100001;

// set overflow interrupts enabled for timer 1
  TIMSK1 |= (1<<TOIE1);

  Serial.println("hello");
}

// each timer 1 overflow, set the next sample value for the PWMs
ISR(TIMER1_OVF_vect)
{

  oscillators.phaseAccu += oscillators.phaseStep;
  valOut = highByte(pgm_read_byte(oscillators.waveform +     highByte(oscillators.phaseAccu)) * oscillators.volume);

  OCR1A = valOut; // replaced ... = valOut[0];  // write to pin 9
}

unsigned int hzToPhaseStep(float frequency)
{
  float phaseStep = frequency * 2.0886902978652881446683197032183;    // (pow(2,16) * frequency) / 31376.6
  return (unsigned int)phaseStep;
}

void setup()
{
  delay(1000);
  Serial.begin(9600);
  OCR1A = 0;
  oscillators.waveform = wave_table[2];
  oscillators.phaseAccu = 0;
  setupTimer();
  oscillators.volume = 200;
  oscillators.phaseStep = hzToPhaseStep(440.00);
}

void loop()
{

}

```

# Answer
> I have the audio jack plugged in to pin 9 ... However, nothing plays out of the audio jack at all.

As you are relying on the timer changing the pin you need to make pin 9 output in `setup`:

```
 pinMode (9, OUTPUT);

```

When I did that I heard stuff - I wouldn't exactly call it pretty but I heard stuff.
> 3 votes

---
Tags: arduino-uno
---