title: Help! My motors are not working!

text:
# Question
Title: Help! My motors are not working!
I have made a project using Arduino, 3 LDRs and a L293D motor driver shield. My project was that when I block light from the first LDR, the motor will spin. When I block light from the second LDR, the motor will spin in opposite direction, and when I will block light from the third one, it will stop. The code had no errors and I expected it to work... But no luck. When I blocked light from the first or second LDR, the motor only made a faint "*zing-zing*" type of sound. Why is this happening? Is this a power problem? But I have connected 2 9v batteries to the shield and the Arduino. Please help! Here is the code I used-

```
#include (AFMotor.h)

const int LDR1 = A0;
const int LDR2 = A1;
const int LDR3 = A2;
const int LightIntensity = 150;
int SensorReading1 = 0;
int SensorReading2 = 0;
int SensorReading3 = 0;
AF_DCMotor motor(1);

void setup(void)
{
  pinMode(LDR1, INPUT);
  pinMode(LDR2, INPUT);
  pinMode(LDR3, INPUT);
  motor.setSpeed(255);
}

void loop()
{
  SensorReading1 = analogRead(LDR1);
  SensorReading2 = analogRead(LDR2);
  SensorReading3 = analogRead(LDR3);

  if (SensorReading1 < LightIntensity)
  {
    motor.run(FORWARD);
  }

  if (SensorReading2 < LightIntensity)
  {
    motor.run(BACKWARD);
  }

   if (SensorReading3 < LightIntensity)
  {
    motor.run(RELEASE);
  }
}

```

# Answer
You have not said what you motor is and that normally has a big bearing on the answer, but I think your problem is you need more power.

A 9V battery doesn't actually give you much current, you would be better off with a 'wall wart' aka a mobile phone charger. The higher the amps the better normally, particularly with motors. Try and find one that can put out 5Volts at 1Amp (assuming you have a 5V motor).

Also make more use of Serial.println() to show you what your program is doing. If you had debug statements in the LDR if statements then you would know the switches are working.
> 1 votes

---
Tags: sensors, motor, shields, sketch
---


title: On start servos rotates to 180 degree

text:
# Question
Title: On start servos rotates to 180 degree
I'm testing a servo using varspeedservo.h and it rotates to 180 degree on start and then rotates back to programmed position. Here is the code:

```
#include <AFMotor.h>
#include <VarSpeedServo.h>
VarSpeedServo myServo;

void setup()
{
  myServo.attach(10);
}
void loop()
{
  myServo.slowmove(0, 30);
  delay(5000);
}

```

# Answer
You will need to open up the VarSpeedServo library source code and read through it to understand how the library actually works with your sketch.

Consider that you have not setup an initial position before issuing your first "slow moving" command. It may be by setting an initial position before assigning a pin to the servo, you may prevent any unexpected movement.

Try something (for your code) like "myServo.wirte(0,0)" where the first argument is the position and second is the speed.
> 1 votes

---
Tags: arduino-uno, arduino-mega, servo, speed
---


# Question
Title: No Information obtained when using 2 x SoftwareSerial ports on Arduino Nano
I have a LoRa Click Module and Adafruit Ultimate GPS which both use Serial Communication.

I wish to just check the initial tests with all the components in on the Serial Console. Hence I have declared :

* `SoftwareSerial GPSSerial(10,11);`
* `SoftwareSerial LoRaSerial(5,6);`

Apparently when I declare them and upload the code on the board I do not obtain any information.

### observations

1. However when I comment out the `LoRaSerial` declaration I obtain the GPS coordinates.
2. When I set the `SoftwareSerial LoRaSerial(10,11)` I retrieve the information.
3. I thought `5,6` pins won't be the right choice and hence went on the set `SoftwareSerial(8,9)` but I retreive no information.

### inference

Nano cannot take into consideration more than 1 SoftwareSerial Component. However the Official Documentation states that all Digital pins can be used for Software Serial.

Is it too much for a Nano to have overall **3** Serial ports (including `Serial` itself)?

### sketch

```
#include <SoftwareSerial.h>
#include <TheThingsNetwork.h>

SoftwareSerial GPSSerial(10, 11); //RX , TX
SoftwareSerial LoRaSerial(8,9); // RX, TX (tried with 5,6 too)
#define freqPlan TTN_FP_EU868

 TheThingsNetwork ttn(LoRaSerial, Serial, freqPlan);
void setup() {
  Serial.begin(115200);
  GPSSerial.begin(9600);
  LoRaSerial.begin(57600);
}
void loop() {
  delay(2000);
  while (GPSSerial.available()) {
    char c = GPSSerial.read();
    Serial.write(c);
  }
  delay(2000);
  while (LoRaSerial.available()) {
    ttn.showStatus();
  }
  delay(2000);
}

```

# Answer
You cannot use two SoftwareSerial instances at the same time - or not for receiving anyway.

SoftwareSerial is a "last resort" system - only to be used if there is absolutely no other option. And then you need to be aware of certain information and rules:

* Only one device can *listen* at any time, switchable using the `SoftwareSerial::listen()` method
* When a byte is being received nothing else can happen - it takes over the entire CPU for the duration of reception
* When a byte is being transmitted nothing else can happen - it takes over the entire CPU for the duration of transmission
* There is a minimum required time between successive bytes when receiving that causes problems at higher baud rates

These limitations mean that, when using multiple devices, you have to know before hand which device will be sending you data so you can be ready to receive it. It also means that SoftwareSerial is effectively half duplex - it only really works properly when you are either only receiving, only transmitting, or using a "call-response" scenario like sending "AT" commands and looking for a response afterwards.

So the general recommendation is: use hardware UARTs whenever possible (and if you don't have enough, then consider using a different, more suitable, board with multiple UARTs), and if you *must* use SoftwareSerial then limit yourself to only *one* instance of it.

As a last resort you can always use multiple boards and connect them using a different system, such as I2C.
> 2 votes

# Answer
Sometimes, with some devices, SoftwareSerial can struggle at higher baud rates, there are quite a few posts on here about it. Would it be possible to set the LoRaSerial to 9600 too?

Can you try just the LoRaSerial on its own?

Do you have a second device, could you wire the SoftwareSerials on you Nano to two Software Serial ports on your second device and then squirt anything it receives to the hardware serial port (and then to the console). Then send some test messages from the Nano and see if the device picks them up?

ESP8266 have 2 and a half serial ports (Serial1 is Tx only), but unless you were going to hook the ESP to the Nano via I2C or use the ESP instead of the Nano, that's probably not going to help you in the case.
> 0 votes

---
Tags: arduino-nano, softwareserial
---


title: Breaking up for loop with ISR

text:
# Question
Title: Breaking up for loop with ISR
I am curious if the following scenario is possible.

```
EICRB |= (0<<ISC60)|(0<<ISC61);
EIMSK |= (1<<INT6);

ISR(INT6_vect) {
  myISR();
}

void myISR() {
     digitalWrite(led_off, OFF);
     // Please break my main for loop :)
}

void loop()
{
      for (i=100; i>=0; i--)
             {

            /* STOP button */
              if (read_switch() == 1) {
                      break;
               }
           .. delays and other logic ...
}

```

As you see the following code is not complete but quite understandable. I have a heating process done in the main program, each loop temp adjustments, printing, delay etc takes about 2-3 seconds to complete. When somebody pushes a switch read\_switch will return 1 and that breaks up this function ending the heating process. This works just fine except the user have to hold the button for the time it finishes looping and get to this point again. I have fortunately realized that the switch pin (Arduino promicro pin7) also an interrupt pin so I could do interrupt in real time, as I doing it in other code already.

However what you can do in this ISR routine is limited (eg you cannot print to serial etc). I could setup a global volatile bool variable here of course which would immediately get flipped as the interrupt triggered but it would not solve anything since in the main loop I would have to wait for the next round again.

So is it possible with some hack to tell the ISR to break that for loop (not the whole program with an exit(0)) and continue execution afterwards?

# Answer
> 2 votes
No, it's not possible, nor desirable. It's complicated and unnecessary.

What you have to do is:

1. Declare a **volatile** global variable (a switch).
2. Inside ISR, change that switch to signal that a break is needed.
3. Inside your loop (for, while, ...) test for that global variable and proceed.

This example print "This is the end" each time a button connected to pin 2 is pressed.

```
volatile bool fin = false; // The switch for ISR-loop communication.

void setup()
{
    Serial.begin(9600);
    pinMode(2, INPUT);  // Read a button or other signal.
    attachInterrupt(0, buttonISR, RISING);
}

void loop()
{
    if(fin) {
        Serial.println("This is the end");
        fin = false; // Reset the switch.
    }
}

void buttonISR()
{
    fin = true;  // Just raise the signal for the main loop.
}

```

This method keeps ISR ultra-short and there is no mixing between ISR's instructions and loop's instructions. All of your logic reside in the main loop.

# Answer
> 0 votes
Turn the loop into a state machine instead.

Wrap the entire loop body in a switch.

Every time you have a `delay(t);` make it a target for a case label and replace it with

```
startTimeout = millis();
currentState = N;
case N: if(millis() - startTimeout < t) return;

```

Every `for(init; condition; inc)` loop that has delays inside them can be replaced with

```
<init>
state = N;
case N: if(!condition) state = N1;
<body>
<inc>
state = N;
return; //return from loop() and let it restart
case N1;

```

Then any delay inside body can be adjusted like above.

Make sure that every state case is unique and make any state that needs to persist across states global.

# Answer
> 0 votes
Fairly easy to do. In your heater code, tests the state of the switch periodically and exits if the right state is detected.

As to how periodically you should test, it will depend on your requirement for response time.

---
Tags: arduino-nano, interrupt, code-optimization
---


# Question
Title: Serial.read(): Value changes to ASCII when I input from Serial Monitor
I was having some problems on a project, so to test my Arduino, I wrote the following program to check things. When I start the serial monitor, the value of `i` is 1, but after I start sending numbers, they change into ASCII. Why?

```
int i = 1;
void setup(){
  Serial.begin(9600);
}
void loop(){
  Serial.println(i);
  if(Serial.available()){
    i = Serial.read();
  }
}

```

# Answer
When you send the character `1`, `Serial.read()` returns the integer 49.
`Serial.println(i)` then sends the characters `4`, `9`, carriage return and a newline.

If you want to get back the same characters that you sent, change the type of `i` to `char`.
> 5 votes

---
Tags: serial
---


# Question
Title: Arduino <<I2C>> ATtiny85 stops updating variables after a while
I've been working on a project for the last few days and spent a LOT of time googling, reading and testing. I'm kinda running out of ideas now and instead of bumping my head to the wall I thought posting my issue here in the hopes someone might be able to point me towards the right direction

I've got an Arduino UNO programmed as I2C Master and an ATtiny85 as an I2C slave. An single Adafruit Neopixel LED is attached to the slave.

When running the two sketches below everything actually works perfect.....for about a minute or so. While during correct operations the Neopixel LED is actually changing color correctly and the serial monitor on the Uno shows the correctly updated R-G-B values, things change after about 1 minute of running. The LED keeps blinking, which tells me the ATtiny is not frozen. The UNO keeps sending I2C and is receiving I2C data...but the data is constant. The updated RGB that the Uno (master) has been sending to the ATtiny slave are somehow not handled (correctly) by the slave.

Any thoughts are more then appreciated. I'm totally lost and do not know which directions to go from here so any pointers would be more then welcome.

The Master - Arduino Uno -

```
#include <Wire.h>

#define I2C_MASTER_ADDR 0x04
#define I2C_SLAVE_ADDR 0x05

/*
* Software config
*/
int pollInterval = 700;//Milliseconds

//Demo's
#define demoLedInterval 150//In milliseconds
boolean demoRequest = false;

/*
* Internal variables
*/
unsigned long lastPoll = 0;

int demoLedState = 0;
unsigned long lastDemoLedUpdate = 0;

/*
* Setup function
*/
void setup()
{
 Wire.begin(I2C_MASTER_ADDR);  // join i2c bus (address optional for master)
 Serial.begin(115200);         // start serial for output
 Serial.println("Setup complete");
}

/*
* The main loop
*/
int i =0;
void loop()
{

 /*
  * Poll the slave
  */
 if( (millis()-lastPoll) > pollInterval)
 {
   /*
    *
    */
   int red=0; int green=0; int blue=0;

     if(i==0)
     {
       Serial.println("Write data to slave - set led red");
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC2);//Command
       Wire.write(0x00);
       Wire.write(255);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC3);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC4);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
     }
     if(i==1)
     {
       Serial.println("Write data to slave - set led green");
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC2);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC3);//Command
       Wire.write(0x00);
       Wire.write(255);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC4);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
     }
     if(i==2)
     {
       Serial.println("Write data to slave - set led blue");
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC2);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC3);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC4);//Command
       Wire.write(0x00);
       Wire.write(255);//Data
       Wire.endTransmission();
     }

   i++; if(i>2) i =0;

   /*
    * General request (without data). Should return something though
    */
   Serial.println("General request for slave");
   Wire.requestFrom(I2C_SLAVE_ADDR, 7);//Request N bytes, N=byte_len
   delay(10);//Give the slave time to answer
   while (Wire.available())
   {
     uint8_t next_byte = Wire.read();
     Serial.print(next_byte);Serial.print(" ");
   }
   Serial.println("\n");

   lastPoll = millis();
 }//End if time to poll again

}//End loop

```

The Slave code - ATtiny 85 - Main file

```
#include <EEPROM.h>
#include <OneWire.h>
#include <TinyWireS.h>
#include <Bounce2.h>
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__ //Which will be true for ATtiny85
  #include <avr/power.h>
#endif

#define I2C_SLAVE_DEFAULT_ADDR 0x05

#include "namespaces.h"//Include at last to make sure all libs are present

//Software config
#define BUTTON_DEBOUNCE 5//Debounce milliseconds

//Hardware config
#define NEOPIXEL_PIN  1
#define BUTTON_PIN    3
#define DS2401_PIN    4

#define NUMPIXELS     1

/*
 * Initialize instances/classes
 */
Bounce button = Bounce();
Adafruit_NeoPixel neopixel = Adafruit_NeoPixel(NUMPIXELS, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800);
OneWire ds(DS2401_PIN);

void setup()
{
  uint32_t _now = millis();

  //Start I2C
  uint8_t _device_addr = EEPROM_DATA::get_device_addr();
  //TinyWireS.begin(_device_id);
  TinyWireS.begin(I2C_SLAVE_DEFAULT_ADDR);
  TinyWireS.onReceive(I2C::receiveEvent);
  TinyWireS.onRequest(I2C::requestEvent);

  //Start NeoPixel
  neopixel.begin();
  neopixel.setPixelColor(NUMPIXELS-1, neopixel.Color(255, 255, 255) );
  neopixel.show();

  //Start Button
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  button.attach(BUTTON_PIN);
  button.interval(BUTTON_DEBOUNCE);

}

unsigned long lastBlink = 0;
boolean lastBlinkState;

void loop()
{

  button.update();

  if(VARS::led_needs_update)
  {
    led_update();
    VARS::led_needs_update = false;
  }

  if(button.fell())
  {
    VARS::button_state = HIGH;
  }
  if(button.rose())
  {
    VARS::button_state = LOW;
  }

  //testblink
  if ( (millis()-lastBlink) > 600)
  {
    if(lastBlinkState)
    {
      neopixel.setPixelColor(NUMPIXELS-1, 0,0,0 );
      neopixel.show();
      lastBlinkState = false;
    }
    else
    {
      led_update();
      lastBlinkState = true;
    }
    lastBlink = millis();
  }

  // This needs to be here for the TinyWireS lib
  TinyWireS_stop_check();
}

/*
 * Helper functions
 */
void led_update()
{
  neopixel.setPixelColor(NUMPIXELS-1,
    VARS::led_red,
    VARS::led_green,
    VARS::led_blue
  );
  neopixel.show();
}

```

The Slave code - ATtiny 85 - namespaces.h

```
namespace VARS
{
  //These are available in a I2C response
  volatile boolean button_state = 0;
  volatile int led_red = 0;
  volatile int led_green = 0;
  volatile int led_blue = 0;
  uint8_t sn_family;
  uint8_t sn_bit1;
  //uint64_t serial_number = 0;
  //int I2C_response_max_length = 4;//Count the above

  //These are internal
  volatile boolean led_needs_update = false;
  int update_interval     = 300;
  unsigned long last_update = 0;
}

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

namespace EEPROM_DATA
{
  uint8_t default_device_addr   =     I2C_SLAVE_DEFAULT_ADDR;
  uint8_t this_device_address   =     0x05;

  bool device_addr_valid(uint8_t addr)
  {
    return (addr > 0x04 && addr < 0x7E);
  }
  bool store_device_addr(uint8_t new_device_addr)
  {
    if (!device_addr_valid(new_device_addr)) return false;//cancel if out of bounds. Assume corrupt data.
    EEPROM.write(EEPROM_DATA::this_device_address, new_device_addr);//Set new i2c address into EEPROM
    return true;
  }
  uint8_t get_device_addr()
  {
    uint8_t _addr = EEPROM.read(EEPROM_DATA::this_device_address);
    if (!device_addr_valid(_addr))
    {
      _addr = EEPROM_DATA::default_device_addr;
      store_device_addr(_addr); //update EEPROM with a valid/default device id.
    }
    return _addr;
  }
}

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

namespace COMMANDS
{
  enum {
    assign_new_device_addr  =     0xC1,
    set_led_red             =     0xC2,
    set_led_green           =     0xC3,
    set_led_blue            =     0xC4
  };
  bool do_command(uint8_t cmd, uint16_t cmd_data)
  {
    //interpret command.
    switch (cmd)
    {
      //set new i2c slave adress.
      //ATTENTION: After command is performed, the chip will need a hard reset.
      case COMMANDS::assign_new_device_addr:
        uint8_t new_device_addr;
        new_device_addr = uint8_t(cmd_data & 0x007F);//ensure the address is 7-bit.
        return EEPROM_DATA::store_device_addr(new_device_addr);//return true if saved, false if invalid address.
        break;

      case COMMANDS::set_led_red:
        //if (cmd_data > 0x00FF) break;//ignore out of range data. Assume corrupt packet.
        VARS::led_red = int(cmd_data);
        VARS::led_needs_update = true;
        break;

      case COMMANDS::set_led_green:
        //if (cmd_data > 0x00FF) break;//ignore out of range data. Assume corrupt packet.
        VARS::led_green = int(cmd_data);
        VARS::led_needs_update = true;
        break;

      case COMMANDS::set_led_blue:
        //if (cmd_data > 0x00FF) break;//ignore out of range data. Assume corrupt packet.
        VARS::led_blue = int(cmd_data);
        VARS::led_needs_update = true;
        break;
    }
  }
}

//===========================================================================
int pointer = 0;
namespace I2C{

  //Gets called when the ATtiny receives a general i2c data request.
  //Tx_stop is sent after end of call, so all bytes need to be sent before leaving.
  void requestEvent()
  {

//The number of bytes requested should NOT exceed the number of bytes returned
    TinyWireS.send( VARS::button_state );
    TinyWireS.send( VARS::led_red );
    TinyWireS.send( VARS::led_green );
    TinyWireS.send( VARS::led_blue );

  }

  //Gets called when the ATtiny recieves an i2c message THAT CONTAINS DATA from another device.
  void receiveEvent(uint8_t byte_count)
  {
    //first byte is command, next 2 bytes is data for command. Total must equal 3 bytes.
    if (!TinyWireS.available() || byte_count != 3 ) return;

    //retrieve the command and 16-bit data.
    //Incomming data is ordered CMD,Data-MSB,Data-LSB.
    uint8_t cmd = TinyWireS.receive();
    uint16_t cmd_data = (TinyWireS.receive() << 8);
    cmd_data += TinyWireS.receive();

    COMMANDS::do_command(cmd, cmd_data);
  }

}

```

# Answer
> 0 votes
After diving into interrupts, timing etc I did found the solution. Thanks for all the suggestions, in particular to @Jot!

In the end I took the following steps:
\- adding a 1ms delay after each Wire.endTransmission()
\- dropped the Neopixel lib (https://github.com/cpldcpu/light\_ws2812)

Below is the final code, for anyone interested. There is still an issue with this code: requesting multiple bytes from the slave always results in receiving just a single byte. But since that's most likely unrelated to the original question I'm opening a new topic for that (if I really can't find a solution myself, that is).

Master

```
/*
 *
 */

#include <Wire.h>

#define I2C_MASTER_ADDR 0x04
#define I2C_SLAVE_ADDR 0x05

/*
 * Software config
 */
int pollInterval = 700;//Milliseconds

/*
 * Internal variables
 */
unsigned long lastPoll = 0;

/*
 * Setup function
 */
void setup()
{
  Wire.begin(I2C_MASTER_ADDR);  // join i2c bus (address optional for master)
  Serial.begin(115200);         // start serial for output
  Serial.println("Setup complete");
}

/*
 * The main loop
 */
int i = 0;
void loop()
{

  /*
   *
   */
  if( (millis()-lastPoll) > pollInterval)
  {
    Serial.println("Write data to slave");
    Wire.beginTransmission(I2C_SLAVE_ADDR);
    Wire.write(0x01);//Register to start at
    switch(i)
    {
      case 0:
        Wire.write(255);
        Wire.write(0);
        Wire.write(0);
        i++;
        break;
      case 1:
        Wire.write(0);
        Wire.write(255);
        Wire.write(0);
        i++;
        break;
      case 2:
        Wire.write(0);
        Wire.write(0);
        Wire.write(255);
        i = 0;
        break;
    }
    Wire.endTransmission();
    delay(1);//Dont let the slave panic

    //Set the register pointer back to 0x01
    Wire.beginTransmission(I2C_SLAVE_ADDR);
    Wire.write(0x00);//Register to start at
    Wire.endTransmission();
    delay(1);//Dont let the slave panic

    //Get values from the three registers up form 0x01
    Wire.requestFrom(I2C_SLAVE_ADDR, 6);//Request N bytes
    while (Wire.available())
    {
      uint8_t next_byte = Wire.read();
      Serial.print(next_byte);Serial.print(" ");
    }
    Serial.println("\n");

    lastPoll = millis();
  }//End if time to poll again

}//End loop

```

Slave

```
#include <EEPROM.h>
#include <OneWire.h>
#include <TinyWireS.h>
#include <Bounce2.h>
#include <WS2812.h>
#ifdef __AVR__ //Which will be true for ATtiny85
  #include <avr/power.h>
#endif

//Software config
#define I2C_SLAVE_DEFAULT_ADDR 0x05
#define BUTTON_DEBOUNCE 5//Debounce milliseconds

//Hardware config
#define NEOPIXEL_PIN  1
#define BUTTON_PIN    3
#define DS2401_PIN    4

#define NUMPIXELS     1

/*
 * I2C Registers
 *
 * Register map:
 * 0x00 - Button state
 * 0x01 - led value red
 * 0x02 - led value green
 * 0x03 - led value blue
 * 0x04 - SerialNumber - Family (byte 0)
 * 0x05 - SerialNumber - Byte 1
 * 0x06 - SerialNumber - Byte 2
 * 0x07 - SerialNumber - Byte 3
 * 0x08 - SerialNumber - Byte 4
 * 0x09 - SerialNumber - Byte 5
 * 0x10 - SerialNumber - Byte 6
 * 0x11 - SerialNumber - CNC (byte 7)
 *
 * Total size: 12
 */
const byte reg_size = 12;
volatile uint16_t i2c_regs[reg_size];

/*
 * Internal variables
 */
cRGB value;
volatile boolean led_needs_update = false;
volatile byte reg_position;

/*
 * Initialize instances/classes
 */
Bounce button = Bounce();
WS2812 led(NUMPIXELS);

void setup()
{
  //Start I2C
  //uint8_t _device_addr = EEPROM_DATA::get_device_addr();
  TinyWireS.begin(I2C_SLAVE_DEFAULT_ADDR);
  TinyWireS.onReceive(i2cReceiveEvent);
  TinyWireS.onRequest(i2cRequestEvent);

  //Start Led
  led.setOutput(NEOPIXEL_PIN);
  value.b = 255; value.g = 0; value.r = 0;
  led.set_crgb_at(0, value); //Set value at LED found at index 0
  led.sync(); // Sends the value to the LED

  //Start Button
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  button.attach(BUTTON_PIN);
  button.interval(BUTTON_DEBOUNCE);

}

void loop()
{
  button.update();

  if(led_needs_update)
  {
    led_update();
    led_needs_update = false;
  }

  if(button.fell())
  {
    i2c_regs[0x00] = true;
  }
  if(button.rose())
  {
    i2c_regs[0x00] = false;
  }

  // This needs to be here for the TinyWireS lib
  TinyWireS_stop_check();

}

/*
 * I2C Handelers
 */
void i2cReceiveEvent(uint8_t howMany)
{
    if (howMany < 1)
    {
        return;// Sanity-check
    }

    reg_position = TinyWireS.receive();
    howMany--;
    if (!howMany)
    {
        return;// This write was only to set the buffer for next read
    }

    while(howMany--)
    {
        //Store the recieved data in the currently selected register
        i2c_regs[reg_position] = TinyWireS.receive();

        //Proceed to the next register
        reg_position++;
        if (reg_position >= reg_size)
        {
            reg_position = 0;
        }
    }
    led_needs_update = true;
}//End i2cReceiveEvent()

void i2cRequestEvent()
{
    //Send the value on the current register position
    //NOT WORKING when requestin multiple bytes
    //TinyWireS.send(i2c_regs[reg_position]);

    //WORKAROUND
    int n = reg_size - reg_position;//Number of registers to return
    for(int i = reg_position; i < n; i++)
    {//Return all bytes from the reg_position to the end
      TinyWireS.send(i2c_regs[i]);
    }

    // Increment the reg position on each read, and loop back to zero
    reg_position++;
    if (reg_position >= reg_size)
    {
        reg_position = 0;
    }
}//End i2cRequestEvent

/*
 * Helper functions
 */
void led_update()
{
  cRGB val;
  val.r = i2c_regs[0x01];
  val.g = i2c_regs[0x02];
  val.b = i2c_regs[0x03];
  led.set_crgb_at(0, val);
  led.sync(); // Sends the value to the LED
}

```

---
Tags: arduino-uno, i2c, attiny, attiny85
---


title: Where is JP1 on the Arduino Uno?

text:
# Question
Title: Where is JP1 on the Arduino Uno?
Recently I have been attempting to make my Arduino Uno a PIC16F877A programmer. Looking at the schematic to do this, I see that there is no JP1 pin on the Arduino as specified on the diagram on the top-left.

As I am new to electrical engineering I may just be simply overlooking it yet this is unlikely because I have been puzzled by this for two days.

# Answer
> 1 votes
JP1 is not a pin. It is a connector, with, if my eyes still work, 2 pins, which look like 13 volt DC and Ground. Likewise JP2 is not a pin, but a connector, with, hmmm, 6 pins. Three of which go directly to the Arduino, another one to the Arduino via Q1, and a final pin to Ground.

# Answer
> 1 votes
**None** of this is on the Arduino. You must construct **all** of this yourself.

---
Tags: arduino-uno
---


title: Decode VGA port by Arduino

text:
# Question
Title: Decode VGA port by Arduino
Is it possible to read somehow VGA port of graphics card by Arduino? Even with some minimal 320 x 240 resolution and minimal frame rate per second, to convert pixels into numbers (for example) somehow. Who can show where to dig?

# Answer
> 1 votes
Calculation:

320 x 240 resolution (assuming 8 bits for 256 colors) is 76,800 bytes

Assuming a frame rate of 50, that is 50 * 76,800 = 3,840,000 bytes/s

The most Arduino's are 16 MHz so assuming quite some instructions are needed (for converting and doing something) I doubt you will get this frame rate.

Also, you cannot store a complete page, but this may not be necessary.

# Answer
> 1 votes
Your standard VGA (640x480@60Hz) has a 25.175MHz pixel clock. That's far too high for an Arduino to read as an analog signal. It's even to high to read as a digital signal through a comparator (1-bit monochrome). Added to that you have three signals, red, green and blue, you would want to sample the signal at 75.525Msps if done sequentially, or 25.175Msps if done with three ADCs in parallel.

Now the Arduino has no hope of ever doing that. However there are methods that could be useful - methods that allowed a lowly little 8-bit computer, such as the ZX Spectrum, etc, to capture graphics when running at only a couple of MHz (such as the Videoface).

One of the most interesting in this scenario is called *progressive scan* (not to be confused with the "progressive scan" used in HD terminology to mean the opposite of interlaced). With this you don't try and capture an entire frame in one go. Instead you capture just a few pixels from each scan line (and even only from a selection of scan lines) from each frame. In subsequent frames you capture a different selection of pixels. Over a number of frames (which can be quite a large number given the amount of data you'd need to capture) you will get the entire image. Of course this is no use if the image is rapidly changing since the image data that you would be reading would change part way through constructing your final image resulting in interesting banding effects.

About half way through this video you can see the scanning in action and how motion causes banding.

So yes, technically it is possible to capture VGA on an Arduino (maybe with the addition of extra external memory) however it is very hard to do it and the results may not be anywhere like what you actually want.

---
Tags: arduino-uno, programming, analogread, hardware
---


# Question
Title: Using Arduino or ESP8266 as a switch to turn on a 12V DC Fan
I am new to the community and this is my first question. Hope it turns out to be a nice question :)

Me and my friend are preparing a senior design project on home automation. I have several things in my mind such as controlling drapes, lights, fans with an IOS application.

We started everything from scratch and came up with a great NTC controlled fan and etched it on a PCB as follows

However, here's our bottleneck . Although this circuit works perfectly fine and dandy, this is kind of not what we want. We want a user to control the fan, which made us realized this circuit is a total waste because it is independent of the user, turns up the fan when the temperature goes high not when the user wants it to turn up. What we really want to implement is using something that can be controlled with a phone and works as a switch.

How do you think we can do this? We have this in mind :

We are writing an IOS app with Xcode and we use ESP8266 Wifi module to bridge our phone to a web server which makes the connection between the phone and system. Do you think we can go from here? If so, what should we do to make this system work ?

# Answer
> 0 votes
Sounds like you want an ESP8266 with an API that controls a GPIO pin state. Very simple.

Phone App or Web app -\> ESP8266 with route for controlling GPIO -\> MOSFET

The MOSFET should be suitable for 3.3V logic. Don't forget the flyback diode on the motor.

Here's some pseudo-ish code:

```
espServer->on("/api/fan", HTTP_POST, [&]() {
    int pwmSpeed = server->arg("pwm").toInt()
    switchGpioState(pwmSpeed);
}
espServer->on("/get-state", HTTP_GET, [&]() {
    // Send state to browser/app
}

```

# Answer
> 0 votes
Take a look at MQTT. This a lightweight protocol designed for the IoT.

You will need:

* An MQTT *broker*. This program is the "Post Office" for MQTT messages. Clients publish and subscribe for messages here. It run on a PC.
* An MQTT *client* library for the NodeMCU or ESP8266.
* An MQTT *browser* for iPhone (Android, PC, Mac, ...).

I recommend mosquitto as a broker, but you can start working with a public broker in Internet. It is free, multi-platform and can run in any old laptop.

For iPhone/Android, I use MQTT Dash as a browser.

The beauty of this alternativa: you don't have to code an app for your phone. Protocol is trivial. Setup is non-existent. Is data agnostic (you can send/receive anything, any size). It can easily interact with apps in other platforms (like databases).

The best: it works thru Internet without any extra effort.

---
Tags: switch
---


# Question
Title: What's the problem with program , continously beeping buzzer
I have used PIR motion sensor with arduino Uno r3, alongwith one piezo buzzer. and the program is as

```
 /*
 * PIR sensor tester
 */

int ledPin = 13;                // choose the pin for the LED
int inputPin = 2;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;
int piezoPin = 11;
// variable for reading the pin status

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);
  pinMode(piezoPin, OUTPUT);
  Serial.begin(9600);
  // declare sensor as input

}

void loop(){
  val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);
    tone(piezoPin,300,160);
    delay(150);

    // turn LED ON
    if (pirState == LOW) {
      // we have just turned on

      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
    digitalWrite(ledPin, LOW);
    tone(piezoPin,0,0);
    delay(300);

    // turn LED OFF
    if (pirState == HIGH){
      // we have just turned of

      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}

```

but it supposed to ring buzzer at the time of pir motion sensor getting signal. But buzzer continuously ringing and at the time of pir sensor getting signal, it just ring louder. What is the problem in program\`\`

# Answer
**noTone()**

*Description*

Stops the generation of a square wave triggered by `tone()`. Has no effect if no tone is being generated.

NOTE: if you want to play different pitches on multiple pins, you need to call `noTone()` on one pin before calling `tone()` on the next pin.
> 1 votes

---
Tags: piezo
---


title: Description about arduino relay

text:
# Question
Title: Description about arduino relay
I have this relay module. I don't understand what is a role of the jumper on it (for now it's shorting the jd-vcc (what??) and vcc pins).

# Answer
The jd-vcc pin can be used to power the relay coils using a separate 5V power supply. Why would you want to do that? Each relay coil draws about 73mA @ 5VDC when energized. Theres a circuit schematic on this website: http://howtomechatronics.com/tutorials/arduino/control-high-voltage-devices-arduino-relay-tutorial/
> 2 votes

---
Tags: relay
---


title: Mixing analog reads with raw port reads

text:
# Question
Title: Mixing analog reads with raw port reads
I'm reading two digital inputs and one analog input. For \[reasons\] I must use `A0` and `A1` as digital ins, and `A2` as an analog in.

I'm uncertain about how the Arduino hardware deals with mixing analog and digital inputs on the same port. For speed, I'm reading like this:

```
 uint8_t raw = PINC;
 boolean digitalA = (bool)(raw & 1);  // read A0
 boolean digitalB = (bool)(raw & 2);  // read A1
 int analogC = analogRead(A2);

```

Will the raw reading of the port interfere with the `analogRead` in any way? I did see a caveat about mixing A & D, but it only had to do with noise introduced in the analog ins when doing digital outs. Would reading analog first minimize that?

# Answer
What you are trying to do is perfectly safe. In fact, you reading `PINC` will have *no effect whatsoever* on the input circuitry. You are just reading an I/O register and, whether you read it or not, this register is updated on every clock cycle from a set of comparators that monitor the pin voltages.

Just for completeness, I should mention that it is *possible* to disable the comparators that update the register. The Atmel datasheet recommends to disable them if you want the lowest possible ADC noise. If you follow that recommendation, then reading `PINC` will just return zero. The Arduino core library does not disable them: the input comparators are thus always active, and you can get a meaningful value by reading that digital input register.

**Edit**: You can *selectivly* disable the input comparator on the pin `A2` by issuing `DIDR0 |= _BV(ADC2D);`. But that is only useful if you really need to maximize the accuracy.
> 2 votes

# Answer
In general, most embedded processors multiplex external pins into specialized internal circuits. Circuits which check standard fixed threshold crossings (digital inputs), circuits which check variable threshold crossings (comparators) and circuit which combine comparators with a variable settable reference (analog to digital converter) to name only three.

Usually a pin is multiplexed to a particular internal circuit only once during initialization. Switching between internal circuits as part of normal operation is tricky and can lead to unexpected results.

Analog reads are often problematic because of noise. However, it is unlikely that reading the state of a digital input will effect the conversion of the ADC circuit.

It would be far more effective to read the actual processor's application note you are using and understand that processor's ADC issues. You may be surprised that the number is significant bits (usable bits) are less than the number found in the ADC register. Or that you can increase the number of significant bits simply by adding averaging to your software.
> 1 votes

---
Tags: arduino-uno, analogread, digital-in
---


# Question
Title: Can I use an Arduino Uno to support an RFID reader, Zigbee module and a touch screen at the same time?
I'm almost a beginner to microcontrollers and have done a few simple projects, but this time I have to use an Arduino Uno (powered by a battery) to support an RFID reader (RC522), a Zigbee module and a touch screen altogether. Apparently there are too few pins to support all the modules. What is the easiest way to implement such a system?

# Answer
Also I don't know what the RFID, zigbee and touch screen uses (generic GPIO pins, I2C, SPI, something else)?

You always can combine multiple inputs/outputs using a multiplexer (i.e. 74HC165, 74HC595), although it will mean extra software and less performance.

About the touch screen, that might be problematic regarding performance and memory usage, since the Uno has only a few KB and even the more expensive Arduino's do not have that much memory you might need.
> 1 votes

---
Tags: arduino-uno, sensors, rfid
---


title: LEDs effects changing with a button

text:
# Question
Title: LEDs effects changing with a button
So I have a bunch of functions (methods) made and I want to make it so that if the button is clicked (single click) the effects to change... I thought something like:

```
buttonState = digitalRead(buttonPin);
if(buttonState==HIGH) {
  counter++;
  if(counter>2) {
    counter=0;
   }
 }
if(counter==0) {
  Foo1();
}
if(counter==1) {
  Foo2();
}
if(counter==2) {
  Foo3();
}

```

But I noticed that it will only read the input button(buttonPin) if I click the button in the exact time (when the function has already ended and at digitalRead time)... So is there some way to do it even if the function is in progress to cancel it and go to the other ones (some way that the digitalRead will read it non stop)?

# Answer
I think you want to look at interrupts. You are right, unless the button happens to be pressed when you read the state of it you won't see it as pressed. If you `foo`s take a long time to execute the you will miss button presses.

What you can do is use 'interrupts'. Certain pins can be configured to stop the main program and run a small bit of code (that can't do certain things). For instance they can change the value of a global `volatile` variable. Next time the program reads the variable it will read the new value (volatile prevents the value being cached by the processor).

With you current code, you would remove the digital read line, and the `if (buttonState == HIGH)` block and move those into you ISR. This would mean every click would be counted. If you wanted the ISR to stop the current `foo` and move on then you `foo`s would need to check a flag that the ISR also set and when they see it they return.

In the ISR you can't call Serial.print() etc, it takes too long and your ISR won't work. Keep it fast and small.

https://www.arduino.cc/en/Reference/AttachInterrupt https://www.arduino.cc/en/Reference/DetachInterrupt
> 1 votes

# Answer
I had been timing single click as part of a minimal button debouncer (wich is part of a larger project).

According to my tests, the duration of button press is as follow:

* Quick fire press. Average, 40-70 ms per button press.
* Normal quick. Average, 150 ms per button press.
* Long press. Over 400 ms (very personal).

Now, if you loop takes less that 40 ms, your sketch still can catch almost any button press. If you restrict to "normal" button presses, your `loop` can take up to 150 ms without trouble.

So, profile your app. Measure your worst case scenario and the take action.

*We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evi*l. Donald Knuth
> 1 votes

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


title: Where to remove an ADC bias?

text:
# Question
Title: Where to remove an ADC bias?
I'm using several ACS712-based 5A current sensors. They're non-polar and so (I gather) the output is biased to Vcc/2 to allow a swing in either direction. The sensor outputs +/- 185mV/A, plus the bias.

The example sketch I've seen does a computation like `amps = ((analogRead(A0) * 5.0) / 1023) - 2.5` (where 2.5v is the bias).

In my case the actual current value and polarity aren't important, just the presence of current. Is there anything untoward about doing this instead?

```
boolean isCurrent = (abs(analogRead(A0) - 512) > thresholdValue);

```

This avoids floating point (unless `abs()` forces it?) and an ADC count of 512 should be equivalent to a bias of Vcc/2. The threshold just cores out some noise / jitter / drift. Seem OK? Can anyone suggest a better approach?

# Answer
> 1 votes
No, there is nothing untoward about that - it is perfectly acceptable and, in fact recommended, since as you note it uses no floating point.

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


# Question
Title: Problem using an array inside a switch statement
I am having a problem when using a `switch` statement to check for something inside an array. I am using an `int` as my switch, then I compare the character arrays using `strstr`. So it reads like this:

```
void function(char *buffer, uint32_t size){
  char *p=(char*)malloc(compareSize); //compareSize is the size of the text to be compared
  #define TXTCOMPARE1 (char*)"Sample Text 1"
  #define TXTCOMPARE2 (char*)"Sample Text 2"
  #define TXTCOMPARE3 (char*)"Sample Text 3"
  switch(intCompare){
    case COMPARE1 :
      p = strstr(buffer,TXTCOMPARE1); break;
    case COMPARE2 :
      p = strstr(buffer,TXTCOMPARE2); break;
    case COMPARE3 :
      p = strstr(buffer,TXTCOMPARE3); break;
  }
  if(p!=NULL) { Serial.println("Success!"); }
  else { Serial.println("No match"); }
    memset(&p,0,sizeof(p);
}

```

This method does not work and `p` is always `NULL`. However, when I write it out without the `switch()` it compares just fine:

```
//using the same p declaration as above
p = strstr(buffer,TXTCOMPARE1);
if(p != NULL) { Serial.print("Success:"); }
else { Serial.print("No Match"); }

```

Why would the `switch` statement give me different results for what is basically the same function call?

**Edit:** Actually it seems to break everywhere when I set more than one call to `p = strstr(...)`. When there is only one `strstr` it works, when two or more are used, it does not...

# Answer
One big problem is that you forgot the break statements for those cases. So if it compares in the first one and finds it, you'll still get null because it is going to go look for the third one afterwards.
> 1 votes

# Answer
I solved this problem, there were a few problems with the code that I found, so thanks for your comments. Basically, it lies in the `#define#` statements. First, in Arduino it's not such great practice to use `#define` for strings/chars, only for `int`. This is because the compiler applies the text every time they appear in the code, so it uses up a lot more memory. The problem here is solved by using `static char TXTCOMPARE1 = {"Sample Text 1"};`

Another problem was that there was no `NULL` terminated character at the end of the `#define` statement, so the program kept looking to the end of the stack when using `strstr()` and finding no termination, I think I was just getting lucky that it worked occasionally at all.

Furthermore, there is no need to clear `p` using `memset`. It needs to be declared as `NULL` and then reset after the switch by `if(p){p = NULL;}`.

And now it works!
> 0 votes

---
Tags: arduino-due, array, switch
---


title: How do I set my sampling rate?

text:
# Question
Title: How do I set my sampling rate?
I want to monitor the vibration from a motor running at 9.5Hz at 565rpm. I am using Arduino Uno and the ADXL345 as my condition monitoring equipment. How do I set the sampling frequency? I want to sample at at least 5x more than the operating frequency which is 50Hz, which will give a interval of 0.02 sec. However, to collect 2500 readings, I would need to take around 300 sec which is 0.12sec per reading different from the preset value at 0.02 sec.

Is my code wrong somewhere? Or what can I do to speed up the process?

```
#include <Wire.h>
#define DEVICE (0x53)    //ADXL345 device address
#define TO_READ (6)        //num of bytes we are going to read each time    (two bytes for each axis)
#define THRESH_ACT  (0x24)
#define THRESH_INACT  (0x25)
#include <SPI.h>
#include <SD.h>
File myFile;

// Declare Variable
byte runComplete; //setting the number of iteration
int i; //delare i for count
byte buff[TO_READ];//6 bytes buffer for saving data read from the device
float x, y, z; //Acceleration variable
float x1, y1, z1; //Acceleration variable

void writeTo(int device, byte address, byte val) {
  Wire.beginTransmission(device); //start transmission to device
  Wire.write(address);        // send register address
  Wire.write(val);        // send value to write
  Wire.endTransmission(); //end transmission
}

void readFrom(int device, byte address, int num, byte buff[]) { //reads num bytes starting from address register on device in to buff array
  Wire.beginTransmission(device); //start transmission to device
  Wire.write(address);        //sends address to read from
  Wire.endTransmission(); //end transmission
  int n = Wire.requestFrom(device, num);    // request 6 bytes from device
  if( n == num)
  {
      Wire.readBytes(buff, n);
  }
    }
void regAddress()
{
    int regAddress = 0x32;    //first axis-acceleration-data register on the ADXL345
    readFrom(DEVICE, regAddress, TO_READ, buff); //read the acceleration data from the ADXL345

     //each axis reading comes in 10 bit resolution, ie 2 bytes.  Least Significat Byte first!!
     //thus we are converting both bytes in to one int
    x = (((int)buff[1]) << 8) | buff[0];
    y = (((int)buff[3])<< 8) | buff[2];
    z = (((int)buff[5]) << 8) | buff[4];

    x1 = (x/256);
    y1 = (y/256);
    z1 = (z/256);

 Serial.println(" ");
    Serial.print("X: ");Serial.print(x1); Serial.println(" mm/s2");
    Serial.print("Y: ");Serial.print(y1); Serial.println(" mm/s2");
    Serial.print("Z: ");Serial.print(z1); Serial.println(" mm/s2");
    Serial.println(" ");

    myFile = SD.open("x30.txt", FILE_WRITE); // if the file opened okay, write to it:
    if (myFile) {
      Serial.print("Writing to X.txt...");
      myFile.println(x1);
      myFile.close();// close the file:
      Serial.println("done.");
    } else {
      Serial.println(F("error opening x.txt")) ;// if the file didn't open, print an error:
    }

    myFile = SD.open("y30.txt", FILE_WRITE); // if the file opened okay, write to it:
    if (myFile) {
      Serial.print("Writing to Y.txt...");
      myFile.println(y1);
      myFile.close();// close the file:
      Serial.println("done.");
    } else {
      Serial.println(F("error opening Y.txt")) ; // if the file didn't open, print an error:
    }
      myFile = SD.open("z30.txt", FILE_WRITE);// if the file opened okay, write to it:
    if (myFile) {
      Serial.print("Writing to Z.txt...");
      myFile.println(z1);
      myFile.close();// close the file:
      Serial.println("done.");
      Serial.println("");
    } else {
      Serial.println(F("error opening Z.txt")); // if the file didn't open, print an error:
      Serial.println("");
    }
       }

void setup()
{
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
  writeTo(DEVICE, 0x2D, 0);   //Turning on the ADXL345
  writeTo(DEVICE, 0x2D, 16);  //Turning on the ADXL345
  writeTo(DEVICE, 0x2D, 8);   //Turning on the ADXL345
  writeTo(DEVICE, 0x31, 8);
  Serial.println("Initializing Accelerometer...");
  Serial.print("Initializing SD card...");
  Serial.println("");
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    Serial.println("");
    return;
  }
  delay(2000);
}

 void loop() {
   if (runComplete == 0){
  for (i=0; i<2501; i=i+1){
 Serial.print("Number of iteration(seconds) = "); Serial.print(i);
 Serial.println("");
 regAddress();
     delay(200);
   }
  runComplete = 1;
  }
}

```

# Answer
0.02 seconds means 20 ms, not 200. Your delay time is too long. Try using millis or micros instead of delay for average deviation. Using delay will accumulate lags caused by process time. Try to sacrifice memory to log the data first (using for() & data array), and then write to serial later.
> 1 votes

---
Tags: arduino-uno, accelerometer
---


# Question
Title: How many Infrared sensor modules can be added to a single Arduino (eg;Uno)
I am looking to add block detection to my model railroad. I need approx. 40 infrared sensors to power 40 LED's on my control panel. No signals or other logic required *yet*, just the LED indications -LED- on=occupied off=vacant. How many Uno boards would I need to do this? I may, in the future, look at integrating several two (or three) aspect signals down the track. I am an absolute novice here, never having used an Arduino, nor done any coding of any sort.

# Answer
> 3 votes
You just want to know how many you can attach to an Arduino board or how many Arduino Uno boards you need, but it does not work like that.

Some sensors with a led require 5mA or 10mA or 20mA. The reflective optical sensors use a IR (InfraRed) led. The Arduino Uno 5V pin can probably not supply enough current for 40 leds. Therefor you might need a seperate power supply.
I think the TCRT5000 is typically set at 10mA.

The Arduino Mega 2560 and the Arduino Due have many pins. But with 40 TCRT5000 sensors, the total current is too close to the limit.

In such situation often extra hardware is added. You can use one Arduino Uno board, with extra hardware for multiple inputs or outputs.

An "**expander**" is a chip or a module that connects to the Arduino with a few wires, but has many input and/or output pins. For example a "expander" with I2C interface to the Arduino Uno as mentioned by @matsk. Although a I2C expander has a slow I2C interface, they are sometimes smart and can tell which pin has changed by reading a single byte.

"**Shift registers**" are chips with for example 8 input pins or 8 output pins. The data of the pins is shifted into the chip with a data and clock signal. There are many examples for that: ShiftOut with a 74HC595.

A analog "**multiplexer**" or "mux" is a chip that can connect one common pin to one of 8 pins. The signal can go both ways. Nick Gammon about a multiplexer.

A "**ADC**" is short for "Analog to Digital Converter". The Arduino Uno has an internal ADC, but also a external ADC can be used. They have often more than one analog input.

"**Polling**" is when an Arduino is reading many inputs continuously one by one. If for example it takes 5ms to read a sensor, then 40 sensors take 200ms. That means that every sensor is read once per 200ms. If a train would pass within that 200ms, then it might be not detected.
The opposite of polling is with interrupts. If an external event happens, it could trigger an interrupt and the Arduino can react right then at that very moment. However, 40 interrupts is not possible.

**Conclusion:**
The best way depends on your hardware and software skills, on the maximum interval that you want to read the sensors, on the sensors themself, and how far apart the sensors are, and if you want 40 wires to a Arduino board.
The best Arduino board also depends on what you want to do with the data and what else the Arduino has to do.
Some sensors have a analog output and some a digital output. It depends on your situation and the way the train is detected.
If possible, then I would choose a solution where all the hardware can be easily be replaced. If the sensor has digital outputs, then I would connect them to a Arduino Mega 2560 or Arduino Due.

---
Tags: led, infrared
---


# Question
Title: Detect if a 3 phase AC submersible pump is on
I need to know when a 3 phase AC submersible pump is turned on, for the sake of logging it to a online database. Thing is, I do not know how tell if it is ON, or OFF. I've given a thought to using a current transformer, specifically the "STC-013-30" one, but it requires to be wrapped around one of the AC wires (live/neutral) but the motor i have has both the wires insulated together forming a single, huge wire. Plus, its 3 phase, and I do now know if the STC can detect 3 phase currents. Can it be done some way? Can I utilise some other tool to tell if the motor is ON?

# Answer
> 1 votes
It's likely that the power to the motor is originating at a panel with breakers. You should be able to confirm that only one breaker set is being used to power the pump motor. At that location, all the wires are separated.

If you do not have the necessary skill to identify the correct wires, consider to consult an electrician. It is advisable to remove power to the panel before you begin to insert your fingers to wrap the sensor wire around the correct lead.

# Answer
> 0 votes
The long and short of it is that you need to measure the current. And there's two basic methods of doing that, and both require access to just one of the wires in the cable.

So you will either have to take a knife to your cable and *carefully* remove a section of the outer insulation to access the wires within it, or create some kind of adaptor cable that the existing cable plugs into (however that is done on your system) to allow access to the individual wires.

Then it's a case of either:

* Use the magnetic field of one wire to monitor the current (current transformer) or
* Introduce a shunt resistance into the current path and measure the voltage drop across it.

The first option is by far the safest.

Alternatively there may well be some form of commercial three-phase power monitor with an output that you can monitor to achieve what you want with less danger of electrocuting yourself and others in the process.

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


title: Arduino Leonardo keyboard

text:
# Question
Title: Arduino Leonardo keyboard
I use Arduino Leonardo board for virtual keyboard. Everything work fine, but when my local keyboard layout is russian it's not work how I want. This is my code

```
Keyboard.print("cmd");
typeKey(KEY_RETURN);
delay(2000);
Keyboard.print("powershell iwr -outf %TEMP%\\index.html http://google.com");
typeKey(KEY_RETURN);

```

Otput in English US keyboard layout:

```
cmd
powershell iwr -outf %TEMP%\index.html http://google.com

```

Output in Russian keyboard layout

```
сьв
зщцукырудд шцк -щгеа %ЕУЬЗ%\штвучюреьд реезЖ..пщщпдуюсщь

```

Is there a way to make Arduino Leonardo to write every time in English US keyboard layout no matter what keyboard layout uses my computer?

# Answer
> 2 votes
The Arduino Leonardo, in the same way as any keyboard, just sends keystroke data. It is down to your computer's operating system to translate those into individual letters and symbols. The Leonardo (and indeed any keyboard) has no say over how the operating system does that translation.

A brief google search (which led back to Stack Exchange) found me this project which may be of some interest. It allows you to automatically change the selected keyboard language depending on which keyboard is being used at any one moment in time.

---
Tags: arduino-leonardo
---


# Question
Title: multiple definition of local variable in linking
I am trying to make my own library and it uses some local variables with the same name as some variables in ino. Compiler complains about it. I stripped it to (nonsence but simple) example

**mylib.h:**

```
#ifndef MYLIB_H
#define MYLIB_H
int doit();
#endif

```

**mylib.cpp:**

```
#include "mylib.h"
int value;
int doit(){
    return value++;
}

```

**example.ino:**

```
#include "mylib.h"
int value;
void setup(){
    value=3;
    pinMode(13,OUTPUT);

}
void loop() {
    digitalWrite(13,(value==doit()) );
}

```

**compiling:**

```
$ make
/usr/bin/avr-gcc -Os -Wl,--gc-sections -mmcu=atmega328p example.o mylib.o .lib/arduino.a -lm -o example.elf
mylib.o:(.bss.value+0x0): multiple definition of `value'
example.o:(.bss.value+0x0): first defined here
collect2: error: ld returned 1 exit status
/home/gilhad/GIT/HW/Arduino/minipro//../Arduino.mk:436: recipe for target 'example.elf' failed
make: *** [example.elf] Error 1

```

---

I am **not** usint the `value` in the `.h` file, so why it collides with similary named variable from another module?

Should not be it private to the module until exposed via `.h` file?

# Answer
> 1 votes
> I am not usint the value in the .h file, so why it collides with similary named variable from another module?
>
> Should not be it private to the module until exposed via .h file?

The quick answer is that a source code file is not a separate unit. The last step in the build process is to link all the object file and create the executable binary. The linker will need to resolve all the symbols. In this case there are two definitions and the compiler cannot resolve the references. The linker can be told to ignore multiple definitions.

The keyword "static" will make the symbol local to the compiled unit (object file). As the keyword "external" tells the compiler that the definition is in another compiled unit. Header files is just a structuring convention. The language does not actually say anything about this. It is a pre-processor (cpp) in the build process that creates the combined source code for the compiler.

C++ (and OOP) adds a number of ways to control the visibility of symbols (aka encapsulation). In a class definition the keywords "public", "protected" and "private" may be used. Also the keyword "static" may be used. In this case it means that the symbol is defined globally for the class (class variable) and not per instance (member variable).

The keyword "static" in C/C++ is actually a "recent" development of the languages. In the early versions of C local symbols where prefixed with underscore "\_local". This is still a common practice even though the object files contain much more scope information today.

Cheers!

# Answer
> 1 votes
The common practice is to write Arduino libraries using C++ classes:

> The core of the header file consists of a line for each function in the library, wrapped up in a class along with any variables you need.

```
class Morse
{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;
};

```

In this way you can specify what is private (variables and methods only seen within the class) and what is public (variables and methods that can be seen outside the class). In the given example, the variable called "\_pin" is private to the class Morse.

In your case, you would want to make a private class variable called "value". Because it is private, you are free to re-use the name when not inside the class.

---
Tags: library, compile
---


title: Using millis(), in nested loops

text:
# Question
Title: Using millis(), in nested loops
I am using millis() to flash some lights (neopixels) on an arduino pro mini. The problem is that I cannot flash the lights for the desired period. More specifically, the lights flash for ~250 ms, whereas I want to flash for 9 seconds! Here is a simplified version of what I am doing.

In loop(), I have a while loop (let's call it loop 1) that should run for 250 ms. Inside loop 1, I call a function flash(), that has to run for 9 seconds! I put another loop (loop 2) after loop 1, that would run for 3 seconds.

Here is the bigger picture...I actually want a radio to wake up for 250 ms. If in that time interval it receives anything, flash() will be called that will flash the lights for 9 secs. If it doesn't receive anything it will simply go to sleep for 3 secs, then come back alive for 250 ms, so on and so on

```
void loop() {
    previousMillis = millis();
    while (millis() - previousMillis < awake_interval) {  //awake_interval = 250 ms
        flash();  //flash for 9 seconds
    }

    previousMillis = millis();
    while (millis() - previousMillis < sleep_interval);  //sleep_interval = 3 secs
}

```

The flash() function looks like this,

```
void flash() {
    unsigned long x = millis();
    while(millis() - x < flash_time){  //flash_time = 9 secs
        lights_on();
        delay(t1);
        lights_off();
        delay(t2);
    }
}

```

I put loop 2 in there because without it the lights flash forever. This makes sense because all the code is in an infinite loop - void loop().

For debugging, I put serial prints after entering the loops. It seems that nesting two loops (in my case flash() inside loop 1), both of which uses millis() is the source of the problem. If that is true, how else should I do this? If that is not the problem, any ideas will be appreciated.

**Edit:** The suggestions made by @VE7JRO and @ratchet freak are neat but I was still having problems making my thing work. Turns out it was a problem with one my initializations. I am posting my whole code below (that uses LEDs). I guess I should post the correct code as an answer.

```
const long sleep_interval = 3000;
const long awake_interval = 250;
const int ledPin = 3;

const uint8_t flash_time = 9000;  //bug
const uint16_t t1 = 5;
const uint16_t t2 = 495;

void flash() {
    unsigned long x = millis();
    while(millis() - x < flash_time){
        digitalWrite(ledPin, HIGH);
        delay(t1);
        digitalWrite(ledPin, LOW);
        delay(t2);
    }
}

void setup() {
    Serial.begin(57600);
    pinMode(ledPin, OUTPUT);
}

void loop() {
    unsigned long x = millis();
    while(millis() - x < awake_interval){
        Serial.println("flash time!");
        flash();  //overflow will occur
    }

    unsigned long y = millis();;
    while (millis() - y < sleep_interval) {  //sleep_interval = 3 secs
        Serial.println("Sleep time!");
    }
}

```

# Answer
> 2 votes
I was wrong being too confident about my whole code. When people suggested posting my whole code, I should have just done it!!!

Anyway, here is the mistake I made. I initialized the variable flash\_time as an 8-bit integer. Of course, 8 bit can only hold up to 255. I am trying to store 9000!!! The following code has this bug fixed.

```
const long sleep_interval = 3000;
const long awake_interval = 250;
const int ledPin = 3;

const uint16_t flash_time = 9000;  //bug fixed by using uint16_t instead of uint8_t
const uint16_t t1 = 5;
const uint16_t t2 = 495;

void flash() {
    unsigned long x = millis();
    while(millis() - x < flash_time){
        digitalWrite(ledPin, HIGH);
        delay(t1);
        digitalWrite(ledPin, LOW);
        delay(t2);
    }
}

void setup() {
    Serial.begin(57600);
    pinMode(ledPin, OUTPUT);
}

void loop() {
    unsigned long x = millis();
    while(millis() - x < awake_interval){
        Serial.println("flash time!");
        flash();
    }

    unsigned long y = millis();;
    while (millis() - y < sleep_interval) {  //sleep_interval = 3 secs
        Serial.println("Sleep time!");
    }
}

```

So, nested loops that use millis() to determine the terminating conditions work just fine, even if loop 1 runs for 250 ms and loop 2 (that's inside loop 1) runs for much longer, like 9 seconds.

Apologies if I have wasted too much of people's time.

# Answer
> 1 votes
Your logic is wrong. If you update previousMillis with millis() value in the first line, you are always subtracting the time difference between the the first and second lines of your code (which is the same you are doing in the loop inside flash()). If what you need is to get the time passed since the program started running, you need to have a fixed variable for that in setup() instead of updating it every time in loop().

Even so, I don't see why millis() is necessary in your case. Using delay() would be much more simple and still get the job done. Example:

```
void setup() {
delay(250);
}

void loop(){

    for(int i = 0; i < 9; i++){
        digitalWrite(LED, HIGH);
        delay(time);
        digitalWrite(LED, LOW);
        delay(time);

        delay(1000 - 2*time); //Delays the loop exactly one second per iteraction
    }

}

```

# Answer
> 1 votes
Use a state machine instead:

```
bool  flashing;
unsigned long lastflashingChange;

void loop() {
    unsigned long currentMillis = millis;
    if(flashing){
        flash();  //update flash state and change IO pin
        if (lastflashingChange - currentMillis >= awake_interval) {  //awake_interval = 250 ms
            flahsing = false;
            //turn off the led
            lastflashingChange = currentMillis;
        }
    } else {
        if (lastflashingChange - currentMillis >= sleep_interval) {  //awake_interval = 250 ms
            flashing = true;
            //possible initialize flash state
            lastflashingChange = currentMillis;
        }
    }
}

```

And a similar bit of code inside `flash()`

```
bool flashOn;
unsigned long lastFlashLightChange;
void flash() {
    unsigned long x = millis();

    if(flashOn){
        if (lastFlashLightChange - x >= t1) {
            flashOn = false;
            lights_off();
            lastFlashLightChange = currentMillis;
        }
    } else {
        if (lastFlashLightChange - x >= t2) {
            flashOn = true;
            lights_on();
            lastFlashLightChange = currentMillis;
        }
    }

}

```

# Answer
> 1 votes
Here is a sketch to get you started. It doesn't use delay or any libraries. I don't have any NeoPixel devices so I used the Arduino built in LED for testing purposes. Just remove the "myTimer4" function and related code/variables to stop the blinking LED. I don't know what type of "radio" you are using so I used a character inputed in the serial monitor to simulate a radio signal being received. There are several serial print statements throughout the code for testing purposes as well.

```
const unsigned long delayTime = 3000;
const unsigned long delayTime2 = 250;
const unsigned long delayTime3 = 9000;
const unsigned long delayTime4 = 500;
unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;
unsigned long previousMillis3 = 0;
unsigned long previousMillis4 = 0;
byte checkForData = 0;
byte dataReceived = 0;
byte flashLED = 0;
byte doOnce = 0;

void setup(){
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop(){

  // Get current time.
  unsigned long currentMillis = millis();

  // First event.
  if(checkForData == 0){
    if(myTimer1(delayTime, currentMillis) == 1){
      Serial.println("3 second timer done");
      checkForData = 1;
      previousMillis2 = currentMillis;
    }
  }

  // Second event.
  if(checkForData == 1){

    // Your radio code here to check for data.

    // I'm simulating data input from your device using the serial monitor.
    if(Serial.read() > 0){dataReceived = 1;}

    if(myTimer2(delayTime2, currentMillis) == 1){
      Serial.println("250 ms timer done");
      checkForData = 0;
      previousMillis = currentMillis;
      if(dataReceived == 1){
        flashLED = 1;
        previousMillis3 = currentMillis;
        dataReceived = 0;
      }
    }
  }

  // Third event.
  if(flashLED == 1){
    if(doOnce == 0){
      flash(1);
      doOnce = 1;
    }
    if(myTimer3(delayTime3, currentMillis) == 1){
      Serial.println("9 second timer done");
      flashLED = 0;
      flash(0);
      doOnce = 0;
      digitalWrite(LED_BUILTIN, LOW);
    }
  }

  // Fourth event.
  if(myTimer4(delayTime4, currentMillis) == 1 && flashLED == 1){
    //Serial.println("500 ms timer done");
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    previousMillis4 = currentMillis;
  }

}

// Function to send data to the NeoPixel device.
void flash(byte startStop){
  if(startStop == 1){Serial.println("flash function started");}
  if(startStop == 0){Serial.println("flash function ended");}
}

// First event timer.
byte myTimer1(unsigned long delayTime, unsigned long currentMillis){
  if(currentMillis - previousMillis >= delayTime){previousMillis = currentMillis;return 1;}
  else{return 0;}
}

// Second event timer.
byte myTimer2(unsigned long delayTime2, unsigned long currentMillis){
  if(currentMillis - previousMillis2 >= delayTime2){previousMillis2 = currentMillis;return 1;}
  else{return 0;}
}

// Third event timer.
byte myTimer3(unsigned long delayTime3, unsigned long currentMillis){
  if(currentMillis - previousMillis3 >= delayTime3){previousMillis3 = currentMillis;return 1;}
  else{return 0;}
}

// Fourth event timer.
byte myTimer4(unsigned long delayTime4, unsigned long currentMillis){
  if(currentMillis - previousMillis4 >= delayTime4){previousMillis4 = currentMillis;return 1;}
  else{return 0;}
}

```

# Answer
> 0 votes
> the lights flash for ~250 ms, whereas I want to flash for 9 seconds!

that logic doesn't make sense. Essentially you want to eat a 2 hour meal within 5 seconds.

your code reflects that kind of logic: when the execution exits flash(), it must also exit the while loop in loop().

so think exactly what you want to do, write it down and then code to it.

---
Tags: time, millis
---


# Question
Title: Can I use a GPS from old Garmin with an Arduino?
I'm working on an Arduino project, and I'd like to add GPS functionality. I could buy a GPS module, but those are expensive. I had an old Garmin Forerunner 305 lying around, so I took it apart and took a peek inside. There are two PCBs - one connected to a screen and one to the GPS. In addition, there was a battery and a small part for charging.

I'd like to know if it is possible to connect this GPS to my Arduino, and if so, how?

Edited: To make my question more precise,

-I see the pins in the top right of the picture. How do I connect those to my Arduino? Is there any specific kind of wire? Because the pins are too small for standard wires.

-Once I connect it, how do I figure out the voltage requirements and pin layout? I tried googling the GPS model, but nothing helpful came up. What kind of scope should I put on it?

The two pictures below show only the GPS part of the inside of the watch.

# Answer
> 1 votes
The short answer is **NO**, unless you have solid experience with microelectronics.

Finding documentation for a module you take out of a commercial device is hard to impossible. Chances are, that module is specific to Garmin, and even if it isn't, it's certainly EOL by now, with no support whatsoever.

Even if you do find the spec, there is a high chance that you'll have to write a software library to support it on Arduino. Don't expect the supplier to share the code they gave to Garmin.

Finally, to put together and debug this project, you will need quite some equipment:

* oscilloscope to debug the electrical interface
* soldering station to solder small pins properly

Like people said in comments, this equipment alone will cost much more than a brand-new GPS receiver.

# Answer
> 1 votes
Yes, interfacing with arduino, PC, ESP8266, whatever, easy peasy. Simple to breakout the serial comms off the Garmin, and whether or not you want to use a logic level shifter (Depending on your RS-232 logic requirements), easy too implement.

I've got a whole bunch of old Garmins (and some new ones) interfaced with some cheapy ESP8266's so I can share the GPS output (All of it. Not just the x,y,z position data), with multiple devices.

I'd be willing to share the code, wiring if you wish.

---
Tags: gps
---


# Question
Title: How do I know the size of the bootloader of ATtiny? Is it the same as ATMega328P?
I burned the bootloader in ATtiny45 with the Arduino tool.

1. I want to know how much memory it has taken.
2. Is this bootloader the same code of a bootloader used in the 328P or other chips?
3. Can I see this code in any way, to know how it works?

# Answer
> 1 votes
> 1) I want to know how much memory it has taken

Look to see how big the bootloader is. If it's a HEX file you will either want to load it into a HEX (Intel HEX, not hexadecimal representation) file editor, or convert it to binary with `avr-objcopy`.

```
$ avr-objcopy -I ihex <hex file> -O binary <bin file>

```

> 2) and if this bootloader is the same code of a bootloader used in the 328P or other chips

No, each chip requires its own special bootloader - simply because all chips are different: that's why they exist. If they were all the same there would only be one chip.

> 3) Can I see this code in any way, to know how it works ?

If it's open source and you download the bootloader from wherever it's stored (probably Github somewhere), then yes, you can. Of course, that also assumes that you would understand what you are seeing which, judging by this question, is not that likely.

---
Tags: attiny, bootloader
---


# Question
Title: Could someone explain this code that sets up the software serial port data rate?
I understand most of it. The part I don't understand is the is the code in for void loop. How does that set the data rate for the software serial port? I thought mySerial.begin(9600) did that? Please help.

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup()
{
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
    }

    Serial.println("Goodnight moon!");

    // set the data rate for the SoftwareSerial port
    mySerial.begin(9600);
    // set master
    mySerial.print("AT+ROLE1");
    delay(10000);

}

void loop() // run over and over
{

    // set the data rate for the SoftwareSerial port
    mySerial.print("test I am master  ");
    delay(10000);
    ***if (mySerial.available())
    Serial.write(mySerial.read());
    if (Serial.available())
    mySerial.write(Serial.read());***
}

```

# Answer
You're confusing "data rate" with "baud rate".

The *baud rate* is the speed at which bytes are transmitted over the wires, and is set with `mySerial.begin(9600);`.

The *data rate* is the speed at which data is sent over the serial port, and that is set by the `delay(10000);` which dictates how often `"test I am master "` is sent and any incoming data is checked for and echoed.
> 1 votes

# Answer
The void loop

```
while(!Serial) {
;
}

```

simply wait for the serial port to be ready to transmite/receive data. Otherwise, your first `Serial.print` will be lost.

You can omit it if you don't plan to transmit anything during the first second or two in your sketch.
> 0 votes

---
Tags: bluetooth, arduino-leonardo
---


# Question
Title: Arduino Pong game Circuit Board Troubleshoot
I am following a tutorial online to make a pong game. I have managed to make quiet a lot work apart from my paddles in the game keep on shaking. The buttons do work fine, up and down on both ends.

Tutorial Link

I am sure, there is something with the power being supplied and not reaching to all points in the breadboard.

I am attaching a picture of my circuit board. Any advice?

Thank you, W

# Answer
The + and - along the bottom of the picture aren't connected to anything. It also looks like this board has a separate left and right side.

So just make sure everything is connected along the sides.
> 2 votes

---
Tags: arduino-uno, display, breadboard
---


# Question
Title: Using an IR sensor from another manufacturer
I am currently trying to create a line tracing robot with my Arduino Uno.

I have an IR Sensor (http://support.robotis.com/en/product/auxdevice/sensor/irsensor\_manual.htm) but I am not sure if I can use this for my Arduino.

Can someone please tell me if I can? Thanks in advance.

# Answer
Yes, you will need to connect the sensor ADC line to an ADC input on the Arduino and calculate the range from the analogread result. You should be able to use one of the Sharp sensor libraries, although you may need to apply a correction factor to the distance results.
> 0 votes

---
Tags: arduino-uno, ir, robotics
---


# Question
Title: Cannot start Arduino IDE after playing with several versions of it
On my Linux Mint 17 Quiana I have manually downloaded and ran several versions of the arduino IDE (1.05 which is in the repo, 1.6.x for some time, now 1.8.3). Things worked like a charm.

Now I am trying to get the IDE 1.8.5 going, but I cannot get the IDE started. Started means: I download, extract the files to a directory and run the install.sh command such that the desktop icon gets created. This finishe with a success message. Now I am clicking on the desktop icon, but nothing happens.

Need to say that the IDE 1.05 which comes as a package with Qiana works just fine. I have run the install.sh of both to and fro, but only the 1.05 will start properly. I checked on the desktop link, the execution rights, user, group etc. They are all looking fine for 1.8.5 but it wont start.

I tried to start the 1.85 arduino IDE from the command line - hoping to get some clue from error messages:

```
java -DAPP_DIR=/opt/arduino-1.8.5/ Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel processing.app.Base

```

--\> running this it tells me, that the main class cannot be found.

Any hints where I am going wrong? Are there any config files to be cleared up, paths to be set ...?

# Answer
You do not *need* to install Arduino at all. In fact I have never had it work right due to things not being found.

All you need to do is, from a terminal, run the `arduino` command in the extracted directory:

```
fred@computer:~/arduino-1.8.5 $ ./arduino

```

Any errors that then throws will be a clue as to why it doesn't want to work.
> 0 votes

# Answer
1.05 is the latest available packaged version (and is quite dated).

You can download and (optionally) install the new version. See Installing Arduino IDE on Linux

Either remove (or ignore) the old version. Apart from the additional support the new version supplies, the directories differ - you can either change to the new (recommended) or change the settings.

There is no NEED to "install" the new version. The supplied script DOES NOT `install` in the traditional sense, it merely installs GUI links to the download.
> 0 votes

---
Tags: arduino-ide, linux
---


title: Arduino UNO vs NANO or MICRO with RPi3

text:
# Question
Title: Arduino UNO vs NANO or MICRO with RPi3
I'm currently using an Arduino UNO with a raspberry pi 3b. I'm using the USB connector for both power and comms, i.e. the arduino is powered by the RPI via the USB cable, and also i use the same cable for serial communication between the pi and the UNO.

My question is, could i use the same code, and wiring if i were to change the UNO with a NANO or MICRO?

So for example, on the RPI side of things, could i still simply setup the arduino in my python code as

```
arduino = serial.Serial('/dev/ttyACM0', 9600)

```

and send commands with something like

```
arduino.write('2')

```

and on the arduino side of things, just check if there is serial data coming in and read it, like

```
if (Serial.available()) {
    command = Serial.read();

```

I know this may be a very stupid question, but to wrap it up, would anything change other than number of analogues, digitals etc, if i were to switch from an UNO to a MICRO or NANO?

# Answer
> 2 votes
The Nano uses the same chip (ATMEGA 328P) that is on the Uno. So putting the same code on the Nano should work the same as the Uno.

The Micro uses a different chip. Whether or not the code from your Uno will work on your Micro depends on what is in the code. You chose not to show anyone the code so that can't be answered yet.

---
Tags: serial, raspberrypi
---


# Question
Title: Arduino Uno serial communication using USB-to-TTL converter
How to send data (Hello World) from Arduino Uno to a PC using USB to TTL/UART (PL2303 4 wires)? Why do I need to press the reset button to upload a program using PL2303?

# Answer
> 1 votes
> How to send data(Hello World) from Arduino Uno to PC using USB to TTL/UART(PL2303 4 wires)?

```
Serial.print("Hello World");

```

That is, assuming it's connected to pins 0/1. Otherwise you would have to use `SoftwareSerial`.

> why I need to press the reset button during upload a program using PL2303?

Because it lacks a DTR signal to press the reset button for you (resetting runs the bootloader).

# Answer
> 0 votes
I think you have a PL2303 board that do not have DTR or RTS line. It is a signal from Arduino IDE to Arduino Board for reset. So you must press reset button before upload.

---
Tags: arduino-uno
---


# Question
Title: Traffic lights: gpios against 5V or ground
I have 3 standard LEDs (red, yellow and green) connected in parallel to GPIO pins 10, 11 and 12. I also have one resistor, to which they are all three connected.

What's the difference between connecting the resistor to ground (so that the leds are high active) or to the 5V output pin of the arduino (so that the leds are low active)?

Moreover: how many ohms should the resistor have? My understanding is: each of the 3 standard LEDs needs 20mA, so, if all three are lit, there is 60mA on the circuit. The 3 parallel LEDs need 2 V. So, the resistor should be chosen such that it has a voltage drop of 3V at 60mA, hence 3V/60mA = 50 Ohm. If only one is lit, I need 3V/20mA = 150 Ohm.

But, if its possible that every possible subset of the LEDs is lit at once, wouldn't it be better, to place a resistor in front of every LED, so that I have 3 LED-resistor pairs in parallel? The value of each resistor is 50 Ohm then, allowing for a voltage drop of 3V in each of the 3 branches, so that each LED only gets the needed 2V?

Well, a lot of thoughts for 3 simple lights... Thanks for any help.

# Answer
> I have 3 standard LEDs (red, yellow and green) connected in parallel to GPIO pins 10, 11 and 12. I also have one resistor, to which they are all three connected.

BAD BAD BAD!!!

> What's the difference between connecting the resistor to ground (so that the leds are high active) or to the 5V output pin of the arduino (so that the leds are low active)?

Nothing, other than the reversed logic. AVR GPIOs (and most GPIOs in modern MCUs) are balanced - i.e., they have the same current limit for both sink and source.

> Moreover: how many ohms should the resistor have? My understanding is: each of the 3 standard LEDs needs 20mA, so, if all three are lit, there is 60mA on the circuit. The 3 parallel LEDs need 2 V. So, the resistor should be chosen such that it has a voltage drop of 3V at 60mA, hence 3V/60mA = 50 Ohm. If only one is lit, I need 3V/20mA = 150 Ohm.
>
> But, if its possible that every possible subset of the LEDs is lit at once, wouldn't it be better, to place a resistor in front of every LED, so that I have 3 LED-resistor pairs in parallel? The value of each resistor is 50 Ohm then, allowing for a voltage drop of 3V in each of the 3 branches, so that each LED only gets the needed 2V?

Yes. That is how you *should* wire LEDs - and you have already identified why.

For *each* LED calculate the resistance as R=(5-Vf)/0.02. You need to find the correct Vf for each LED from the datasheet to get the best results - but if you can't then a rule of thumb is: Red, Green and Yellow are about 2V, Blue and White are about 3V.
> 0 votes

---
Tags: led
---


# Question
Title: Pin change interrupt does not work properly to wake up arduino from sleep mode
I am building a timer circuit using Arduino Pro Mini Atmega168p 5v 16MHz (which later supposed to be become to adjustable one).

Here is the current breadboard view.

(I am supposed to use SS relay at place of that green thing. I am not sure if that item is correct SS relay in Fritzing)

Here is the program code I wrote.

```
#include <PinChangeInterrupt.h>
#include <PinChangeInterruptBoards.h>
#include <PinChangeInterruptPins.h>
#include <PinChangeInterruptSettings.h>

#include <avr/sleep.h>

// LED to indicate timer is active.
const int ON_LED = 5;
// It should be high when timer is active.
// Connect to relay.
const int PUMP_SWITCH = 6;

// Button to start timer running.
const int START_BUTTON = 8;
// Button to stop timer forcefully.
const int STOP_BUTTON = 9;

volatile boolean timer_running;
volatile int timer_start_time;

// TODO: Make it volatile once timer has mdified as configurable.
volatile unsigned long timer_time = 0;

void enter_sleep_mode() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sei();
  sleep_mode();
}

/**
 * Activate timer.
 */
void start_timer() {
  if (!timer_running) {
    // Time period in milliseconds.
    timer_time = 30000ul; // 30 seconds

    timer_running = true;
    timer_start_time = millis();
  }
}

/**
 * Stop timer.
 */
void stop_timer() {
  timer_running = false;
  timer_start_time = 0;
}

void setup() {
  timer_running = false;
  timer_start_time = 0;

  // Configure output pins.
  pinMode(ON_LED, OUTPUT);
  pinMode(PUMP_SWITCH, OUTPUT);

  // Configure pins for input push buttons.
  pinMode(START_BUTTON, INPUT_PULLUP);
  pinMode(STOP_BUTTON, INPUT_PULLUP);

  // Attach interrupt handlers
  // Buttons are with pull up resistors so listening for 'falling' (voltage).
  attachPCINT(digitalPinToPCINT(START_BUTTON), start_timer, FALLING);
  attachPCINT(digitalPinToPCINT(STOP_BUTTON), stop_timer, FALLING);
}

void loop() {
  if (timer_running) {
    digitalWrite(ON_LED, HIGH);
    digitalWrite(PUMP_SWITCH, HIGH);
    // TODO: Handle the case when return value of millis() goes back to start from zero
    if ( (millis() - timer_start_time) >= timer_time ) {
      // Timer elapsed the required time period.
      // So, stop the timer.
      stop_timer();
    }
  }
  else {
    digitalWrite(ON_LED, LOW);
    digitalWrite(PUMP_SWITCH, LOW);
    // Nothing to do If timer is not running.
    // Save power!!
    enter_sleep_mode();

    sleep_disable();
  }
}

```

**The problem is timer does not work when pressing START button starting from third click. Two initial clicks works OK and timer functions as it should be. I think it does not wake up properly from sleep mode. However, wondering why it works for two initial clicks??**

Please help me to identify the problem. I don't have much experience in writing Arduino code.

Thanks

# Answer
Start by checking your calculation of time limits. I see you are mixing signed and unsigned arithmetics - not a very good idea. Check the blink-without-delay example for how to do that.

The declaration of timer\_start\_time should be paid special attention.

Good luck with your project!
> 3 votes

# Answer
> Please help me to identify the problem.

it is always very easy to solve this type of problems, if you just follow some common sense.

1) decompose your functionality into manageable blocks. for example, one is PCINT - can you blink an led with it - and another is going into sleep - can you put the mcu into sleep - and the next is to walk up from sleep - does your mcu support that? what has to be true for that to happen? ...

2) test individual blocks on their own.

3) integrate them into one functional program.

don't co-mingle them day 1. tackle only what you can manage. no more and no less.
> 2 votes

---
Tags: interrupt, arduino-pro-mini, sleep
---


# Question
Title: Arduino Uno WiFi - WiFi mode keeps changing
I have an Arduino Uno WiFi device, which is turned on all the time (day and night). The WiFi mode is set to 'STA'. But from time to time it switches to 'AP+STA' mode automatically, so the device is visible in the network as an Access Point, which is not what I want. Is there a way to prevent my Arduino Uno to switch the WiFi mode by itself? Can it be done via code maybe? Thank you for your help.

Here's the code that is working on it (and it's still working without any problems):

```
#include <Wire.h>
//#include <Ciao.h> // for older IDE
#include <UnoWiFiDevEd.h> // for newer IDE

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

int sensorsValues[] = {9999,9999,9999};
int timerCount = 25;
static const uint8_t analogPins[] = {A0, A1, A2};

// for LEDs
int NUMPIXELS = 9;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXELS, 2); // (numOfPixels, pinNo, options)

boolean hasChanged = false;

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code
  //start serial connection
  Serial.begin(9600);
  for(int i=0; i<3; i++){
    pinMode(analogPins[i], INPUT_PULLUP);
  }
  strip.setBrightness(40);
  strip.begin(); // Initialize the NeoPixel library.
  strip.show(); // Initialize all pixels to 'off'
  Ciao.begin();
}

void loop() {
  for (int i = 0; i < 3; i++) {
    int sensorVal = analogRead(analogPins[i]) >= 1000 ? 1 : 0;
    if( sensorsValues[i] != sensorVal ) {
      hasChanged = true;
      if (sensorVal == 1) {
        // green light
        strip.setPixelColor( (i*3), 100, 255, 100);
        strip.setPixelColor( (i*3)+1, 100, 255, 100);
        strip.setPixelColor( (i*3)+2, 100, 255, 100);
        strip.show();
      } else {
        // red light
        strip.setPixelColor( (i*3), 255, 50, 50);
        strip.setPixelColor( (i*3)+1, 255, 50, 50);
        strip.setPixelColor( (i*3)+2, 255, 50, 50);
        strip.show();
      }
    }
    sensorsValues[i] = sensorVal;
  }
  timerCount += 1;
  if( hasChanged == false && (timerCount % 30) == 0 ){
    CiaoData data = Ciao.write("rest", "xxx.xxx.xxx.xxx", "/d/add/A001/active", "GET");
    if (!data.isEmpty()){
      String st = String(data.get(1));
      String re = String(data.get(2));
    }
  }
  if (hasChanged == true && (timerCount % 5) == 0 ) {
    CiaoData data = Ciao.write("rest", "xxx.xxx.xxx.xxx", "/d/add/A001/a/" + String(sensorsValues[0]) + "," + String(sensorsValues[1]) + "," + String(sensorsValues[2]), "GET");
    if (!data.isEmpty()){
      String st = String(data.get(1));
      String re = String(data.get(2));
    }
    hasChanged = false;
  }
  if (timerCount > 30) timerCount = 0;
  delay(1000);
}

```

# Answer
> 0 votes
OK. I found a little workaround. Arduino UNO Wifi web interface gives some possibilities. When you go to `http://<IPADDRESS>/wifi/info` you'll get json formatted info about its wifi connection settings, including WiFi mode (STA or AP+STA). To set new WiFi Mode you can go to `http://<IPADDRESS>/wifi/setmode?mode=<MODE>` to set new mode. mode=1 is for 'STA', mode=2 is for 'AP' only and mode=3 is for 'AP+STA'. I've created a little cron job on my server that checks the wifi mode and changes it if needed.

# Answer
> 0 votes
Note that when the Uno WiFi board first boots, it is in AP+STA mode...

* Which means it broadcasts its own SSID (that's the AP part).

AND

* It can connect to an existing wireless AP on your network, if you've configured those settings (that's the STA part, because it's a STAtion off the infrastructure AP).

IDEALLY

* You will change it to STA mode so it connects to your existing wireless AP only and stops broadcasting as its own AP.

Why does yours go back to AP+STA mode? Is your sketch crashing/running out of memory/rebooting? Is it older firmware? I'm not sure.

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


title: Automotive Lighting Control Module

text:
# Question
Title: Automotive Lighting Control Module
I am looking for an Arduino-based solution for an automotive lighting application.

System Requirements:

* Able to Operate in Automotive (Interior) Environment (12 +/- 2V DC Voltage)
* Minimum 3 12 V DC Inputs (Preferably 6)
* Minimum of 3 12 V DC Outputs capable of operating standard automotive-style relays. (Preferably 6)
* Compact/Condensed Form-Factor

Finding an Arduino that runs on a 12 V power supply is simple, but finding one that can handle 12 V I/Os has proven tricky.

Using a relay shield for the outputs is straightforward enough, and would be a safe way to step up the output voltage and current (although current is of little concern, given I'm only going to powering the coil in a relay). But what to do about the inputs? I don't want a transistor on each input - that would get quite tedious and large very quickly. Using relays on both sides would work, but most shields are setup to receive coil activation signals from the Arduino and as such also can't handle 12 V inputs, so using a relay shield to step-down from 12 V to 5 V also seems problematic.

Is there an all-in-one I/O solution that can step-down incoming voltages for the board and step-up output voltages on the other side?

What are my best options? I'd prefer not to have to custom-make a shield for such a basic I/O application...

Any and all help is greatly appreciated!

# Answer
A Logic Level Converter can step-down incoming voltages for the Arduino inputs and may also work to drive the relay coils. Heres an example of a 4 channel board:

https://www.sparkfun.com/products/12009

and there are also 8 channel boards:

http://www.ebay.ca/itm/8-Channel-I2C-IIC-Logic-Level-Converter-Module-Bi-Directional-for-Arduino-MF-/172424799119?hash=item282551a38f:g:6Q0AAOSwo4pYPDwg.

The boards are small and use BSS138 MOSFETs, which, according to the data sheet: http://cdn.sparkfun.com/datasheets/BreakoutBoards/BSS138.pdf can handle a maximum of 0.22A continuous current and a Drain-Source Voltage of 50V. The SparkFun link has lots of information about these devices. Normally, you would use them to translate between 5V and 3.3V but I don't see why you couldn't power the "high voltage side" with the vehicles 12 - 14V and the "low voltage side" with 5V from the Arduino.
> 1 votes

# Answer
You could use a simple voltage divider on the inputs. It would take 2 resistors pre input. That wouldn't be too huge.
> 0 votes

# Answer
An easy solution would be to use a 10K resistor in series between the 12V input and the Arduino input. This reduces the current down to about 1mA. The zener diode in the microcontroller would then safely limit the voltage to 5V.

simulate this circuit – Schematic created using CircuitLab

Its the nice easy compact solution you are looking for.
> 0 votes

---
Tags: shields, relay, input, voltage
---


# Question
Title: Programing a Mini 05 without a USB-to-serial converter
I have an Arduino Mini 05 clone Wattuino, an Elegoo Mega, a Powerboost 1000c, but not access to a USB-to-serial converter. Is there any way to program the Arduino Mini with these devices?

I tried to search it but they only mention using an Arduino uno as the chip can be put out of the board. Discusion

# Answer
You can use the Mega. The only reason for "removing the chip from the board" is to disable it so it doesn't respond to the serial data - you can also disable it by just connecting the RESET pin to GND.
> 1 votes

---
Tags: programming, usb, arduino-mini
---


# Question
Title: Send Email through Cayenne serial connection
I have an Arduino Uno connected to Cayenne through the serial connection, currently i am reading the data from a sensor of temperature and humidity DHT12 and showing it in the Dashboard of Cayenne correctly.

I need to know if i can send emails from the Arduino using the connection that cayenne let me use, because i can't stay with the pre-defined alerts that the platform have.

# Answer
> 1 votes
No, the Arduino cannot send emails directly through serial. The communication channel you have set up is a direct connection between the Arduino and Cayenne. It cannot be used for anything else other than communicating with Cayenne.

However that doesn't mean you can't try and see if there is some way of making Cayenne send emails for you. Having never used Cayenne I cannot comment on this aspect. You would be better off consulting directly with Cayenne and their users through their forums.

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