title: Using VS1838B with Arduino

text:
# Question
Title: Using VS1838B with Arduino
I just bought VS1838B IR module (from here) and I’m trying to make it work. Below you can find the circuit to see how I have connected the 1838B IR receiver:

My Code (Here) :

```
#include <IRremote.h>

int RECV_PIN = 2;
IRrecv irrecv(RECV_PIN);
decode_results results;
#define CH1 0xFFA25D
#define CH 0xFF629D
#define CH2 0xFFE21D
...
#define BUTON8 0xFF4AB5
#define BUTON9 0xFF52AD

void setup()

{

 Serial.begin(9600);

 irrecv.enableIRIn();

}

void loop() {

 if (irrecv.decode(&results))
  {

 if (results.value == CH1)

 {

 Serial.println("CH-");
 }

 if (results.value == CH)

 {

 Serial.println("CH");

 }

 if (results.value == CH2)

 {

 Serial.println("CH+");

 }

 ...

 if (results.value == BUTON8)

 {

 Serial.println("BUTON8");

 }
if (results.value == BUTON9)

 {

 Serial.println("BUTON9");

 }
 irrecv.resume();

 }

}

```

But I'm not getting any output from Serial Monitor. Can you help me for debugging it?

# Answer
Looking further here

http://forum.arduino.cc/index.php/topic,188236.0.h...

I found the following

"Removing the files - libraries\RobotIRremote\IRremoteTools.cpp and libraries\RobotIRremote\IRremoteTools.h solved the problem. They are example files which somehow are getting included. You can move those two files to some other location as backup."

I went to my libraries file and did this and can confirm that the example given above then compiles fine without downloading a new library. Its an Arduino libraries problem .

Either way will work

answer from here and worked for me

i use this code:

```
#include <IRremote.h>
int input_pin = 10; //set D10 as input signal pin
IRrecv irrecv(input_pin);
decode_results signals;
void setup()
{
    Serial.begin(9600);
    irrecv.enableIRIn(); // enable input from IR receiver
}
void loop() {
if (irrecv.decode(&signals)) {
        Serial.println(signals.value, HEX);
        irrecv.resume(); // get the next signal
    }
}

```
> 3 votes

# Answer
i have also bought this IR receiver with a remote controller (as a kit), and i had the same problem, i changed the remote controller and it worked perfectly, so even if the IR and RC came as a kit it doesn't mean they will work, if you don't have another remote controller in hand you can use a lighter just to check if the IR is working.
> 2 votes

# Answer
I could be wrong, but I believe that this receiver operates at 38kHz (at least that is listed in the specs), so the IR source must be oscillating at that frequency for this receiver to see it. Check out this link to see how to create a circuit to oscillate your IR LED:

http://www.electro-tech-online.com/threads/ir-emitter-at-38khz.94119/
> 1 votes

# Answer
```
void loop(void) {
   int numberpulses;

   numberpulses = listenForIR();

   Serial.print("Heard ");
   Serial.print(numberpulses);
   Serial.println("-pulse long IR signal");
   if (IRcompare(numberpulses, ApplePlaySignal)) {
      Serial.println("PLAY");
      if (ledState == LOW)
         ledState = HIGH;
      else
         ledState = LOW;

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

   }
   if (IRcompare(numberpulses, AppleRewindSignal)) {
      Serial.println("REWIND");
   }
   if (IRcompare(numberpulses, AppleForwardSignal)) {
      Serial.println("FORWARD");
   }
}

```
> 1 votes

# Answer
connect vcc to 5V connect Gnd to GND connect In to D11 pin onto Uno, Nano etc. download the library from here and follow the instructions/where to unzip and removing the other folders/: http://z3t0.github.io/Arduino-IRremote/

Open the Arduino program and paste this code onto a new Arduino project:

```
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}
void loop()
{
  if (irrecv.decode(&results))
    {
     Serial.println(results.value, HEX);
     irrecv.resume(); // Receive the next value
    }
}

```

Select 'Sketch'/Import Library from Arduino and select IRremote from the drop-down menu.

Upload the sketch Open Tools/Serial monitor then select 9600 as baud rate Use a Tv remote, IR car remote or the remote from the module. You will see the HEX code of each button after pressing it.
> 1 votes

---
Tags: remote-control, ir
---


title: Doubt on Processing Power

text:
# Question
Title: Doubt on Processing Power
The datasheet of arduino mega claimed that the board has 16Mhz processing power. But the question that doubt me is what would happen to the board if the board has no enough processing power.

For example, if the board is used in an application that involves a lot of calculation in each loop. Would it stall the board?

Personally, i think the board would just give slower response instead of stalling the board. It was due request is done in sequential method in the code. Therefore it would not accumulate up the request until stalling the device like PC and I think it would be just at most an arduino which is always busy.

Is it what would happen if the board has no enough processing power?

# Answer
Processing Power is a bit of a misnomer. Clock Frequency is a better description.

In general one assembly instruction gets executed each clock cycle. That means approximately 16 million instructions per second (there are a couple that take more than 1).

Your C program gets compiled into those instructions and executed at 16 million instructions per second.

If your routine is 16 million instructions long (when loops are unrolled) then it will take 1 second to execute.

Unlike a PC, which is constantly switching between tasks, an Arduino does only one thing, and that is the one thing you programmed it to do. Because of that execution time is predictable. If it took 1 second to execute today it will take 1 second tomorrow, and 1 second next week.
> 1 votes

---
Tags: arduino-mega, hardware
---


title: Arduino Due power supply

text:
# Question
Title: Arduino Due power supply
I have an Arduino Due. It communicate to the computer with the native usb port. It is also powered by the native port. Anyway, the connected sensors are pretty sensitive to the current, thus I would like to use a power supply (as a portable smartphone charger) in order to provide the current at the Arduino.

How can I say to the Arduino to get the current from another 'port' (e.g. the serial programming) and use the native port only for the communications?

# Answer
> 0 votes
You can't really fiddle with the power circuitry of the Due. If external sensors need more power than the due can provide through its internal 5V connection, whatever you choose that to be (dictated by the USB connection used) then you will either have to use a higher voltage to feed the barrel jack, or better, power the sensors separately to the Due. Just remember to connect the grounds.

---
Tags: power, arduino-due, serial-data
---


# Question
Title: Problem regarding getting split data of JSON - Another issue
In my recent project, I'm working with Arduino and JSON. I've successfully split the JSON data I want. My JSON data length is fixed. So, I used the `length()` function and I'm getting the length of my data.

Now, my input JSON data is:

```
{"TPS":"0.40","MAP":"0.95","LOAD":"14"}

```

Using the `length()` function, its length is `39`.

But when I use an `if` statement like `if(len == 39)` and put my logic inside this, I'm not getting the split data. Below is my whole code.

Here, I'm displaying my data on LCD.

```
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);
String data_TPS_Json = "";
String data_MAP_Json = "";
String data_LOAD_TM_Json = "";
String response = "";
bool begin = false;
int counter = 0;
int len = 0;
char in;
float TPS_Json;
float MAP_Json;
float LOAD_TM_Json;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop() {
  while(Serial.available() || !begin) {
    in = Serial.read();
    if (in == '{') {
      begin = true;
    }
    if(begin) {
      counter++;
      response += (in);
      len = response.length();
      if(len == 39) {
        if(counter >= 9 && counter <= 12) {
          data_TPS_Json += (in);
        }
        if(counter >= 22 && counter <= 25) {
          data_MAP_Json += (in);
        }
        if(counter >= 36 && counter <= 37) {
          data_LOAD_TM_Json += (in);
        }
      }
    }

    if(in == '}') {
      break;
    }
    delay(1);
  }
  TPS_Json = data_TPS_Json.toFloat();
  MAP_Json = data_MAP_Json.toFloat();
  LOAD_TM_Json = data_LOAD_TM_Json.toFloat();
  lcd.setCursor(0, 0);
  lcd.print(TPS_Json);
  lcd.setCursor(8, 0);
  lcd.print(MAP_Json);
  lcd.setCursor(0, 1);
  lcd.print(LOAD_TM_Json);
}

```

# Answer
Finally, I got the solution. Using `substring()` function, I can able to split my data.

Here, suppose I have two input data with fixed length.

```
{"TPS":"0.40","MAP":"0.95","LOAD":"14"}

{"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

```

So, using `length()` function I got the length of both data. So, I can able to differentiate the different data. In my previous code, I use counter and according to counter index I split my data. But somehow it does not work. So, after using `substring()` function I got the same result even better.

And below is my whole arduino code:

```
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String data_TPS_Json = "";
String data_MAP_Json = "";
String data_LOAD_TM_Json = "";

String data_LOAD_RI_Json = "";
String data_RPM_Json = "";
String data_INJECTION_TIME_Json = "";

String response = "";
bool begin = false;

char in;
int len = 0;

float TPS_Json;
float MAP_Json;
float LOAD_TM_Json;

float LOAD_RI_Json;
float RPM_Json;
float INJECTION_TIME_Json;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop()
{
  while(Serial.available() || !begin)
  {
      in = Serial.read();

      if (in == '{')
      {
        begin = true;
      }

      if(begin)
      {
        response += (in);
      }

      if(in == '}')
      {
        break;
      }

      delay(1);
  }

  len = response.length();

  if(len == 39)
  {
    data_TPS_Json = response.substring(8, 12);
    data_MAP_Json = response.substring(21, 25);
    data_LOAD_TM_Json = response.substring(35, 37);

    jsonMapTps();
  }

  if(len == 52)
  {
    data_LOAD_RI_Json = response.substring(9, 13);
    data_RPM_Json = response.substring(22, 26);
    data_INJECTION_TIME_Json = response.substring(46, 50);

    jsonRpmLoad();
  }
}

void jsonMapTps()
{
    TPS_Json = data_TPS_Json.toFloat();
    MAP_Json = data_MAP_Json.toFloat();
    LOAD_TM_Json = data_LOAD_TM_Json.toFloat();

    lcd.setCursor(0, 0);
    lcd.print(TPS_Json);
    lcd.setCursor(8, 0);
    lcd.print(MAP_Json);
    lcd.setCursor(0, 1);
    lcd.print(LOAD_TM_Json);
}

void jsonRpmLoad()
{
    LOAD_RI_Json = data_LOAD_RI_Json.toFloat();
    RPM_Json = data_RPM_Json.toFloat();
    INJECTION_TIME_Json = data_INJECTION_TIME_Json.toFloat();

    lcd.setCursor(0, 0);
    lcd.print(LOAD_RI_Json);
    lcd.setCursor(8, 0);
    lcd.print(RPM_Json);
    lcd.setCursor(0, 1);
    lcd.print(INJECTION_TIME_Json);
}

```
> 1 votes

# Answer
I don't think your loop handles the situation where the data comes in too slowly. Looking at your `while` condition:

```
while(Serial.available() || !begin)

```

Once you receive the start char, this becomes:

```
while(Serial.available())

```

Now, if there is a delay in the serial buffer, the loop exits before you have the entire message.

You should change the loop so it only ends when you have all 39 chars.

```
void loop() {
    while (39 != response.length()) {  // Keep going until full msg {
        // Check for data in serial buffer
        if (Serial.available()) {
            in = Serial.read();
            .....
        }
        // No data?
        else {
            delay(10);
        }
    }

    TPS_Json = data_TPS_Json.toFloat();
    MAP_Json = data_MAP_Json.toFloat();
    .....
}

```
> 1 votes

---
Tags: arduino-uno, json, serial-data
---


title: Arduino ISP ATtiny problems

text:
# Question
Title: Arduino ISP ATtiny problems
As I was trying to program my ATtiny chip with my arduino, I ran across some problems. Note that I know that this problem is faced almost in every Q and A site and forum so don't flag me as repeat *yet*. (I was trying to burn the bootloader so my chip runs at 8MHz)

So this is the error code:

```
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -v -v -v -pattiny85 -cstk500v1 -PCOM1 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0xe2:m

 avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

 System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM1
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

avrdude done.  Thank you.

Error while burning bootloader.

```

* **deleted attempt 2 to 9** *

Although a solution to this problem will be very nice, that is not my intention here. I tried almost all solutions I have found and non of them work, and I want to know why. So these are my questions:

1. What does this code actually mean? The for example the "programmer", is it referring to the Arduino or the ATtiny(or the highly unlikely, laptop that im using.)
2. How do I access more error codes, if there are any, as I think that these codes really do not tell that much.
3. \[Solved\]To prevent Arduino from auto-resetting, almost all tutorials connect the Reset pin to the Ground pin with a 10uF capacitor, and I don't have one. I tried with various other capacitors that I have(22uF, 0.4uF, 0.22uF, 47uF, and 330uF). I do not know how does the capacitance affect the anti auto-resetting function, so some explanation here is helpful. \[solved\]

**EDIT: I disconnected the ATtiny and the same error code persists. This, I conclude as either I never had a proper connection with the ATtiny, or the problem is with the communication of my laptop with the Arduino.**

# Answer
> 2 votes
I did not download Arduino as ISP into my arduino. I realize how much of an idiot I am. The capacitor wasn't even needed for some reasons. I might make an intensive tutorial on this project.

---
Tags: arduino-uno, attiny, bootloader, isp
---


# Question
Title: How to access the member of union in loop?
Trying to get the address of receiving XBee's data in the loop in API mode with escape. Sent data can be received properly. However, in order to identify XBee, I need the address in the loop. In other words I need those address1 to 7 which is in union XbEE\_FRAME. How to get the address in main loop. Following is the code. Appreciate your help.

```
#include <SoftwareSerial.h>

struct SENSOR_DATA{
   char rpm;   // worked
  //float rpm;
  //float strain;
  //unsigned long sampling_interval;
};

boolean xbee_rx(struct SENSOR_DATA *ret) {
  union LEN_FRAME{
    byte len_array[2];
    word len;
  }lenlen;
  static int len_i = -1;

  union XbEE_FRAME{
    byte buf[25]; // 30
    struct {
      byte frame_type;
      byte frame_id;
      byte address1;
      byte address2;
      byte address3;
      byte address4;
      byte address5;
      byte address6;
      byte address7;
      byte reserved1;
      byte reserved2;
      byte recieve_options;
      struct SENSOR_DATA sensor_data;
      byte checksum;
    } frame;
  } xbee;
  static int buf_i = -1;
  static bool escape = false;
  static byte sum;

  while (Serial.available() > 0) {
    byte b = Serial.read();

    //Serial.print(b, HEX);

     //b = Serial.read();
    if (
      b != 0x7e &&
      buf_i == -1 &&
      len_i == -1
      ) {
      continue;
    } else if (b == 0x7e){
      buf_i = 0;
      lenlen.len = 0;
      len_i = 0;
      sum = 0;
      escape = false;
      continue;
    } else if (b == 0x7d){
      //Serial.print("es: ");
      //Serial.println(b,HEX);
      escape = true;
      continue;
    }

    if (escape){
      b = b ^ 0x20;
      escape = false;
    }

    if (len_i < 2){
      lenlen.len_array[1 - len_i] = b;
      len_i++;
    } else {
      xbee.buf[buf_i++] = b;
      sum += b;
    }
    if (
      len_i == 2 &&
      buf_i >= sizeof(xbee.buf)
      ){
      len_i = -1;
      buf_i = -1;
      // frame recieved !!
      if (sum == 0xff){ // check sum!
        *ret = xbee.frame.sensor_data;
        return true;
      }
    }
  }
  return false;
}

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

void loop() {
  //mySerial.println("work");
  // put your main code here, to run repeatedly:
 struct SENSOR_DATA data;
  if (xbee_rx(&data)){
    //Serial.print(data.rpm);

     // if(b == 0x40 )  //&& b == 0xd5 && b == 0xaa && b == 0xac
  }
}

```

# Answer
Function xbee\_rx() only returns the contents of `struct SENSOR_DATA` which doesn't include those addresses. You could instead 1) return the contents of the entire `struct {...} frame` which does contain them (making sure `loop()` 's buffer is large enough; or 2) instead of returning all of that data at all, make the `union {...} xbee` static so it persists after `xbee_rx()` exits, and return a pointer to `sensor_data`, with which loop() can access any member of it, such as `p->address1`.

Update: The caller - rather than the called-function - allocates the memory buffer and the called-function uses that memory instead of its own, effectively passing the data to the caller. Here's your code, slightly re-written, with my initialed comments. I have not tried to run it but it does compile:

```
#include <SoftwareSerial.h>

struct SENSOR_DATA{
   char rpm;   // worked
  //float rpm;
  //float strain;
  //unsigned long sampling_interval;
};

//-jr-: Here we define what an XbEE_FRAME is and make it a data-type
// but we don't allocate any storage. This is just information to the
// compiler:
typedef union {
    byte buf[25]; // 30
    struct {
      byte frame_type;
      byte frame_id;
      byte address1;
      byte address2;
      byte address3;
      byte address4;
      byte address5;
      byte address6;
      byte address7;
      byte reserved1;
      byte reserved2;
      byte recieve_options;
      struct SENSOR_DATA sensor_data;
      byte checksum;
    } frame;
} XbEE_FRAME;

//-jr-: This function expects a pointer to memory (i.e., its address)
// allocated for data of type 'XbEE_FRAME' - the union from your
// original code. Note that we don't allocate any memory for it here;
// the caller is expected to do that, and this function will use what
// the caller allocated.
boolean xbee_rx(XbEE_FRAME *pXbF) {
  union LEN_FRAME{
    byte len_array[2];
    word len;
  }lenlen;
  static int len_i = -1;

  static int buf_i = -1;
  static bool escape = false;
  static byte sum;

  while (Serial.available() > 0) {
    byte b = Serial.read();

    //Serial.print(b, HEX);

     //b = Serial.read();
    if (
      b != 0x7e &&
      buf_i == -1 &&
      len_i == -1
      ) {
      continue;
    } else if (b == 0x7e){
      buf_i = 0;
      lenlen.len = 0;
      len_i = 0;
      sum = 0;
      escape = false;
      continue;
    } else if (b == 0x7d){
      //Serial.print("es: ");
      //Serial.println(b,HEX);
      escape = true;
      continue;
    }

    if (escape){
      b = b ^ 0x20;
      escape = false;
    }

    if (len_i < 2){
      lenlen.len_array[1 - len_i] = b;
      len_i++;
    } else {
       //-jr-: Note how we changed our reference from 'xbee.buf...' to
       // 'pXbF->buf...'! The '.' style addressing is used to refer to
       // memory we can name directly, as when you allocated that union
       // here. But now we  have to refer to it by the  pointer we received -
       // its address. The '->' symbol is how you address members of a
       // union or struct through a pointer:
      pXbF->buf[buf_i++] = b;
      sum += b;
    }
    if (
      len_i == 2 &&
      buf_i >= sizeof(pXbF->buf)
      ){
      len_i = -1;
      buf_i = -1;
      // frame recieved !!
      if (sum == 0xff){ // check sum!
    //-jr-: Notice that here we don't try to return any data;
    // we don't have to. Since We did everything in memory the
    // caller owns, the caller already has the data!
        return true;
      }
    }
  }
  return false;
}

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

void loop() {
  //mySerial.println("work");
  // put your main code here, to run repeatedly:

   //-jr-: Define the entire XbEE_FRAME here and pass its address to
   // your function. The function will use _this_ local storage
   // (instead of its own) to buffer the data, so it will already
   // be here when your function returns:
   XbEE_FRAME data;     //-jr- Define the entire union here
   if (xbee_rx(&data)){    //-jr-  and pass its address to the function
      //-jr-: You can address a member such as address3 as:
      //      data.frame.address3
    //Serial.print(data.rpm);

     // if(b == 0x40 )  //&& b == 0xd5 && b == 0xaa && b == 0xac

  }
}

```

Update:

> How to get the SENSOR\_DATA sensor\_data?

Use: `data.frame.sensor_data.rpm` (lower case).

* `SENSOR_DATA` only describes the kind of contents in a struct, not any actual data in memory.
* `sensor_data` is one instance of such a struct.

To go a bit further, suppose frame{} contained more than one `SENSOR_DATA` in it, maybe named sensor\_data\_a, sensor\_data\_b, ..., etc. Now to get the data from, say, `sensor_data_a` it should be clear that you need to refer to the particular instance you're interested in.
> 0 votes

# Answer
I don't think you can.

The structures are defined within a function so the loop() won't have access to them.

Further the parameter returned from the function `xbee_rx()` is of type `SENSOR_DATA` which is a sibling in the `frame` structure to the data you want to read.
> 0 votes

---
Tags: arduino-uno, xbee
---


# Question
Title: Arduino-based mains frequency monitor follow-up
Following my previous question, I'm getting closer to thinking about putting together this mains frequency monitor. I would just like to do a sanity check on my electronics before I order the components and the board. Please keep in mind I am not qualified in this so I have had to research how all this will work.

**A** and **B** inputs will accept power from a 16VAC 1.25A unregulated power pack.

**C1** is a 1µF 25V 85°C ceramic capacitor. I guess this is mostly unnecessary as the power pack should filter any DC bias, but it won't hurt.

**D1** is an IN4001 1A standard recovery diode.

**R1** is a 300ohm 500V 3W resistor. The RMS power is 16VAC, which is half-wave rectified, so that's sqrt(2) * 16 = ~24V peak @ 300ohm = 80mA peak, and about 25mA on average (right?)

**IC1** is a 4N28 optocoupler. It's weird, in one data sheet I see 80mA max forward current on inputs but in another I see 60mA. Anyway, the average should be 25mA so I guess that's probably going to be okay?

The Arduino I will use is the Arduino Micro, as it's quite small and also has a 16Mhz **crystal oscillator** that will provide a more stable clock than a ceramic resonator. The Arduino will be powered by USB, which I believe is 5V. The digital I/O pins I believe will also operate at 5V and are rated at 40mA max.

**C** will come from one of the Arduino's digital output pins, and **D** will go to the Arduino's GND.

**R2** is a 150ohm 500mW 250V resistor, that should ensure the **C****D** current does not exceed 40mA @ 5V.

Now, assuming the components look okay and the circuit looks okay (I assume the circuit is fine), I just had some questions:

1. Do I need to add anything to the output of the 4N28 coming from the input? I think with a regular transistor, some of the base current gets added to the collector current?
2. What can I expect the response on the output of the 4N28 to look like? I assumed that it would more-or-less be a square wave, where even a tiny current on the input would activate the transistor and allow the output current to flow freely on the other side, but someone has suggested that this might not be the case?
3. The way it is set up, the Digital I/O pin can be "trying" to output or not, and that's basically irrelevant to what the transistor is doing. When the transistor is on, the output current from the pin will successfully flow to GND. I assume there is a way to detect this in the Arduino? Something like setting the output pin to 1 and check in loop when there is or is no current flowing?

Thank you!

# Answer
> 3 votes
You should remove the capacitor. It won't remove any DC offset because there can be no DC offset. From where would the DC offset be relative? There is only two points in the circuit, and both of them are direct from the transformer and is an AC waveform. There is no concept of a DC offset in such a circuit. All the capacitor will do is impose a phase change between the current and voltage of the AC waveform limiting the current during the conducting period of the diodes. You have a resistor for that function.

You make some incorrect assumptions about how to read the data. You talk about outputting a signal and somehow finding out if the transistor is on or not by if that signal is being output. That's completely backwards. Instead you should treat the transistor like a simple pushbutton and provide it with a pullup (or pulldown if you prefer) resistor, like this:

simulate this circuit – Schematic created using CircuitLab

You should feed the signal into an interrupt-enabled pin (such as D2 on the Uno as shown) so that an interrupt can be used for capturing the incoming edge time. Better would be to use the Input Capture peripheral, but that is harder to program for as there is no (AFAIK) library for it.

Yes, it would be possible to use the internal pullup resistor of the input pin instead of an external one, however using an external one allows you to fine tune the resistance which, coupled with the gate capacitance of the input pin, forms a low-pass filter limiting the frequency range you can monitor. At 50Hz it shouldn't be a problem though, so the choice is yours. Personally I use an external one.

---
Tags: arduino-micro, frequency, digital
---


title: Avr dude programmer

text:
# Question
Title: Avr dude programmer
I was trying to upload a hex file to my attiny85 with an arduino,and I came across this:

```
avrdude -c avrisp (followed by other codes and the flash address )

```

This doesn't work and it gave one of the most famous arduino errors : stk500\_getsync() : not in sync: resp=0x00

Then I tried

```
   avrdude -c arduino

```

And the code was successfully downloaded, but the chip itself doesn't work as intended. So this is the question, what does the -c \[programmer id\] actually do, for example in this case, does it download the hex file to my arduino?

Thanks in advance.

# Answer
> 0 votes
Try these steps:

1. Install ArduinoISP (in the examples menu) on your Arduino board.
2. Disable reset on the Arduino board by adding a 10µF capacitor between the RESET and GND pins.
3. Wire the ATTiny chip to the Arduino following this schematic.
4. Run the upload command using `-c avrisp` with your program's HEX file

Alternatively you can just install the boards package detailed in the schematic link and program it directly from the Arduino IDE instead of messing with the `avrdude` upload command.

You must also ensure that you are uploading at the right baud rate. The ArduinoISP sketch defaults to 19200 baud:

```
// Configure the baud rate:

#define BAUDRATE    19200
// #define BAUDRATE 115200
// #define BAUDRATE 1000000

```

and you must match that in your `avrdude` command with, for example, `-b 19200`.

---
Tags: attiny, isp, programmer
---


title: Arduino % symbol meaning

text:
# Question
Title: Arduino % symbol meaning
I dont know what meaning of this symbol - %.

for example,

buttonPressCount % numberOfLED == i

I hope anyone can tell me the name and basic function of this symbol.

# Answer
It is called the modulus operator, and it performs the modulo operation.

TL;CBR: It results in the remainder after division is performed.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: Use Female USB Type A as Power Supply for external device
I bought a female USB Type A Breakout, like this (https://www.sparkfun.com/products/12700). I thought I could use this one to simply power a USB 5v water pump. Therefore I use an external USB power supply that is regulated by a relay, that I regulate with my Arduino. But I'm wondering if it is possible to get that USB Breakout to "give out" power to my water pump.

# Answer
Yes. Just connect VCC to +5V and GND to GND and you can plug a 5V device into it.

If you need to use it as a charge port (for charging a phone) you will need to connect the D+ and D- pins together.
> 0 votes

---
Tags: power, arduino-pro-mini
---


# Question
Title: How many and fast interrupt pin can handle in Uno?
So I am using Arduino UNO to do phase cutting and read Fan RPM.

For phase cutting, every half frequency it will triggers interrupts and then arduino will triggers TRIAC. Half frequency(50Hz) is 20ms. And for reading rpm, my fan running at 950rpm or 15.83rps, or doing a revolution for 63ms.

I think both of that works is doing a fast work, and I am afraid if I do it simultaneously the arduino will get an error(like a skip on one half wave, or a skip on reading one revolution), or will it not? Thanks.

# Answer
Let's do some math here.

UNO works at a 16 MHz clock rate. That's a clock cycle every 62.5 nanoseconds, or 16.000 cycles every millisecond. That means plenty of processing power within 20 millisecond, if used wisely (i.e., avoiding processing-intensive functions).

Conclusion: you shouldn't find any major problem if you do a good work with your code. Just keep things simple and don't go through the roof with what you intend to do each 20 ms.
> 1 votes

# Answer
If two interrupts happen at the same time they will both execute in the numerical order of their INT number (INT 0 will trigger before INT 1). But they will both execute - just one will be a little delayed.

If one interrupt occurs whilst the other is executing the second interrupt will trigger once the first has finished.

As long as both your interrupt routines combined take less than the time than the time between triggerings of the most rapid interrupt you won't get any issues.
> 1 votes

# Answer
You can find the number of external interrupt and pcint pins from the data sheet.

If you use interrupts, the overhead is about 20 or so ticks, or just over 1us. That gives you the minimum.

If polling, and you are lucky, 1 tick is all it takes. 1 /16th of a us.
> 1 votes

---
Tags: interrupt
---


title: Stepper motor control

text:
# Question
Title: Stepper motor control
I'm using Arduino to control a stepper motor. I need it to make one revolution and then stop. I'm new to this and haven't ran it yet. Will this do for me?

```
#include <Stepper.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  myStepper.setSpeed(60);
}

void loop() {
  myStepper.step(stepsPerRevolution);
}

```

# Answer
No, that will not do what you want. That will continuously rotate the stepper round and round and round.

The clue as to why is in the name of the function you put the `myStepper.step` call: "loop". That function repeatedly loops around over and over again, so your step function will be called over and over again.

There is one piece of information lacking from your thinking at the moment, and that is *when* do you want the stepper to rotate? If it's just once when you turn the power on then it's as simple as doing everything (including calling `myStepper.step`) in `setup()` and leaving `loop()` empty. If not, then you will need to add appropriate logic to only run the step function when the required conditions are met.
> 2 votes

---
Tags: stepper
---


# Question
Title: Cannot correctly access element in array when given index
I have the following strings which are stored in the program memory. They are basically just morse code definitions, with another array of characters where each character in the array has the same index as the morse code definitions:

```
const char a[] PROGMEM = ".-";
const char b[] PROGMEM = "-...";
const char c[] PROGMEM = "-.-.";
const char d[] PROGMEM = "-..";
const char e[] PROGMEM = ".";
const char f[] PROGMEM = "..-.";
const char g[] PROGMEM = "--.";
const char h[] PROGMEM = "....";
const char i[] PROGMEM = "..";
const char j[] PROGMEM = ".---";
const char k[] PROGMEM = "-.-";
const char l[] PROGMEM = ".-..";
const char m[] PROGMEM = "--";
const char n[] PROGMEM = "-.";
const char o[] PROGMEM = "---";
const char p[] PROGMEM = ".--.";
const char q[] PROGMEM = "--.-";
const char r[] PROGMEM = ".-.";
const char s[] PROGMEM = "...";
const char t[] PROGMEM = "-";
const char u[] PROGMEM = "..-";
const char v[] PROGMEM = "...-";
const char w[] PROGMEM = ".--";
const char x[] PROGMEM = "-..-";
const char y[] PROGMEM = "-.--";
const char z[] PROGMEM = "--..";
const char one[] PROGMEM = ".----";
const char two[] PROGMEM = "..---";
const char three[] PROGMEM = "...--";
const char four[] PROGMEM = "....-";
const char five[] PROGMEM = ".....";
const char six[] PROGMEM = "-....";
const char seven[] PROGMEM = "--...";
const char eight[] PROGMEM = "---..";
const char nine[] PROGMEM = "----.";
const char zero[] PROGMEM = "-----";

const char* const morse_table[] PROGMEM = {a, b, c, d, e, f, g, h, i, j, k, l, m,
    n, o, p, q, r, s, t, u, v, x, y, z, one, two, three, four, five, six,
    seven, eight, nine, zero};

const char alphabet[] PROGMEM = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0'};

```

I am then creating a function which is supposed to be able to take in the morse code definition and spit out a character. This function is below:

```
void checkString(char * compare) {
  //Unwrap the pointer to the array into a "real" array
  char buf[7];
  for (int i = 0; i < 6; i++) {
    buf[i] = compare[i];
  }

  int correctIndex = -1;

  for (int iterator = 0; iterator < 35; iterator++) {

    char buf2[7];
    strcpy_P(buf2, (char*)pgm_read_word(&(morse_table[iterator])));

    if ((buf[0] == buf2[0]) && (buf[1] == buf2[1]) && (buf[2] == buf2[2]) && (buf[3] == buf2[3]) && (buf[4] == buf2[4])) {
      correctIndex = iterator;
    }
  }

  if (correctIndex == -1) {
    Serial.println("Failed!");
  }

  else {
    Serial.print("Success! Index: ");
    Serial.println(correctIndex);
  }

  char characterBuffer = alphabet[correctIndex];
  Serial.println(alphabet[correctIndex]);
}

```

The strcpy\_p line of code was essentially copied from the PROGMEM reference for Arduino. I don't understand much about it, but from my tests it appears to work in getting an actual string object out of the pointer.

If I input any of the morse code definitions given, the correctIndex integer does contain the correct location of that definition in the morse\_table 2d array. However, when I pass this integer into the alphabet array hoping to get out the character at that location I am given a seemingly random character. Is there something that I'm doing wrong with this code to produce such a result? Thanks for your help.

# Answer
You can't access arrays that are in PROGMEM as if they were normal variables. The compiler can't tell the difference and just interprets it as a RAM address, which is wrong.

Instead you have to use `pgm_read_byte` to get the data:

```
char characterBuffer = pgm_read_byte(alphabet + correctIndex);

```
> 1 votes

---
Tags: c++, string, array
---


# Question
Title: Help with my DHT22 sensor and using GET request
For some reason using my DHT22 sensor I keep getting "NaN". I have tried using older versions of the DHT22 sensor library as suggested by a few of my searches, but it still doesn't fix the issue.

Also I can't get it to work with the GET request portion. Any help would be greatly appreciated.

```
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <ESP8266WiFi.h>
#include <Phant.h>
#include <ESP.h>

#define DHTPIN 2
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "Myyyyyyh";
const char* password = "Ixxxxx1";
const char* host = "script.google.com";

//*****example address
//https://script.google.com/macros/s/AKfycbyNsFc87GQmRP3GnWoTzK6/exec?tag=test&value=8
const String gardenchart = "/macros/s/AKfycbyNnWoTzK6/exec?";
const byte sleeptime = 1;
const byte NUM_FIELDS = 5;
const String fieldNames[NUM_FIELDS] = {"ghumidity", "gtemp", "light", "otemp", "wtemp"};
String fieldData[NUM_FIELDS];

void setup() {
  Serial.begin(115200);
  delay(10);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  fieldData[0] = 1;
  postdata();
  ESP.deepSleep(sleeptime * 60 * 1000000, WAKE_RF_DEFAULT);
}

void loop() {
  delay(50);
}

void postdata() {
  fieldData[0] = dht.readHumidity();
  fieldData[1] = dht.readTemperature(true);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect (host, httpPort)) {
    return;
  }
  for (int i=0; i<NUM_FIELDS; i++) {
    client.print("GET ");
    client.print(fieldNames[i]); client.print("&value=");
    client.print(fieldData[i]); client.print(" HTTP/1.1");
    client.println("Host:"); client.print(host);
    Serial.print(fieldNames[i] + fieldData[i]); delay(500);
  }
  client.println("Connection: close");
}

```

# Answer
The Adafruit DHT library causes a shortcut on the signal line. That can be a problem for Arduino boards, but it is a big problem for the ESP8266.
Issue: DHT init sequence wrong #48
I don't know what is a bigger problem, the shortcut in the code or Adafruit not fixing it.

Why do you mention the Arduino Uno with a label ?
For the "GET" you should find a good working example.

The DHT22 is not very good. There are better sensors with a normal I2C interface, for example the HTU21D-F or the BME-280. This is about a great test: Hackaday: Humidity Sensor Shootout. The BME-280 is the undisputed winner.
> 2 votes

---
Tags: arduino-uno, esp8266, temperature-sensor, http
---


title: Drawing bitmap on TFT

text:
# Question
Title: Drawing bitmap on TFT
So, my .ino file is like this (do not worry about TftDisplay library, it totally works fine and myDrawPixel function just calls the adafruit drawPixel function):

```
#include "TftDisplay.h"
#include <avr/pgmspace.h>

TftDisplay tft;

const uint8_t myBitmapBitmap [] = {
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0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 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
  0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
};

void setup() {
  Serial.begin(9600);
  Serial.print("Starting...");
  tft.init();
}

void loop() {
  mdrawBitmap(0, 0, myBitmapBitmap, 100, 146, GREEN);
  delay(2000);
  mdrawBitmap(0, 0, myBitmapBitmap, 100, 146, RED);
  delay(2000);
  mdrawBitmap(0, 0, myBitmapBitmap, 100, 146, BLUE);
  delay(2000);
}

void mdrawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color) {
  int16_t i, j, byteWidth = (w + 7) / 8;
  uint8_t byte;
  for (j = 0; j < h; j++) {
    for (i = 0; i < w; i++) {
      if (i & 7) byte <<= 1;
      else byte   = pgm_read_byte(bitmap + j * byteWidth + i / 8);
      if (byte & 0x80) tft.myDrawPixel(x + i, y + j, color);
    }
  }
}

```

So, I get some really weird *things* on my TFT. I have no idea what is going on...

As I said, the TftDisplay library is OK, but if you really wonder here is the code:

TftDisplay.h:

```
#ifndef _TFTDISPLAY_h
#define _TFTDISPLAY_h

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

//#define TFT_CS     15
//#define TFT_RST    5
//#define TFT_DC     2
//#define TFT_SCLK 14
//#define TFT_MOSI 13

#define TFT_CS 26
#define TFT_RST 24
#define TFT_DC 25
#define TFT_SCLK 22
#define TFT_MOSI 23

//#define TFT_CS 10
//#define TFT_RST 8
//#define TFT_DC 9
//#define TFT_SCLK 22
//#define TFT_MOSI 23

/*#define TFT_CS   10
#define TFT_DC   9
#define TFT_RST  8
#define TFT_SCLK 13   // set these to be whatever pins you like!
#define TFT_MOSI 11*/   // set these to be whatever pins you like!

#define BLACK           0x0000
#define BLUE            0x001F
#define RED             0xF800
#define ORANGE          0xe5f442
#define GREEN           0x07E0
#define CYAN            0x07FF
#define MAGENTA         0xF81F
#define YELLOW          0xFFE0
#define WHITE           0xFFFF

/* TFT Dimensions */
#define TFTHEIGHT 160
#define TFTWIDTH 128

class TftDisplay
{
  public:
    TftDisplay();
    ~TftDisplay();

    void init();

    void setDefaultTextSize(int textSize);
    void setDefaultTextColor(uint16_t color);
    void setTextWrap(int status);

    void text(String text, int x, int y, uint16_t color, int textSize);
    void text(String text, int x, int y, uint16_t color);

    void clearPart(uint16_t x, uint16_t y, uint16_t w, uint16_t h);
    void clearScreen();
    void myDrawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t color);
    void myDrawPixel(uint16_t x, uint16_t y, uint16_t color);
    void myDrawRectangle(uint16_t x0, uint16_t y0, uint16_t w, uint16_t h, uint16_t color);
    void myDrawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color);
    uint16_t ConvertRGB( byte R, byte G, byte B);
  protected:
    Adafruit_ST7735 *tft;

    int default_textSize;
    uint16_t default_color;
};

#endif

```

TftDisplay.cpp:

```
#include "TftDisplay.h"

TftDisplay::TftDisplay()
{

  //init cannot be here as TFT must be inited in arduino setup routine otherwise
  //it crashes everything
}
TftDisplay::~TftDisplay ()
{
  delete tft;
}

void TftDisplay::init()
{

  tft = new Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
  //tft = new Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
  tft->initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab
  tft->fillScreen(ST7735_BLACK);
}

void TftDisplay::setDefaultTextSize(int textSize){
    default_textSize = textSize;
    tft->setTextSize(textSize);
}

void TftDisplay::setDefaultTextColor(uint16_t color){
    default_color = color;
    tft->setTextColor(color, BLACK);
}

void TftDisplay::setTextWrap(int status){
    tft->setTextWrap(status);
}

void TftDisplay::text(String text, int x, int y, uint16_t color, int textSize)
{
    tft->setCursor(x, y);
    tft->setTextColor(color, BLACK);
    tft->setTextSize(textSize);
    tft->print(text);
    setDefaultTextSize(default_textSize);
    setDefaultTextSize(default_color);
}

void TftDisplay::text(String text, int x, int y, uint16_t color)
{
  tft->setCursor(x, y);
  tft->setTextColor(color, BLACK);
  tft->print(text);
  setDefaultTextColor(default_color);
}

void TftDisplay::clearPart(uint16_t x, uint16_t y, uint16_t w, uint16_t h) {
  tft->fillRect(x, y, w, h, BLACK);
}

void TftDisplay::myDrawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t color) {
  tft->drawLine(x0, y0, x1, y1, color);
}

void TftDisplay::myDrawPixel(uint16_t x, uint16_t y, uint16_t color) {
  tft->drawPixel(x, y, color);
}

void TftDisplay::myDrawRectangle(uint16_t x0, uint16_t y0, uint16_t w, uint16_t h, uint16_t color) {
  tft->drawRect(x0, y0, w, h, color);
}

void TftDisplay::clearScreen(){
  tft->fillRect(0, 0, TFTWIDTH, TFTHEIGHT, BLACK);
}

void TftDisplay::myDrawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color){
  tft->drawBitmap(x, y, bitmap, w, h, color);
}

uint16_t TftDisplay::ConvertRGB( byte R, byte G, byte B)
{
  return ( ((R & 0xF8) << 8) | ((G & 0xFC) << 3) | (B >> 3) );
}

```

# Answer
> 1 votes
You have duplicate instances on the tftDisplay.h.

```
///////#define TFT_CS 26
#define TFT_RST 24
#define TFT_DC 25
#define TFT_SCLK 22
#define TFT_MOSI 23

//#define TFT_CS 10
//#define TFT_RST 8
//#define TFT_DC 9
//#define TFT_SCLK 22
//#define TFT_MOSI 23

/*#define TFT_CS   10   --->comment this correctly
#define TFT_DC   9
#define TFT_RST  8
#define TFT_SCLK 13   // set these to be whatever pins you like!
#define TFT_MOSI 11*/   // set these to be whatever pins you like!

```

And if you're using a Mega, it has different pins for SPI as compared to Uno.

---
Tags: arduino-mega, adafruit, tft
---


# Question
Title: Will the Arduino's low clock speed limit wireless transmission frequencies that are higher than the clock speed of the Arduino?
I've recently used 2.4GHz and 433MHz wireless communication modules, and I was wondering if the Arduino can only process at 16MHz(Arduino UNO's clock speed), then won't the communication modules also be limited to a maximum 16MHz?

# Answer
> 3 votes
The frequency of a (wireless) radio is its carrier frequency. The data stream is carried on it by modulating that carrier wave in some way: by frequency-shifting, for example. A given processor could not provide data at a rate faster than its clock frequency (at least as a steady-state rate), but a packet of data, once supplied to and buffered in the radio, could then be streamed out at a speed unrelated to the physical specs of the supplier (the MCU). If the MCU had to drive the transmitter, bit-by-bit, then that would indeed limit the transmission speed.

# Answer
> 0 votes
You need like 22kHz for "telephone quality" transfer of speech, but you can hardly articulate more than 4-5 syllables per second. The first is the carrier frequency, the other is data transfer speed. (And you usually need some time to think about what you want to say).

The wireless frequency is modulated by the transmitted signal, which must be lower than the frequency itself, to be able modulate it successfully and then be separated from it. There is also some overhead like headers stating who is transmitting, to who, how much, control sum and so. A lot of it is managed in hardware, without direct processor control. (You also do not generate the frequencies and tone in you head as values of sinus wave, you just send the modulation - talk - and the body makes its parts vibrate so fast with your breath).

---
Tags: communication, wireless
---


# Question
Title: Is an Arduino Uno made in the USA compatible with SunFounder shields?
I bought an Arduino Uno from Radio Shack. I was under the impression it was the authentic model made in Italy. I read on Arduino.cc that the USA version is licensed and essentially the same. I then went to Amazon and ordered an RBG shield, and what I thought was the starter kit that is used with the examples on the IDE. I received the package and it is from SunFounder. Will this work with the IDE on the website and the Arduino I have from Radio Shack?

# Answer
> 0 votes
Use the latest official Arduino IDE : Arduino IDE

Every Arduino Uno and all the clones are compatible. Some clones have the CH340G usb-serial chip and require an extra driver. If you look very hard, you might find an Arduino Uno board that is not version 'R3' and does not have SDA and SCL near the USB connector, or does not have the polyfuse for USB 5V, or uses an ATmega328 instead of a ATmega328P. There is a chance of maybe 1 in 10,000 that you find a wrong Uno board, and in most cases those are still compatible.

Do you mean the SunFounder RGB Matrix Driver Shield? That should be no problem.

---
Tags: arduino-ide, shields
---


# Question
Title: Is Fastled.io library suitable for SMD50500 led strip?
I was looking for a ready to use library to control my SMD5050 color led strip, and I stumbled across FASTLED.IO library , but after reading trough their website I didn't find anywhere the support for SMD5050 color LED strip. Does anyone knows another "ready to use" animation library? Are FASTLED.IO suitable anyway? Thanks

# Answer
> 1 votes
No. FastLED is for addressable LEDs (like the WS2812B). Yours aren't addressable. You just need to set the colour you want with the PWM outputs of your Arduino. Changing the PWM values is not hard and you don't need a library to do it for you.

---
Tags: arduino-uno, c, rgb-led
---


# Question
Title: Arduino Uno unable to detect usb port on Mac OS Sierra 10.12.5
Few weeks ago my Arduino Uno (IDE version 1.8.2) detected the USB port and I was able to do some small IOT projects. I updated my OS to Sierra 10.12.5 and now suddenly the usb serial option has disappeared.

I followed this link : https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac where it tells us to download and install the FTDI drivers separately. I tried that but it did not help.

Then I came across this post: https://forum.arduino.cc/index.php?topic=427825.0 where the user is having this same problem with MacOS Sierra. He suggested we remove the FTDI drivers and rely on Apple's drivers. So I removed the FTDI drivers from my Mac so it will use Apple's drivers.

Now even after doing all this when I connect my Arduino Uno to my Mac via the USB it does not get detected.

I removed the kext and pkg files for the FTDI drivers and deleted them completely, still when I open the System Report I still see the FTDI USB Serial Driver entry.

When I go to System Report \> Hardware \> USB I see this:

What is happening? Did the FTDI drivers got removed? If they did then why wont the serial usb port get detected on Arduino? If they are not removed completely then what did I miss?

# Answer
> 2 votes
I installed the CH340 Driver and the board now shows the USB serial as port option: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver

---
Tags: arduino-uno, usb, ftdi, mac-os
---


# Question
Title: How can I seriously calibrate ADC voltage readings with Arduino Nano?
I have been using Arduino Nano Analog input to measure voltages, in the range between 22-30 Volts.

I want to measure it down to a tenth of a volt.

Following the instructions found here:

Read Analog Voltage (www.arduino.cc)

Which basically states that all I need is this code:

```
int sensorValue = analogRead(A0);
float voltage= sensorValue * (5.0 / 1023.0);

```

5.0/1023 = 0.004888 volts per increment in analog readings. Turning that around, voltage input divided by this value should give me the sensor value. Clearly they are presuming an input of 0-5 Volts.

My voltage divider is 1 Mohm (R1) between the voltage input and A2, then 200K (R2) from A2 to ground

30 Volts measures as 4.2 Volts. 22 Volts measures as 3.1 Volts.

I think the range between 22 volts and 30 Volts doesn't present enough variation to the ADC - every single-digit change in the analogRead really make a big difference.

The result is that it is giving me some crazy readings. It is definitely nonlinear, so I am having real trouble trying to get it to be accurate at both ends of my measurement range. Each slight ADC increment makes too much of a difference in the measured voltage because I am not using the full 0-5V input range.

So I have been taking 10 readings in a row, at 500 ms intervals, then averaging.

And yet it is not working well enough.

(The biggest problem was the reference voltage and resolution were assumed to be 5/1024 which is completely incorrect. Unless, as someone pointed out, I fed the Nanos directly at the 5V pin - which is still on the table - then it would be 5/1023)

I changed my resistor network to be 147K/23.5K

(Parts list: 1x 100K, 3x 47K)

R1 = 47K / 47K = 23.5K

R2 = 100K + 47K = 147K

Also added a 100uF 50V electrolytic across the input from the battery bank I am monitoring.

I am feeding 5V to Vin. And have figured out that the reference is measurable on the 5V pin, after the regulator, as 4.6V.

Knowing that

Resolution/Vref = ADC/Vin

I turned that around to be

Vin = ADC * (Vref/Resolution)

Or, Vin = A2 * (4.6/1023)

Using a laboratory power supply I was able to confirm that with those settings 22 Volts came in at 3 Volts, and 29.98 came in right at 4 Volts.

So

Vbat = A2 * (4.6/1023) / (R2/(R1+R2))

Vbat = A2 * (4.6/1023.0)/(147000/170500)

It is now operating reasonably well.

(Yellow means the inverter is on)

--UPDATE-- Changed resistors to 100K/20K for the divider and brought power to the 5V pin, bypassing the regulator for a reference. It measures at 5.02 and is stable.

Results:

Charge controller meter says I am at 24.5 Volts.

Program says 24.64 (in the serial monitor).

---

--ADDENDUM: I want to pursue the Op-Amp setup. But if 741 won't work will need a suggestion.

---

Similarly, I went to 147K/47K for the 11-15 Volt circuit, and moved a higher-quality P/S over to the 5V pin, where it measures 5.03V; the results are better there, too. Just very slightly high.

---

So anyway, I'll put this to rest until I can figure out an op-amp circuit.

Thank you all for your help

# Answer
> 1 votes
In my opinion, this is a very Arduino specific question.

First of all, you can't map 22-30V to 0-4.4V with a voltage divider (unless you have a negative voltage available). A opamp introduces a little more inaccuracy but can map the voltage which increases the accuracy. I suggest to first get the maximum out of the voltage divider. If that is not enough, then you can try a opamp.

The impedance of the circuit at a analog pin should be 10k or less for a accurate ADC conversion. You can add a small capacitor (1nF to 100nF) from the analog pin to GND, to keep the value stable during the ADC conversion.

The 5V VCC as a reference is a pain. The best option is to use an external voltage reference, for example a LM4040. The second best option is the internal voltage reference of 1.1V. That voltage is never 1.1V, and you have to determine the actual voltage. That 1.1V also depends on the temperature and a little on VCC.

Only 10 readings for an average is a small number. Sometimes I use 5, sometimes I use thousands.

Is the Arduino Nano used indoors, with only a small variation in temperature ? Then select the analogReference(INTERNAL). Use for example 10k and 270k for the voltage divider and 10nF parallel with the 10k. Use the average of 100 samples. An accuracy to measure the 24-30V with 0.1V resolution should be easy to achieve and 50mV resolution should be possible.

If you prefer the 1M to measure the voltage, you can also use 1M and 33k. With the 10nF parallel to the 33k, the ADC conversion is probably still accurate enough.

\[**ADDED**\] You have not told us yet how accurate you want to read the battery voltage. Is ±500mV okay, or must you have ±20mV ? I say it again: 0.1V resolution is easy. But it all depends on a good reference. A bad reference means even worse results. Dit you take a look at `analogReference` to see what the INTERNAL reference is about ?

# Answer
> 4 votes
Rather than mapping to a range of 0 to 4.4 V, map to the range 0 to 1.1 V and use `analogReference(INTERNAL)` to select the internal band-gap 1.1 V reference source. This reference voltage might vary a small amount as Vcc varies, but the variation is likely to be just a few millivolts.

To get your input voltage into the range 0 to 1.1 V, use a voltage divider and a voltage subtractor. The voltage divider ratio should map the 8-volt range of 22 to 30 V to a 1.1 V range, ie, should have a ratio of 8:1.1, and should map 30 V to 4.125 V and 22 V to 3.025 V.

If you use a Unity Gain Differential Amplifier as described at electronics-tutorials.ws, the divider can use large resistors, ie, need not provide the under-10 KΩ resistance needed for ADC input; instead, the UGDA's low output impedance will meet that requirement when used as ADC input. For example, you could have 1 MΩ in series with 160 KΩ for the main divider.

Feed that divided voltage into V1 in the diagram below. Use a pot or another voltage divider to create a 3.025 V reference to feed into V2, perhaps based on the board's 3.3 V regulator output.

Note, use R1 = R2 = R3 = R4, with all of them some value like 10 KΩ or 20 KΩ.

# Answer
> 2 votes
> Changed resistors to 100K/20K for the divider

you probably want to read the datasheet about the impedance requirement on the source and potential solutions there.

# Answer
> 0 votes
Thank you for your answers and there is a lot of collective knowledge there. It helped me find the way to stabilize and calibrate this system with what I had on hand. The biggest problem was that the reference voltage and resolution were 5/1024, which is completely incorrect.

I changed my resistor network to be 147K/23.5K (Parts list: 1x 100K, 3x 47K)

Also added a 100uF 50V electrolytic across the input from the battery bank I am monitoring.

I am feeding 5V to Vin. And have figured out that the reference it is using is measurable on the 5V pin.

Knowing that Resolution / Vref = ADC reading / Vin, I turned that around to be Vin = ADC * Vref / Resolution.

(Can someone please edit that previous line so the equations look right?

I found out that the proper resolution is 1023, not 1024

Then by measuring the 5V pin I found 4.6 from the 12v-to-5v converter going through the regulator. The 12 Volts is battery-backed and is very stable.

Vin = A2 * (4.6 / 1023)

Using a laboratory power supply I was able to confirm that with those settings 22 Volts came in at 3 Volts, and 29.98 came in right at 4 Volts.

Then I divided the Vin by (R2/R1+R2) to get the Vbat reading

Vbat = A2 * (4.6/1023) / (R2/(R1+R2))

Vbat = A2 * (4.6/1023.0)/(147000/170500)

You can see it better at

https://electronics.stackexchange.com/questions/307586/need-help-calibrating-adc-input-using-a-voltage-divider/307643#307643

It is now operating reasonably well.

(Yellow means the inverter is on)

Next step is to try 100K/20K for the divider and bring in 5V to the 5V pin, bypassing the regulator.

I want to pursue the Op-Amp setup. But if 741 won't work will need a suggestion. This setup I have been asking for measures a 500Ah 24 Volt deep-cycle Marine battery bank being charged by 6x 100W poly PV panels with a single-axis positioning system.

I now also need to measure exactly half the voltage, 11-15, for the positioning circuitry that has its own battery and dedicated 50 Watt panel to run the computer and motors. The regulated 5V out there is el-cheapo but I now have the parts on hand to give it better 5V just like I have in here with the storage bank. Should be able to finish that part today after church. I expect the ADC will see half the voltage. Instead of 3-4 Volts it should see 1.5-2 Volts.

Terrible loss of precision. I really want both systems to see 0-4 Volts at the ADC.

So my question is still the same. I think the answer is here.

---
Tags: arduino-nano, analogreadresolution, calibration
---


# Question
Title: Galileo Positioning System signal receiving
I want to determine my arduino's position. However, I want to use the *European* **Galileo** system instead of the *US-American GPS*.

Therefore, I searched for any possibilities receiving the Galileo signals. I figured out, that u-blox has some receivers: NEO 8 or the LEA 6 (firmware update required). However I did not find any arduino breakout board (, etc.) that uses these u-blox sensors or other Galileo-compatible hardware.

Does anyone know, how I could use the Galileo Position System?

# Answer
> 1 votes
You need the hardware and a library. Most GPS modules use a serial communication, and I think that also the Galileo compatible boards use serial communication. That makes them compatible with most microcontrollers and also with Arduino boards.

I could find a few shields that can be attached to an Arduino board.
This one is in development at the moment: Kickstarter shield with Galileo
This one is compatible via the serial pins: GA-001 Multi GNSS Ublox
There is a "NEO-M8N" shield and maybe one or two others.

All those boards are very new, and I don't know if they come with a library for an Arduino. Perhaps you have to wait a few months and then it should be a lot easier to buy a complete functioning module with a library.

Before buying a module, confirm that there is a library for Arduino or good documentation to write your own library.

---
Tags: gps
---


# Question
Title: Arduino Mega external interrupts fire randomly
I'm trying to solve a nagging issue with external interrupts - this is for a slot car track lap count controller. It uses the Mega's 6 external interrupt lines connected to photo diodes. The HW itself works fine - yes, trust me, it's fantastic.

I have observed the following. The code in the loop() is surrounded with:

```
detachAllInterrupts();
delay(10);
...
... process any interrupts and/or button presses
...
delay(10);
attachAllInterrupts();

```

If I omit or reduce the delay amount the random firing gets worse.

The ISR is lean and mean:

```
void lapDetected1() {
  lane1.lapDetected();
}

```

calling the method of class Lane:

```
    void lapDetected() { // called by ISR, short and sweet
      now = millis();
      if ((now - finish) < laneProtectionTime) {
        return;
      }
      start = finish;
      finish = now;
      count++;
      reported = false;
    }

```

all the variables used are declared *volatile*.

I don't *like* to use delay and I'm seeking advice on how to correctly implement ISRs and their handling.

here's the link to the entire code on GitHub: https://github.com/gabe2001/PCLapCounterWithArduino/

Thanks for any advice I can get here! -gabe

# Answer
Now, you write the following:

```
detachAllInterrupts();
delay(10);
...
... process any interrupts and/or button presses
...
delay(10);
attachAllInterrupts();

```

I understand that you put this stuff into the loop, such that the loop in effect looks like this:

```
void loop() {
    detachAllInterrupts();
    delay(10);
    ...
    ... process any interrupts and/or button presses
    ...
    delay(10);
    attachAllInterrupts();
}

```

Assuming that the above is correct, then you will be enabling and disabling your interrupts in one long stream. You would often NOT disable your interrupts, because you don't know when the are available or not, then.

You should typically ENABLE the interrupts in the startup code, and then in the `loop()` you can have any Other processing you want, but not any processing referring to the interrupt processing.

The interrupt processing would take care of the button pressed etc. So - in the `lane.lapdetected1()` algorithm, you would take care of reading buttons pressed etc., and, you would have to attach the interrupt itself directly to your algorithm. I cannot see that you have told that when an interrupt has been happening, then the code execution goes to the ISR `lane.lapdetected1()` algorithm?

What you would want to do, is to setup an interrupt in the `setup()`, which is run once upon start of the program in the arduino, and then, providing that you want the interrupt on pin 2 (external pin), and the algorithm to run while you receive falling signals on the pin 2 is lapdetected1, then you could use the following:

```
void setup() {
  attachInterrupt(digitalPinToInterrupt(2), lapdetected1, FALLING);
}

```

Thereby you would remove the `detachAllInterrupts()`, and all the way down to `attachAllInterrupts()` from the loop construction and thereby you would be able now to process interrupts within the lapdetected1-algorithm and run what ever you would want to run, normally, from within the loop-construction.
> 2 votes

# Answer
> The code in the loop() is surrounded with:

it doesn't make much sense for you to "process the interrupts" in the loop(). Use ISR instead.
> 0 votes

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


# Question
Title: Nano clone not working over USB, no data, no power, but can power via Vin (CH340 chip? schottky diode?)
My quite new Nano clone (ATmega328P + CH340G) suddenly stopped working. Plugging it in with USB did not light up the LED(s) nor did it get detected by my machine. I looked it up, and found some how-to's (such as this one: Repair Arduino Nano (no power on USB)), which suggested at least some diagnostics.

So I plugged the Nano in to a 5V breadboard power source using the Vin and GND pins, and the power LED lights up, but connecting via USB cable to my machine does not detect it.

So then I used some of the methods mentioned in the link, and used just a normal jumper cable (without soldering) to check if that could magically make it detectable by my machine. No luck. I tried bypassing the voltage regulator by "jumping" over it, and the power LED gets brighter, and "pin 13" LED flashes for just an instant. The same occurs if I "jump" the voltage regulator all the way to either end of what I am guessing is the "Schottky diode".

In all cases, still nothing in terms of being detected by my computer. The cable is fine because I tested with another nano clone, and it gets detected right away.

So, how do I properly diagnose what is going on here? Specifically how do I fix my poor board? How do I find which component is in need of replacing?

---

Update:

I found some online guides on how to have another Arduino board talk to this one over SoftwareSerial and found that I could get some data flowing through. However, the text was garbled, such that, for example if I was expecting it to say:

> "Please enter some input"

It might read instead:

> "Ulease XYZter some \[\]\[\]put"

Often with the same characters being garbled in the same way. I tested the Schottky diode the way it was suggested in the video (with some guessing as to the multimeter setting I had to use was, since I have a different model than the one in the video), and it seems the diode is fine. So at this point I am guessing it is the ch340g chip that is toasty, either that, or the ATmega chip itself, which I don't know, but that sounds less likely.

So, could it be that it is the CH340G chip, since I get no power over USB, and the TX/RX over serial is being interfered with? Is there anything else I can do to figure out if it is the CH340G that's damaged before I go about trying to replace it?

# Answer
Either you have a cable problem or that board is just not working well.

What you call the CH340 chip - when they go bad you get power but NO communications, in my experience. You can test voltages at the various points like 5V, 3.3V, etc., to see if it getting power. If it is and you're still not communicating, then if it were me it would go on the shelf for the kids to see.

It no longer can trusted.

Rather than troubleshooting the board it would be worth getting another to compare with.

And if you have more than one cable on hand, try them and see if there are any differences.

But my prediction is that a new board will work and this one will continue to not work.
> 1 votes

---
Tags: arduino-nano, atmega328, ch340
---


# Question
Title: Does Nano not get sufficient power via USB?
I have an Uno, and I can play all I want with it, just using a USB cable.

Then I got two Nano clones, and they both show the same behavior:

When I connect it to the USB cable (which leads to my PC) it blinks a few times, then seemingly does nothing. I am also not able to connect to it via the Arduino IDE.

If I then connect an external power source to Vin and Gnd, it wakes up and blinks forever, and I am able to connect to it.

Is this just because I got a cheap clone? Or is this really the accepted / expected behavior?

# Answer
I have a few clones but have not seen this behaviour so I guess it could be one of three things (in order of most likely to least):

1. They have a fault related to taking power from the USB connector.
2. The USB lead is not able to supply enough power ie. it is cheap and extremely thin and cannot carry much current. Have you already tried other cables?
3. Your USB port cannot supply enough power. Given that the spec says 500mA from a USB 2 port, this seems unlikely unless the port is faulty. Have you tried other ports / another PC?
> 6 votes

# Answer
To answer your title question, My Nanos run at significantly less than the 500 mA you can draw from a normal USB port, so unless you have a cable problem it should be getting enough, yes.

One thing I have learned about cables is that your mileage may vary. For the Pi, it is nice enough to show me a lightning bolt on-screen when it isn't getting enough, and swapping the cable fixes it 99.9% of the time.

Arduinos simply display odd behavior like this one.

**I always suspect power supply first.**

So first, try changing cables. Then if that doesn't help try changing Arduinos and see if the problem follows the Arduino.

Good luck!
> 0 votes

---
Tags: power, arduino-nano
---


# Question
Title: How can Arduino know Wire.available() is true or false?
In this part of code

```
void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

```

## How can Arduino know that Wire.availble() is true or false?

I thought that when the microcontroller "reads" the value from the sensor, in pieces of 8 bits, he reads from 0 (n) to 5 (n+5) at the I2C address of the MPU-6050, and when he increments 6 it finds nothing, but this is my conclusion, i am not sure about it.

I am studying how Serial.available works and how the circular buffer works for the data comunication, because available() inherits from the Stream utility class.

The entire code is the following taken from this question

```
  #include <Wire.h> //The I2C library

int gyroResult[3], accelResult[3];

//Function for writing a byte to an address on an I2C device
void writeTo(byte device, byte toAddress, byte val) {
  Wire.beginTransmission(device);
  Wire.write(toAddress);
  Wire.write(val);
  Wire.endTransmission();
}

//Function for reading num bytes from addresses on an I2C device
void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

//Function for reading the gyros.
void getGyroscopeReadings(int gyroResult[]) {
  byte buffer[6];
  readFrom(0x68,0x1D,6,buffer);
  gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
  gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
  gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
}

//Function for reading the accelerometers
void getAccelerometerReadings(int accelResult[]) {
  byte buffer[6];
  readFrom(0x53,0x32,6,buffer);
  accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
  accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
  accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
}

void setup() {
  Wire.begin();            //Open I2C communications as master
  Serial.begin(9600);    //Open serial communications to the PC to see what's happening

  writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
  writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
  writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
  writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
}

void loop() {
  getGyroscopeReadings(gyroResult);
  getAccelerometerReadings(accelResult);

  Serial.print(gyroResult[0]);
  Serial.print("\t");
  Serial.print(gyroResult[1]);
  Serial.print("\t");
  Serial.print(gyroResult[2]);
  Serial.print("\t\t");
  Serial.print(accelResult[0]);
  Serial.print("\t");
  Serial.print(accelResult[1]);
  Serial.print("\t");
  Serial.print(accelResult[2]);
  Serial.print("\n");

  delay(50);
}

```

## Minor Question

I am trying to undestand the difference between the register and the device address, but i did find anything on my book.

# Answer
> 1 votes
The simple answer is that the Arduino Wire library has an internal buffer, and it can bring in characters and have them sitting there ready for you to pick them up.

It can also sense a total disconnect because of the way it uses both data pins to establish communications. It is more like a current loop than a simple one-is-transmit-and-the-other-is-receive. If it disconnects the Arduino knows it is not available.

Kudos on going to the documentation, by the way.

---
Tags: serial, i2c, hardware, wire-library, buffer
---


# Question
Title: Arduino Wire.h library: how to communicate with an LCD?
I am having an Arduino Uno and a C2042A LCD with I2C shield on it. Because the VirtualWire library does not work for me. I tried only the wire library but it's still not working:

My code:

```
#include <Wire.h>

void setup() {
  Wire.begin(0x63);
}

void loop() {
  Wire.write(4);
}

```

I just read on this website which commands you have to use but it doesn't do anything. What is my fault, how to solve it?

# Answer
SOLVED!

I forgot to write `beginTransmission()`. Here's my code:

```
#include <Wire.h>

void setup() {
  Wire.begin(0x63);
}

void loop() {
  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write("Temperatur:");
  Wire.endTransmission();
}

```
> 1 votes

# Answer
The documentation under the link you posted says: "The I2C display is located on the I2C bus at an address of 0XC6.", not the address you have used in your code.
> 0 votes

# Answer
You can't begin writing unless you first initialize it like with Serial.begin

In this case you don't show Wire.beginTransmission.

Perhaps it is in the code you didn't show us, but it is required.
> 0 votes

---
Tags: i2c, lcd, wire-library
---


title: Which sensor to detect light?

text:
# Question
Title: Which sensor to detect light?
I have a kit of 37 sensors as described here:

I want to create a simple circuit:

* if the light is detected - flash LED
* if there is no light - do nothing

Among 37 sensors I don't seem to find anything related to light / brightness / lumens...

**Can you please advise me which sensor to get?**

---

Shall I get a photocell (Light Dependent Resistor) as described here: https://learn.adafruit.com/adafruit-arduino-lesson-9-sensing-light/parts ?

# Answer
Number 23 in the list says *photoresistor*, corresponding to module KY-018 in your kit, which is what you called *photocell* (a photocell is another type of sensor to my knowledge). As the name states, a photoresistor is a device changing it's resistance depending on the amount of light it detects/receive.

A photoresistor usually looks like:

In order to get a meaningful reading from an LDR you need to convert the resistance into a voltage which the Arduino's ADC can read. The simplest method is to use a voltage divider: the junction between the LDR (photoresistor) and R1 is the node to connect your analog pin to get your readings, which will be a voltage that is a proportion of the supply voltage (5V) defined by the ratio of the two resistances.

The KY-018 module mentioned above already provides all the necessary and provides you 3 pins: `5V`, `ANALOG` and `GND`.

simulate this circuit – Schematic created using CircuitLab
> 3 votes

# Answer
You are after the "KY-018 Photo resistor module". It is number #23 "Photoresistor" on the instructables.com webpage.

The module contains a Light Dependant Resistor (LDR).

More information on the module can be found at https://tkkrlab.nl/wiki/Arduino\_KY-018\_Photo\_resistor\_module.
> 3 votes

# Answer
Use a photoresistor aka photocell. They are variable resistors that change there values depending on the intensity of the light source.

It is sensor KY-018 : KY-018 Photo resistor module.

Here is a helpful code:

```
const int sensor = A0; //declare photocell pin
const int led = 13;

void setup()
{
  pinMode(sensor, INPUT);
  pinMode(led, OUTPUT);
}

void loop()
{
  int val = analogRead(sensor);
  if(val > 512)
  {
    digitalWrite(led, HIGH);
    delay(500);
    digitalWrite(led, LOW);
    delay(500);
  }
}

```
> 1 votes

# Answer
No, I would suggest you not bother with photocell, phototransisters nor light-dependent resistors.

Better answer is the 1750 light-detection and measurement module.

It connects by I2C and reads out a numeric value corresponding to the amount of light (Lux) it senses.

Very easy to set up.

I use one to measure the light of the sky so I can compare it to the output of my solar cells.

Here is a cool light meter project (complete with hookup instructions and code) that uses one to sense light and displays the results on a 7-segment display:

BUILDING A SIMPLE DIGITAL LIGHT METER USING ARDUINO AND BH1750FVI SENSOR
> -1 votes

---
Tags: sensors
---


# Question
Title: Expected unqualified ID before numeric constant
After debugging and having some conflicting declarations about analog pins, I finally thought it was done, after compiling I got this error:

```
32:0,
1:
31:12: error: expected unqualified-id before numeric constant

2:5: note: in expansion of macro 'B1'

```

I can't understand what this means. What's wrong with my code down here?

```
// don't judge me if it's too long and overcomplicated :P I'm still new xD
int AA1 = 0;
int B1 = 1;
int C1 = 2;
int D1 = 3;
int AA2 = 4;
int B2 = 5;
int C2 = 6;
int AA3 = 8;
int B3 = 9;
int C3 = 10;
int D3 = 11;
int B4 = 12;
int C4 = 13;
int sec = 0;
int min1 = 0;
int min2 = 0;
int hour1 = 8;
bool hour2 = 0;

void setup() {
  pinMode(AA1, OUTPUT);
  pinMode(B1, OUTPUT);
  pinMode(C1, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(AA2, OUTPUT);
  pinMode(B2, OUTPUT);
  pinMode(C2, OUTPUT);
  pinMode(AA3, OUTPUT);
  pinMode(B3, OUTPUT);
  pinMode(C3, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(B4, OUTPUT);
  pinMode(C4, OUTPUT);
}

void loop() {
  OutputOn();
  delay(1000);
  sec++;
  if(sec == 60) {
    sec = 0;
    min1++;
      if(min1 == 10) {
      min1 = 0;
      min2++;
        if(min2 == 6) {
        min2 = 0;
        hour1++;
          if(hour1 == 10) {
          hour1 = 0;
          hour2 = 1;
        }
        if(hour2 == 1, hour1 == 3) {
          hour1 = 1;
          hour2 = 0;
        }
      }
    }
  }
}

void OutputOn() {
  digitalWrite(B1, LOW);
  digitalWrite(C1, LOW);
  digitalWrite(D1, LOW);
  digitalWrite(A2, LOW);
  digitalWrite(B2, LOW);
  digitalWrite(C2, LOW);
  digitalWrite(A3, LOW);
  digitalWrite(B3, LOW);
  digitalWrite(C3, LOW);
  digitalWrite(D3, LOW);
  digitalWrite(B4, LOW);
  digitalWrite(C4, LOW);
  if(min1 == 1) { digitalWrite(AA1, HIGH); }
  if(min1 == 2) { digitalWrite(B1, HIGH); }
  if(min1 == 3) { digitalWrite(B1, HIGH); digitalWrite(AA1, HIGH); }
  if(min1 == 4) { digitalWrite(C1, HIGH); }
  if(min1 == 5) { digitalWrite(C1, HIGH); digitalWrite(AA1, HIGH); }
  if(min1 == 6) { digitalWrite(D1, HIGH); digitalWrite(B1, HIGH); }
  if(min1 == 7) { digitalWrite(D1, HIGH); digitalWrite(AA1, HIGH); digitalWrite(B1, HIGH); }
  if(min1 == 8) { digitalWrite(D1, HIGH); }
  if(min1 == 9) { digitalWrite(D1, HIGH); digitalWrite(AA1, HIGH); }
  if(min2 == 1) { digitalWrite(AA2, HIGH); }
  if(min2 == 2) { digitalWrite(B2, HIGH); }
  if(min2 == 3) { digitalWrite(B2, HIGH); digitalWrite(AA1, HIGH); }
  if(min2 == 4) { digitalWrite(C2, HIGH); }
  if(min2 == 5) { digitalWrite(C2, HIGH); digitalWrite(A2, HIGH); }
  if(min2 == 6) { digitalWrite(C2, HIGH); digitalWrite(B2, HIGH); }
  if(hour1 == 1) { digitalWrite(AA3, HIGH); }
  if(hour1 == 2) { digitalWrite(B3, HIGH); }
  if(hour1 == 3) { digitalWrite(B3, HIGH); digitalWrite(AA3, HIGH); }
  if(hour1 == 4) { digitalWrite(C3, HIGH); }
  if(hour1 == 5) { digitalWrite(C3, HIGH); digitalWrite(AA3, HIGH); }
  if(hour1 == 6) { digitalWrite(C3, HIGH); digitalWrite(B3, HIGH); }
  if(hour1 == 7) { digitalWrite(C3, HIGH); digitalWrite(AA3, HIGH); digitalWrite(B3, HIGH); }
  if(hour1 == 8) { digitalWrite(D3, HIGH); }
  if(hour1 == 9) { digitalWrite(D3, HIGH); digitalWrite(C3, HIGH); }
  if(hour2 == 1) { digitalWrite(B4, HIGH); digitalWrite(C4, HIGH); }
}

```

It's supposed to be code for a clock (if it wasn't obvious enough) hooked up to 4 7-segment decoders, also connected to 4 7-segment LED displays.

# Answer
> 6 votes
Bad luck. There is a file within Arduino called "binary.h", and it contains a define called "B1". Which means you may not use "B1" as a variable. In my opinion, that file "binary.h" is totally unnecessary.

In the preferences you can turn on extra output for the compiler and turn on line numbers. The compiler will tell what is wrong, but you have to know how the compiler does that. The first compiler error is the most important.

"*.../hardware/arduino/avr/cores/arduino/binary.h:31:12: error: expected unqualified-id before numeric constant #define B1 1*" means that the compiler was reading the file "binary.h" and at line 31 it noticed something it did not understand and it has to do with "B1".

---
Tags: arduino-uno
---


# Question
Title: Trying to print "occur = 1" in an if statement but it wont work
Cant seem to get this code to work with my arduino, and yes its all hooked up properally, even used leds to show that the button is being pressed, what am i doing wrong or dont know?

```
const int digitalInPin3 = 8;     //switch
int Occur = 0;
int Switch = 0;

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

void loop() {
int Switch = digitalRead(digitalInPin3);

if (Switch == 1){
  int Occur = 1;
}

else {
 int occur = 2;
}

   Serial.print("\t Switch =");
   Serial.print(Switch);
   Serial.print("\t occur =");
   Serial.println(Occur);

  delay(1);
}

```

# Answer
> 1 votes
Remove the *int* from inside the if and else statement. The code would always show 0 because access of *occur*, which is assigned value 1 or 2 is limited to the if..else statement. So the global occur remains 0 always.

So change it to:

```
if (Switch == 1){
 Occur = 1;
}
else {
 Occur = 2;
}

```

This will work.

# Answer
> 0 votes
The comments are right, as is the other answer.

Also, I see that both Switch and Occur are highlighted as if they are keywords.

I know for sure Switch is a reserved word.

Take all of these suggestions together. Remove the int from inside the if.

I recommend you change the variable names entirely to something else. And make them consistent.

Define them one time at the top then just modify them within the code.

---
Tags: arduino-uno
---


# Question
Title: How do I use an ATMega 328 (not P) chip with an Arduino board?
I just burned the bootloader on an ATMega328 chip and then I put in on the Arduino board. But when I try to upload a program to it, it says programmer not in sync and programmer not responding.

For burning the bootloader I changed the address in the avrconfig file and reset it back to the original one. Do I need to keep changing the address of the board?

How do I use this as a normal Arduino board, as I fried my original chip? Do I need to get an ATMega328P chip?

# Answer
So I found the solution:

Here is the link to the method that worked for me. I think the reason my previous method didn't work was because of fuses for the clock as mentioned by Majenko in the comments.
> 2 votes

# Answer
You can force the 'P' bootloader into it and use it as an Arduino board. The extra possibilities of the 'P' are not used by the standard Arduino libraries and when uploading it does check the bootloader but it does not check the chip signature.

I think you have already done this. Perhaps something else is wrong.
> 0 votes

---
Tags: atmega328, avr
---


title: Custom boards list

text:
# Question
Title: Custom boards list
Is there a simple way to create or modify my boards list? I find having a full library listing confusing. I have about 6 boards I program regularly, but using the listings from the board manager gives me about 60 things to look through, which gets tedious fast.

Here is a list of MCUs I frequently use:

* Teensy2.0
* Adafruit Trinket 16Mhz
* Adafruit Trinket Pro 16MHz
* Adafruit Circuit Playground
* Adafruit feather Huzzah
* Arduino Uno R3

How can I make a boards list that only includes the boards I own?

# Answer
Throwing out the unneeded boards from the boards.txt files will do what you want.
> 1 votes

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