# Question
Title: Using a library of sleeping with a combination of the WD and a physical INTERRUPT
I would like to use one of the nice libraries like :

1. JEELIB
2. ENERLIB
3. SLEEP\_N0M1
4. NARCOLEPTIC
5. ADAFRUITSLEEPY\_DOG
6. LOW\_POWER\_MASTER

1. But to use a X second interval of sleeping and in the same time to enable the option of an Interrupt on pin2 that will get me out of all this sleepy mode vector if there will be interrupt ! which library is better and easier for this situation?
2. when I want more then 8 second , what is the mining of doing 2x8s when they wrote it in some of those libraries -what should it mean to do ?
3. Is there an option to enable the interrupt for a wake up from the sleep not only by a LOW\_mode but also by a CHANGE\_mode of the pin2 ??

Thank you very much in advanced @!

# Answer
> 1 votes
1. "Best" is completely subjective. I've used Narcoleptic myself. it's easy to use and somewhat limited. For the needs of my project, it served well. You'll need to review the libraries' source code and descriptions to decide which library will best serve your application.
2. The Watchdog timer has a maximum interval of 8 seconds. To sleep longer, you'll need a routine that counts enough 8 second sleeps, plus lesser sleep periods, to make up the total sleep time you want. There are other timers you can use, but not in Power Down sleep mode.
3. See section 10, "Power Management and Sleep Modes" of the ATmega328p datasheet (or the datasheet for the chip your Arduino uses). There is a table of wake-up sources for each sleep mode. It says that, except from Idle mode, only a level-triggered interrupt can wake the chip. But note that section 10.5 says a pin-change interrupt can wake the CPU. It appears that either kind can wake it but "the required level must be held long enough for the MCU to complete the wake-up to trigger the level interrupt." It does not mention the (obviously transient) pin-change interrupt. You may need to experiment.

Update:

> ...I cant get a sleep for more than 8 second but I can only get to a sleeping mode twice and by that to get almost a 16 second of sleeping ?

Yes, the longest Watchdog timer period is 8 seconds.

> I still didn't understand if there is an easy possible to get into a sleep with a routine periods of WD wakings and in the same time enabling a physical interrupt on pin2 that works parallel ?

From my reading of the datasheet, yes, you can use both timers in parallel. But it wasn't clear to me whether a pin-change can both wake the CPU and cause an interrupt (that is, vector into your interrupt routine). A level-interrupt can, if the level is held long enough (I believe they said 4 CPU cycles would be required).

---
Tags: library, interrupt, sleep
---


# Question
Title: Using GPS Module ET314AC With arduino Mega
Can I use GPS Module ET314AC with Arduino Mega? Here is the datasheet of ET314AC ET314AC Datasheet

# Answer
yes you can, the datasheet is saying that you can read from a serial port which is what you want to do.

Connecting the serial port to TX and RX pins of the Arduino, ground and power, you should be able to talk to the module.

I cant find a breakboard for this module so I suppose you are going to solder it or you can give us the link where you bought it.

I suggest you to try with TinyGPS library to decode the data, after you are sure that the module is talking to the Arduino correctly.
> 1 votes

---
Tags: arduino-mega, gps
---


title: Using 5V arduino with 12v solenoid lock

text:
# Question
Title: Using 5V arduino with 12v solenoid lock
I wish to use an arduino like this with a 12v solenoid lock like this. How can I do this. I am told that using this might work, but I am also thinking I can use a transistor's amlification to do that. Can you tell which one is better and if transistor, how to do that?

# Answer
> 4 votes
By sheer luck your lock solenoid looks very similar to this one (similar spec too "Draws 650mA at 12V") and they have a working circuit for it over here so look at that and see what they used to drive it. Apparently it's a TIP120, so the peak/draw current is probably higher than that ballpark figure, which I suspect is for the hold.

Overengineering the transistor by an order of magnitude or so (for a poorly spec'd solenoid part) ensures it doesn't go pop so easily. Also, a Darlington like TIP120 is very easy to drive from the arduino or some other microcontroller.

A similar project using the same solenoid lock used an IRLB8721 (power MOSFET) instead, which is even more beefy in terms of load current it can handle.

---
Tags: transistor
---


title: What's Happened with my Arduino?

text:
# Question
Title: What's Happened with my Arduino?
I am in a First Year Design class, and we are supposed to be making an autonomous robot. After hooking up some wind speed and temperature sensors to calibrate, I plugged in to my laptop (we have 2 arduino nanos) and ran a temperature code. I got the reading, but smelled something burning. Nothing was smoking, but I've found that when I plug my arduinos into my laptop, the light and the code indicate that they are not connected. This is odd because when I plug in the batteries, they show that the proper voltage is coming through, but they will still not connect to the laptop. Is it a problem with the micro-usb port?

I've included the code I'm using just in case that is cause for suspicion. It is notable that our instructors have written an API that allows us to code in Java for the arduinos.

```
public static void main (String[] args)
{
    robot = new ArduinoNano();
    robot2 = new ArduinoNano();
    robot.setPort("COM5");
    robot2.setPort("COM6");
    robot.connect();

    int reading = getThermistorReading();

    System.out.println("The probe read the value " + reading);
    System.out.println("In volts: " + (reading * (5.0/1023.0)));
    System.out.println();

    double temperature = (reading - 855.02) / -7.563;

    System.out.println("Temperature: " + temperature);

}

public static int getThermistorReading()
{
    int sum = 0;
    int readingCount = 10;

    for (int i = 0; i < readingCount; i++)
    {
        robot.refreshAnalogPins();
        int reading = robot.getAnalogPin(3).getValue();
        sum += reading;
    }

    return sum / readingCount;
}

```

}

# Answer
First, did the Arduino continue to respond and operate after you smelled the burning?

Just because there isn't smoke doesn't mean you didn't kill something on the board.

If your Arduino is not responding, there are two possibilites I can think of:

1. Your port is not working so simply switch to a different USB port
2. Somehow your laptop must have sent a large amount of amps/volts to the circuit and burned it out. If you have a multimeter you can use the sound setting to test whether or not wires are burned out, and if your nifty with an iron/heat gun, you can replace the part. Or you could buy a new one.

If the connection is good, you will hear a small beep. Oh, and these things don't work if there's a resistor in the way.
> 1 votes

---
Tags: serial, usb, hardware
---


# Question
Title: Arduino ethernet shield not responding to every request because it is busy
I have a simple HTTP server that monitors a serial port and responds to HTTP requests by sending the value. The serial port constantly outputs data, so that apart from a brief moment when the device is initializing the Arduino always has data available. Once a value is retrieved from the RS232 connection it is stored in a buffer. The buffer is overridden when new values are received.

Occasionally the server does not respond to a request. Monitoring through Chrome developer tools reports net::ERR\_CONNECTION\_RESET Could it be that the Arduino is busy with processing the serial port when the connection request is made? What I find very difficult to understand is that once in a while the code below will display "Not available". This shouldn't happen because, as stated above, the buffer is always available.

```
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("Connection: close");
    client.println("Cache-Control: no-cache, no-store, must-revalidate");
    client.println("Pragma: no-cache");
    client.println("Expires: 0");
    client.println("Refresh: 5");
    client.println();
    client.println("<!DOCTYPE HTML>");
    client.println("<html>");
    client.println("<body>");
    client.print("Value: ");
    if (valueReady()) {
      client.println( getValue() );
    } else {
      client.println( "Not available" );
    }
    client.println("</body>");
    client.println("</html>");

```

The "Not available" message is really confusing because that should only occur when the Arduino starts. valueReady() will only return false when power is first applied.

The LEDs on the Ethernet shield do not indicate that the Arduino is being reset, but it seems as if the sketch is periodically restarting. Is it possible for a buffer overrun to cause the Arduino to reboot?

# Answer
> 1 votes
The delay was occurring because, in some cases, I was storing the RS232 data into a character array past the initialized length. It looks like it was causing the Arduino to reboot.

---
Tags: arduino-uno, ethernet, rs232
---


# Question
Title: Arduino Leonardo is not recognized by usb cable in Windows 8
My Arduino Leonardo was working properly but for the last two hours when I connect it to a PC via a USB cable, it is reporting something like `USB is not recognized` and even in device manager it is not showing. However, when I press the restart button on the Arduino, the PC will detect it as an `Arduino Leonardo bootloader(com 7)` but after few seconds it disappears. What do I have to do? I tried to restart the PC, changed USB cable but the same issue occurs. I checked the USB by connecting another device - it works fine but the Arduino is not recognised. I tried other PCs also but the same problem continued. What do I have to do?

# Answer
> 3 votes
It is highly likely that the sketch you loaded is causing this.

> However, when I press the restart button on the Arduino, the PC will detect it as an Arduino Leonardo bootloader(com 7) but after few seconds it disappears.

For a few seconds after reset the bootloader will configure the board as a USB serial device, awaiting upload of a new sketch. Once that times out it runs the existing code. If the existing code does not configure the USB port (eg. by doing `Serial.begin`) then it will cease to enumerate as a USB device. This is perfectly normal.

The "fix" is to upload a sketch that uses the USB interface. For example, open a serial port, open the keyboard (`Keyboard.begin()`) or similar.

# Answer
> 3 votes
Nick Gammon's solution worked for me. I am adding the arduino code I used below.

While Arduino Leonardo is connected to your computer, press its reset button. A COM for Arduino Leonardo appears under the Arduino IDE: Tools \> Port: **You should upload the code within a few seconds just after you press the reset button while the Leonardo COM is appearing.**

The following is the code I used:

```
// Start of Code

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

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

// End of Code

```

# Answer
> 0 votes
It could be the settings of the serial port (you mentioned com 7). Try going on your Arduino Integrated Development Environment.

Go to Tools \> Serial Port \> (and try putting this setting on different serial ports)

If the Serial Port is grayed out and you cant press it, try restarting the Arduino with the restart button, and hopefully you will have an opportunity to change the Serial Port in those few seconds that the Arduino is recognized. Try all the different Serial Ports your computer has.

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


title: Interfacing ADS8319 with Arduino UNO

text:
# Question
Title: Interfacing ADS8319 with Arduino UNO
I am using Arduino UNO and trying to interface 2 16-bit ADS8319 ADCs with it via the SPI interface.

I have interfaced the 2 ADCs with the micro-controller using the "4 Wire CS Mode Without Busy Indicator" (data sheet page number 15).

I am using the following code to get the values from the ADCs.

```
#include <SPI.h>
#define CONVPIN 7
#define SELPIN 8
#define SELPIN2 4
#define MISOPIN 12
#define SCLKPIN 13

int adcvalue;
byte byte1; byte byte2;
const float aRefVoltage = 5;
float volts = 0;

void setup() {

  // put your setup code here, to run once:
  pinMode(SELPIN, OUTPUT); // ADC's selection pin
  pinMode(SELPIN2, OUTPUT); // 2nd ADC's selection pin
  pinMode(CONVPIN, OUTPUT); // ADC's conversion pin
  pinMode(SCLKPIN, OUTPUT); // ADC's clock pin
  pinMode(MISOPIN, INPUT);  // ADC's data out
  SPI.begin();
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(CONVPIN, LOW);
  digitalWrite(SELPIN, HIGH);
  digitalWrite(SELPIN2, HIGH);
  digitalWrite(CONVPIN, HIGH);
  digitalWrite(SELPIN, LOW);

  delay(1000);

  byte1 = SPI.transfer(0x00); //transfer (read) 8 bits from the adc chip D15-8
  byte2 = SPI.transfer(0x00);  //transfer (read) the second 8 bits. D7-0

  adcvalue = (byte1 <<8) | (byte2 & 0xff);  // combine the 2 bytes to make our 16 bit word
  Serial.print("Voltage Value: ");
  Serial.println(adcvalue,BIN);
  volts = (adcvalue*aRefVoltage/65535);
  Serial.print(" Sensor Volts: ");
  Serial.println(volts,5);
  delay(1000);
}

```

However i am not getting the right values. The ADC that ive selected by "digitalWrite(SELPIN, LOW);" should output 1V, whereas the values keep on changing in between 0 and 2.2 V .I am not sure if my code is correct or not. Can you please verify the code so that i should know whether the problem is in my hardware, or the code.

Below is the screenshot for my schematic :

Your helpful suggestions and comments would be appreciated ! Thankyou.

# Answer
After lots and lots and changing values for resistors and capacitors and checking connections, i came to find out that my micro-controller ground was not at the same level as the ADCs ( i had already connected its ground with my circuit board ground but there was some kind of problem ). When i soldered the controllers ground just near the ADCs ground, both the ADCs started working properly.
> 0 votes

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


title: Why atmega168/328p starts to reset?

text:
# Question
Title: Why atmega168/328p starts to reset?
First we set fuse bits:

```
avrdude -c usbasp -p atmega328p -U lfuse:w:0xFF:m -U hfuse:w:0xDF:m -U efuse:w:0x07:m # same for atmega168

```

In the following examples we use the following commands to compile and burn all the programs:

```
avr-gcc -Os -mmcu=atmega328p -c -o serial.o serial.c
avr-ld -o serial.elf serial.o
avr-objcopy -O ihex serial.elf serial.hex
avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

```

Let us burn the following program:

```
#define F_CPU 16000000UL
#include <avr/io.h>
void main (void) {
  DDRB |= (1<<PB5);
  PORTB |= (1<<PB5);
  while (1);
}

```

It makes the led to be on constantly. And it stays so for infinite period of time.

Then we burn the following program:

```
#define F_CPU 16000000UL
#define BAUD 9600
#include <avr/io.h>
char data = 0;
void main(void) {
  // Initialize USART:
  #include <util/setbaud.h>
  UBRR0H = UBRRH_VALUE; // set the speed (Higher bit)
  UBRR0L = UBRRL_VALUE; // set the speed (Lower bit)
  UCSR0B |= (1<<RXEN0); // enable receiver
  UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00); // set mode (8N1)
  DDRB |= (1<<PB5); // enable output on pin PB5 (default led on arduino)
  while(1) {
    while(!(UCSR0A&(1<<RXC0))); // wait until a byte is received
    data = UDR0; // read it
    if (data) PORTB |= (1<<PB5); // set the led on
  }
}

```

Then we open a terminal (9600,8N1) and press several keys, until the led turns off. Now we burn the first program again and the led is constantly blinking. The reason for this is that watchdog times gets started when we press the keys in terminal. But why and when WDT gets started? How to make so that it will not start?

It should be noted also that we can disable the blinking only with complete poweroff/poweron - only after that the led lights constantly without blinking, as necessary.

This happens on atmega168 and atmega328p, 100% reproducible.

avr-gcc version 4.8.1 avrdude version 6.1

**NOTE:** bootloader is not used at all.

# Answer
> 1 votes
One thing that I found whilst experimenting with command line compilation is that for some strange reason no startup code was being linked with my code, so it all went completely screwy.

I finally tracked the problem down to a missing command line flag while linking.

First, you need to link with `avr-gcc` not `avr-ld`. Second, you need to pass the `-mmcu=atmega328p` flag to the link command so that it knows which startup code to link in.

This is my complete command line sequence for compiling a simple blink program:

```
avr-gcc -g -mmcu=atmega328p -ffunction-sections -fdata-sections   -c -o blink.o blink.c
avr-gcc -mmcu=atmega328p -Wl,--gc-sections -o blink.elf blink.o
avr-objdump -S blink.elf > blink.dis
avr-objcopy -O ihex -R .eeprom blink.elf blink.hex

```

You notice I'm making function and data sections too, and then garbage collecting the unused ones - good practice since it can very much reduce the size of your finished program.

I am doing this through a Makefile, which looks like this:

```
PREFIX=avr-
CC=${PREFIX}gcc
CXX=${PREFIX}g++
LD=${PREFIX}ld
AS=${PREFIX}as
OBJCOPY=${PREFIX}objcopy
OBJDUMP=${PREFIX}objdump

BIN=blink
MCU=atmega328p
OBJS=blink.o

CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
CXXFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections -fno-exceptions
LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

${BIN}.hex: ${BIN}.elf
    ${OBJCOPY} -O ihex -R .eeprom $< $@

${BIN}.elf: ${OBJS}
    ${CC} ${LDFLAGS} -o $@ $?
    ${OBJDUMP} -S $@ > ${BIN}.dis

install: ${BIN}.hex
    avrdude -c usbasp -p ${MCU} -U flash:w:${BIN}.hex -qq

clean:
    rm -f *.o *.elf *.hex

fuses:
    avrdude  -c usbasp -p ${MCU} -U lfuse:w:0xff:m -U hfuse:w:0xd6:m -U efuse:w:0x05:m -qq

```

# Answer
> 1 votes
WDT settings will remain unchanged, even after a reset. So the timer will keep running and therefore keep resetting the device. Which causes the blinking. Power cycling will clear the WDT settings.

PS I didn't read the code, as uncommented register writes are pretty much unreadable.

# Answer
> 1 votes
The problem code was reduced to this:

```
#define F_CPU 16000000UL
#include <avr/io.h>
char data;
void main(void) {
  UBRR0H = 0x00;
  UBRR0L = 0x67; // baud=9600
  UCSR0B = 0x10; // 00010000
  UCSR0C = 0x06; // 00000110
  DDRB |= (1<<PB5);
  PORTB |= (1<<PB5);
  while(1) {
    data = UDR0;
  }
}

```

This is the code which works:

```
#define F_CPU 16000000UL
#include <avr/io.h>
void main(void) {
  char data;
  UBRR0H = 0x00;
  UBRR0L = 0x67; // baud=9600
  UCSR0B = 0x10; // 00010000
  UCSR0C = 0x06; // 00000110
  DDRB |= (1<<PB5);
  PORTB |= (1<<PB5);
  while(1) {
    data = UDR0;
  }
}

```

But I don't know how to explain that char inside main makes the problem disappear...

**EDIT** Just for the record, here are two more examples. The first example works with both compilation methods. The second example works only with the second compilation method. The examples differ only with that in the first direct code is used, and in the second it is used via functions.

```
#define F_CPU 16000000UL
#define BAUD 9600

#include <avr/io.h>
void main(void) {
  char data;
  #include <util/setbaud.h>
  UBRR0H = UBRRH_VALUE;
  UBRR0L = UBRRL_VALUE;
  UCSR0B = (1<<RXEN0)|(1<<TXEN0);
  UCSR0C = (1<<UCSZ01)|(1<<UCSZ00);
  DDRB = (1<<PB5);
  while (1) {
    PORTB ^= (1<<PB5);
    while(!(UCSR0A&(1<<RXC0)));
    data = UDR0;
    UDR0 = data;
    while(!(UCSR0A&(1<<TXC0)));
  }
}

```

```
#define F_CPU 16000000UL
#define BAUD 9600

#include <avr/io.h>
void serialSetup(void) {
  #include <util/setbaud.h>
  UBRR0H = UBRRH_VALUE;
  UBRR0L = UBRRL_VALUE;
  UCSR0B = (1<<RXEN0)|(1<<TXEN0);
  UCSR0C = (1<<UCSZ01)|(1<<UCSZ00);
}
void serialSend(char data) {
  UDR0 = data;
  while(!(UCSR0A&(1<<TXC0)));
}
char serialGet(void) {
  while(!(UCSR0A&(1<<RXC0)));
  return UDR0;
}
void main(void) {
  char data;
  serialSetup();
  DDRB = (1<<PB5);
  while (1) {
    PORTB ^= (1<<PB5);
    data = serialGet();
    serialSend(data);
  }
}

```

---
Tags: serial, atmega328, avrdude, avr-gcc
---


# Question
Title: Wiring Lilypad USB + ESP8266 Serial WiFi Module
I am trying to solve the following scenario: Lilypad USB connected to WIFI through ESP8266 Serial WiFi Module.

http://arduino.cc/en/pmwiki.php?n=Main/ArduinoBoardLilyPadUSB

http://www.seeedstudio.com/wiki/WiFi\_Serial\_Transceiver\_Module

According to the wiki: I should connect to TX RX pins. None of them are present as "selectable pins", because they are built in.

This post Using LilyPad Arduino USB with LilyPad Xbee Shield talks about using SoftwareSerial something that is new to me.

Could anyone explain how should I proceed with the wiring and if possible a sample sketch just to connect the lilypad usb with the WIFI module to my personal WIFI.

**Edit:**

I found the following tutorial (spanish one but easy to follow...) where they use the Arduino UNO. I tried the example with the software serial and it worked. I saw in that tutorial sometimes the pin RST is needed. So I tried to do the same with the lilypad USB, but still didn't work.

# Answer
> 1 votes
First, upload the sketch below to your Arduino. Then, try to tie RX (pin 3) and TX (pin 2) of SoftwareSerial together. Open the Serial Monitor and send some text and see if you get it back as a response.

```
#include <SoftwareSerial.h>
SoftwareSerial Serial1(3, 2);

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

void loop()
  {
     if (Serial1.available())
         { char c = Serial1.read() ;
           Serial.print(c);
         }
     if (Serial.available())
         {  char c = Serial.read();
            Serial1.print(c);
         }
   }

```

Once you get a response, then your SoftwareSerial part is working and you can then try to connect to your ESP8266.

---
Tags: wifi, wires, esp8266
---


# Question
Title: Stop Arduino from powering LED strip when connected to USB
I have a WS2812B LED strip that is controlled by an Arduino. Normally, both the Arduino and LED strip are powered by the same 5V power supply. The 5V and GND pins of the Arduino and LED strip are connected together. If I want to reprogram the Arduino, I have to disconnect the LED strip or else it might want to try and draw power from my computer's USB.

I have a bunch of (assorted) transistors, (schottky, zener) diodes and resistors. Is there something I can build that will allow the power supply to power both the Arduino and LED strip, while the Arduino's USB can only power the Arduino itself?

I've thought about using a diode between the 5V of the Arduino and 5V of the power supply and using a resistor to pull the 5V terminal of the power supply pin low (when the power supply is not connected) but I'm not sure how stable that will be: once the diode starts conducting the resistor will have no chance to pull the pin low again and I'm not sure if the Arduino will like the voltage drop across the diode.

Obviously the external power would be disconnected before plugging the Arduino into USB. Since the LED strip runs on 5V I can't use the VIN pin.

# Answer
I'd try powering the led strip for the power-supply directly, and the arduino board via a (schottky) diode.

That way the led strip will have no power when only usb is plugged in.

The Arduino won't mind that it receive a bit less that 5v because of the voltage drop of the diode.

The only thing to look out for it sending a 5v signal to a WS2812B chip that has no power. According to the datasheet this is not allowed.

So you either need to buffer the output of the arduino going to the input of the WS2812B (e.g. using some transistors, or a simple pull-up with diode). Or, since you are not hot-plugging the usb, have the 5v from the power supply go (via a resistor) to an input on the arduino, so you can detect this in your setup routine, and have it block the rest of the code, or something.
> 3 votes

---
Tags: power, led
---


# Question
Title: Is it possible to run emulator from IC? and how?
I have an Emulator and Roms I would like to create a portable device to allow me to connect via RCA to a TV and play. Only I have no prior knowledge of how Integrated Circuits function or what they are capable of. If a IC would work, how does one go about programming one to load up the emulator? What other components aside from RCA and USB would I need? Any direction with this would be great and sorry in case I am not asking the proper questions.

I figured arduino is similar to what I am building in regards to circuitry/ electronics. Thanks in advance.

This is the only bit of information I have found online in 4 days thats not store bought. CLICK HERE

# Answer
Not a chance, I am afraid. The Arduino cannot do what you think it does.

Yes, you could *program* the Arduino to act like some of the simple old video games, but there is no way it can run a pre-existing emulator program like your computer can.

You need something more like a Raspberry Pi - in fact there is an interesting project that might be just what you want: RetroPie
> 1 votes

---
Tags: electronics
---


title: Help to decode xbee S2 API packet

text:
# Question
Title: Help to decode xbee S2 API packet
I'm new at using Xbee and I would like to get some help on how to interpret API packets. Me setup consists of two arduino unos, two xbee S2, two xbee shields and a one magnetometer sensor HMC5883L. The sensor is connected to the arduino via I2C and transmitting the data to the xbee (router) using serial communication. On the other side (coordinator) I'm reading and displaying the data on the serial monitor. I have read the data sheet of the xbee but I still can't figure how to interpret the packet. Here is a screen shot of the values that I'm getting on the serial monitor on the router and the corresponding packets on the coordinator's serial monitor.

There are four bytes that are changing each time so how can I translate them to an integer value. Any help would be greatly appreciated.

# Answer
> 0 votes
You have a bunch of "stuff", followed by the data you sent, followed finally by another bunch of "stuff". I don't know what the "stuff" is, but I can see and decode your data easily enough.

I suspect you transmitted the data using `.println(...)`. That will send an ASCII representation of the data.

So to take the line: `-196.88<CR><LF>`, if we find the ASCII values and represent them as hexadecimal we have:

> 2D,31,39,36,2E,38,38,D,A

Which I am sure you can find in one of those lines - maybe this one:

> 0,15,90,0,13,A2,0,40,C1,A8,2E,98,8D,1,**2D,31,39,36,2E,38,38,D,A**,3B

So you have 14 bytes defining something interesting about the packet (I'm sure Google can tell you what - source and destination maybe, probably a packet length too), then your data, and finally what looks like it's probably a checksum.

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


title: Remove unused boards from Arduino IDE

text:
# Question
Title: Remove unused boards from Arduino IDE
In the current project I'm programming simultaneously an UNO board and a Leonardo one.

Switching back and forth between the two boards in the **Tools** menu takes too much time because of the other 18 boards that I do not own anyway.

Is there a way to remove those boards from the Tools menu?

# Answer
> 8 votes
After some more investigation of the IDE folder, I found a text file called **boards.txt** in the following path.

```
 [Arduino Path]/hardware/arduino/boards.txt

```

EDIT: Be sure to make a copy of the file in case you mess up the following part.

Between two series of '**#**' characters there will be all the information on a specific microcontroller (e.g *uno.name=Arduino Uno*). Deleting every line of text between the two '**#**' series will have the desired effect of removing the board from the **Tools** menu.

# Answer
> 1 votes
You can open two Arduino IDE windows, and use Tools / Board to set each of them to one of the two kinds of boards you are programming. Ie, you can have multiple IDE windows open, with different options selected in each. I've programmed an Uno and a Nano device with the same program from two different windows simultaneously (ie, RX lights blinking on both boards at the same time) without problems.

You can use one USB cable and one port, or can use a separate USB cable for each window. You might need to use Tools / Port occasionally if the port number changes when you recable things.

I have the external editor option selected. Text in each Arduino IDE window updates when I click Verify or Load, rather than each time I save the file in emacs. I don't know how it works if you aren't using an external editor and have the same file open in two IDE windows.

---
Tags: arduino-ide
---


# Question
Title: Why won't the slide switches control the motor in this 123d simulation?
```
int guard = 7;
int switchPin = 6;
int motorPin = 9;

void setup(){
  pinMode(guard,INPUT);
  pinMode(switchPin,INPUT);
  pinMode(motorPin,OUTPUT);
}

  void loop(){
   if (digitalRead(guard==HIGH)&&digitalRead(switchPin==HIGH))              //&&

   {

     digitalWrite(motorPin,HIGH);
    delay(500);
    digitalWrite(motorPin,LOW);
    delay(1000);
   }
        else {

     digitalWrite(motorPin,LOW);
   }

  }

```

# Answer
> 0 votes
This should be written like this:

```
if ( digitalRead(guard)==HIGH && digitalRead(switchPin)==HIGH ) {

// Rest of the code..

}

```

---
Tags: arduino-uno, motor, transistor
---


title: Get csv field values

text:
# Question
Title: Get csv field values
I am uploading data using Thingspeak and I would like to get only values stored in a field. Is there any way to get this in a cvs http request?

When you call a cvs http url, you get:

What I am trying to get is just the value in field2: 10,10,12,12,16 without the headers.

# Answer
> 0 votes
You can use this format to achieve what you described:

```
http://api.thingspeak.com/channels/(channel_id)/field/(field_id).(format)

```

Source: http://community.thingspeak.com/documentation/api/

**Edit:** It seems that there are no available options that can do what you want. But, you can tweak the response like in this example:

```
  int i;
  String response = "created_at,entry_id,field2 2015-10-22 19:30:00,14878,5";

  for (i = response.length()-1; i >= 0 ; i--)
  {
    if (s.charAt(i) == ',') break;
  }
  String value = response.substring(i+1);
  Serial.println(value); // This will show only 5

```

---
Tags: arduino-uno
---


# Question
Title: arduino PWM temperature inexpected results
I am making a system which regulates the temperature of a plate. using the PID library I programed the system as followed:

```
/********************************************************
 * PID Basic Example
 * Reading analog input 0 to control analog PWM output 5
 ********************************************************/

#include <PID_v1.h>
#include "math.h"

int val, output2;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
PID myPID( &Input, &Output, &Setpoint,0,20,20, DIRECT);

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

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

void loop()
{
  // phase haute
  //delay(100-output2);
  val = analogRead(1);
  float mv = ( val/1024.0)*5000;
  Input = mv/10;
  myPID.Compute();
  {   output2 = map(Output, -100, 100, 0, 200);
      Serial.print("output is :");
      Serial.println(output2);
      digitalWrite(9,HIGH);
      delay(output2);
      // phase basse
      digitalWrite(9,LOW);
  }
  //analogWrite(5,Output);
  //Serial.print("input temperature is :");
  //Serial.println(Input);
  // Serial.println(Output);
  // Serial.println(Input);

}

```

As you can see in the code the output result is between 0 and 100. the temperature desired in the plate is 37 degre. and the actual temperature is 24 degre. consequently, the program supposes to set the value of the output to the max value to reach to 37 degre. But the problem is my output is setting to different values as you can see here:

what can be the problem here ? thank you in advance

# Answer
> 0 votes
As Gerben said in a comment, you should add the value of Input to the serial print, to facilitate problem diagnosis. As your question stands, one can only speculate about what the problem might be. My speculation is that the system is unable to cope with parameters (Kp, Ki, Kd) = (0, 20, 20), ie, that it's unstable and unresponsive without proportional control.

---
Tags: arduino-uno, programming, temperature-sensor
---


# Question
Title: Instead of 1 and 0, make display say On or Off
So for my project, I am making a button that turns on and off an LED, but also display the state of the led on an LCD and by Serial. But my issue is, I don't want it to just show a 0 or a 1, I want it to say On or Off.

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int inPin = 22;         // the number of the input pin
int outPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup(){
    // set up the LCD's number of columns and rows:
    lcd.begin(16, 2);
    // Print a message to the LCD.
    lcd.print("System Activated");
    //
    lcd.setCursor(0, 1);
    lcd.print("Ready...");

    pinMode(inPin, INPUT);
    pinMode(outPin, OUTPUT);

    Serial.begin(9600);
    Serial.println("System Activated");
    Serial.println("Made by Mateo Holguin");
    Serial.println("0 = Light is Off | 1 = Light is On");
    Serial.println("=======================================");
}

void loop(){
    reading = digitalRead(inPin);

    if (reading == HIGH && previous == LOW && millis() - time > debounce) {
        Serial.println("Button Switch State Change:");
        if (state == HIGH)
            state = LOW;
        else
            state = HIGH;

        Serial.println(state);
        Serial.println("");
        lcd.clear();
        lcd.print("State: ");
        lcd.print(state);

        time = millis();
    }

    digitalWrite(outPin, state);

    previous = reading;
}

```

# Answer
> 2 votes
Another option: use the "inline" *if* construct:

```
lcd.print(state ? F("On") : F("Off"));

```

The format is:

```
<if comparison> ? <true result> : <false result>

```

Note the use of `F(...)` to force the strings to stay in flash memory.

# Answer
> 5 votes
Put the strings to display in an array, and output them instead.

```
char const * const stateDisplay[] = {"Off", "On"};

 ...

lcd.print(stateDisplay[state]);

```

---
Tags: serial, c++, lcd, button, debounce
---


# Question
Title: The difference between "time_t" and "DateTime"
I've run into an issue trying to combine 2 different Arduino timer projects I've found online.

For both projects I'm using a DS3231 RTC, but have been able use the DS1307 library just fine in my code.

The first set of code I picked up started with:

```
#include <DS1307RTC.h>

```

The second set of code I tried to combine did not have this 'include', but instead used

```
RTC_DS1307 RTC;

```

as found here:

https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/understanding-the-code

As a novice coder, I'm not really sure what the difference between the above two ways to call this library. But I do know the first way using "include", if I want to access the current time on the RTC I use

```
RTC.get();

```

as opposed to the second method which requires:

```
RTC.now();

```

And while it was easy to find documentation to sync the RTC to computer time over the USB cable using this handy bit of code:

```
// Notify if the RTC isn't running
    if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running");
  }

   // Get time from RTC
  DateTime current = RTC.get();
  DateTime compiled = DateTime(__DATE__, __TIME__);
  if (current.unixtime() < compiled.unixtime()) { //CHECKS AGAINST COMPUTERTIME
    Serial.println("RTC is older than compile time! Updating");
    RTC.adjust(DateTime(__DATE__, __TIME__));  //UPDATES FROM COMPUTER IF OLD TIME IS OFF
  }

```

I can find no easy alternative using "#include DS1307RTC"

I first thought that the difference between RTC.now() and RTC.get() was just a matter of word substitution. But later on when I want to use a "time\_t" call after initializing with "RTC\_DS1307 RTC;"

```
 time_t timeNOW = RTC.now();

```

I get the error "cannot convert 'DateTime' to 'time\_t {aka long unsigned int}' in initialization"

So I'm assuming one method uses "DateTime" and one method uses "time\_t". But I'm not sure if this is the case, and if so, how to convert a "DateTime" value to a "time\_t" value.

I have two goals in writing this post.

1- Can someone please explain to me the difference between "#include DS1307RTC.h" and "RTC\_DS1307 RTC;" and how it impacts my code.

2- I'd like to stick with using ""RTC\_DS1307 RTC;", only because it seems easy to sync my RTC to my computer. But if I do, I get the above error. So can someone please tell me how to convert a "RTC now()" call to a "time\_t" value? Or is the issue more complicated than just a mere conversion between data types?

# Answer
> 12 votes
A `DateTime` is a full class with lots of methods to it - a `time_t` is just an unsigned long.

`time_t` is used to store the number of seconds since the *epoch* (normally 01/01/1970)

The Arduino *Time* library returns a `time_t` to the `now()` function - but RTCLib return s a DateTime object.

The DateTime object, though, has a `unixtime()` method which will return a `time_t` representation of the time stored in the DateTime object.

So you can do:

```
DateTime dt = RTC.now();
time_t time = dt.unixtime();

```

---
Tags: arduino-uno, timers, time, rtc
---


title: RS-232 is a protocol or a cable?

text:
# Question
Title: RS-232 is a protocol or a cable?
RS-485 and RS-232 are a type of communication protocol or a type and cable?

I studying these serial communication protocols and each place refers to the RS-232 / RS-485 in different ways. Some articles mention that it is a cable, the other a protocol, so I was in doubt.

# Answer
> 1 votes
RS-232 etc mean different things in different contexts. More specifically it is called TIA/EIA-232.

It refers to both the electrical characteristics of an NRZ signalling system, and at the same time it refers to the packet format for the transmission of data through such a system.

It also refers to the connectors that are used with such a system and, by extension, the cables that have those connectors on them.

> The standard defines the electrical characteristics and timing of signals, the meaning of signals, and the physical size and pinout of connectors. The current version of the standard is TIA-232-F Interface Between Data Terminal Equipment and Data Circuit-Terminating Equipment Employing Serial Binary Data Interchange, issued in 1997.

RS-485, or TIA/EIA-485, in contrast *only* specifies the electrical characteristics and not the data that is sent down the line. It doesn't specify any connectors to use, nor what format the data should take. For instance you can use RS-232 formatted packets, or you could use a MODBUS-RTU format that uses completely different packets. It only refers to the drivers and voltages used.

> TIA-485-A, also known as ANSI/TIA/EIA-485, TIA/EIA-485, EIA-485 or RS-485, is a standard defining the electrical characteristics of drivers and receivers for use in balanced digital multipoint systems.

---
Tags: serial, rs485
---


# Question
Title: Interfacing Arduino UNO with TFT LCD and WiFi Shield
I'm trying to interface my Arduino UNO with both a 1) TFT LCD screen and 2) WiFi Breakout board/shield. The WiFi breakout board uses many of the same Digital pins as the LCD screen so is it possible for the arduino to interface with both devices simultaneously?

I also noticed that the shield goes over the arduino, but covers the header pins. Does this mean that I can't use these pins?

I've never worked with shields or breakout boards and would like some advice before I purchase either component. If neither of these solutions will work, please provide me with alternate methods.

Your time/feedback is greatly appreciated :)

-Vip

# Answer
I agree with Chris on this. The uno is limited where it comes to pins and and ram, you should probably look at a mega, or similar.

As far as running both at once, i don't think it would be possible with the uno, with the ram limitations, as well as pin limitations, you'll be hard pressed to get them going at the same time, within the same sketch.

While technically it is possible to use alternative pins, i doubt there will be enough unused pins to shift an entire shield over to on the Uno

If you're looking for a cheaper rout, you may look at adding a secondary Uno to run the wifi, and send any data you need displayed to the uno running the tft via serial coms.
> 1 votes

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


# Question
Title: HX711 Load Cell application strange behaviour
I have an application where an HX711 ADC is used with 4 load cells. (in wheatstone bridge configuration, rated at 50kg each).

The thing is that I am trying to sense 30~ish gram changes with it accurately, while the cells will be loaded with 10 to 40 kilograms.

I have built up the circuitry and placements properly, calibrated and tested etc. but I have 2 questions that I couldn't come up with a solution.

**1st question:** When powering arduino from USB cable the readings are much more stable (they are fluctuating like +-5 grams only) but when I connect a 12V power source (with 5A output) to the arduino, the readings start to fluctuate much more. (+-30 grams or so). The HX711 is powered from arduino 5v out pin but even though i tried to power it from a 5v adapter the fluctuations seemed to happen.

I should also note that the HX711 is connected to the analog pins A0 and A1, and there are 8 other sensors connected to the pwm pins of the arduino.

Now any ideas why does that happen? Any way to prevent this fluctuation?

**2nd question:** If I calibrate with a load close to the max. weight (as suggested in many papers) the small changes seems to be very unreliable. If I calibrate it with a small weight (like around 200g) I can sense small weights properly but this time when a 2 kg weight is put it is read like 2.3kg or something. Is this normal?

I know that my load cells are not the proper ones for the application but I would like to push them as much as i can.

Thanks for your time

# Answer
1) Put your power source on an oscilloscope and check it. I assume what's happening is you don't have a clean sine, and the power fluctuates, whereas power from a PC USB port is usually very well regulated. This may be causing issues in your sensor due to under/over voltage at a minuscule level.

2) Because you're pushing your sensors to the edge of their capabilities, you're going to have to work around them, so the normal scenario's don't really offer much help, as they are usually based on working within the middle ground of capabilities.

You said that factoring based on low load vs high load created unreliable variances in your measurements, i would personally suggest calibrating not for max load, nor min load, but 2/3 of max, or 1/3 max, and see if that stabilizes you, or at least gets you somewhere to the middle of the road where your differences are nominal, or something you can live with.
> 2 votes

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


title: ESP 8266 does not respond at all

text:
# Question
Title: ESP 8266 does not respond at all
I have a ESP8266\_01, and I wired up. It does not work for me.

I have connected the ESP to an Arduino Uno. I am using a 5V pin from uP with a 3.3V regulator, and I have a voltage divider between RX(ESP) and TX(uP). And I am sure that the wiring is correct. The thing is, I am not getting anything back from ESP, not even errors. And I tried to use different baudrates as well. There is a blue LED flashing from ESP only when I am using 115200, and red LED lights up constantly at any other baudrate.

What have I done wrong here?

I did 4 hours of research already and don't know what else I can do now. If you have any idea, please leave me a word.

# Answer
Start by uploading blink sketch to your Arduino then connect it to your ESP8266 like this: TX-TX and RX-RX.

Now open Serial Monitor and send AT command and see if it responds. If so then you can control it using your Arduino by wiring it back to TX-RX and RX-TX.

PS: Don't forget to set the line ending in the Serial Monitor to Newline or Carriage Return.

**Edit:** Use this code to connect to ESP8266:

```
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  ESP8266.println("AT");
  delay(30);
  while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}

```

Since the Hardware Serial interface will be busy when connected to Computer, then you have to use another Serial interface to communicate with your ESP8266. In this case, Software Serial comes handy.
> 4 votes

---
Tags: esp8266
---


# Question
Title: In what situation would the Vin pin be attached to any of the I/O pins?
In what situation would the Vin pin be attached to any of the I/O pins?

Also, in what situation would the Vin pin be attached to an external circuit?

# Answer
> 3 votes
Vin is exactly the same as using the barrel jack (DC in) on the Arduino. You can use it when you want to power your Arduino from an external source and you don't want to have the bulk of a big power plug. It can also be used as a power output when you are using the barrel jack, for instance for powering relays or motors. It just saves on having to splice wires into the cable of a wall wart, for example.

The voltage you feed in to the Vin pin should be of the same specification as the barrel jack - that is, between 7 and 12V. From there, just like the barrel jack, it goes to the 5V regulator to provide the 5V for the board, and then on to the 3.3V regulator for low powered peripherals.

If, at any time, you power the board from the USB and have something connected to the Vin pin that consumes power you risk damaging the 5V regulator on the Arduino since power will flow backwards through it form 5V to Vin, which it really isn't meant to do. In these situations it is good to connect a diode between 5V and Vin such that the anode is on 5V and the cathode on Vin - so that if the 5V is higher than the Vin voltage then the current will bypass the regulator safely.

# Answer
> 2 votes
Vin connected to an IO pin: If you want to damage your Arduino.

Hypothetically, I could imagine a misguided attempt to detect if it's being powered from a barrel jack or from USB, but the higher voltage (and it will ALWAYS be a higher voltage if powered from that rail) is likely to damage the chip

To do that safely/correctly, you would need a voltage divider, to reduce both the voltage to a level below the +5v level.

Vin to an external circuit is very reasonable. If you have, for example, a motor that needs +12v, and your Vin is 12v, then you can provide the power for the motor from Vin, and still control it from the Arduino - you would use a transistor to turn the +5v from one of the digital pins (set to output) to 12v from Vin. This is typically what happens on a "motor driver" - for example, see http://www.hobbytronics.co.uk/image/data/tutorial/bipolar-stepper-drive.jpg \- on the left-hand side, you will see "motor supply" - this runs at a higher voltage (and is isolated from +5v and Arduino pins), and if your motor needs what the barrel jack supplies (and is no more than 12v), then Vin is perfect.

The other situation is that you can put +7v to +12v INTO the Vin, instead of using the barrel jack - this will power your Arduino.

---
Tags: serial
---


title: Matlab and Arduino Serial communication

text:
# Question
Title: Matlab and Arduino Serial communication
I'm new to Arduino and am learning how Serial communication works. I am trying to send a value from Matlab to Arduino, but it seems to be partly fruitful. If anyone can explain the difference between the acquiring input and predefined strings in Matlab Here is the program I tried, and it is successful. Arduino :

```
 %This program receives an array of chars and stores them in array and transmits them back

 const int no_of_fields = 3;
 int field_index = 0;
 int vec_to_hold[no_of_fields]; //Array to hold the numbers

void setup()
{
   Serial.begin(9600);
}
void loop()
{
   if(Serial.available())
    {
     char ch = Serial.read();
     if(ch >= '0'&& ch<= '9') //check if the received chars are digits
      {
         if(field_index<no_of_fields)
           {
              vec_to_hold[field_index] = (vec_to_hold[field_index] * 10) + (ch -'0'); //accumulate values to form and integer
           }
      }
     else if(ch == ',')
     {
       field_index++;
     }
     else if(ch == '\n')
     {
        for (int i = 0;i<min(no_of_fields,field_index+1);i++)
         {
         Serial.print(vec_to_hold[i]);
         vec_to_hold[i] = 0;
         }
        Serial.println();
        field_index = 0;
      }
   }
}

```

Here is the Matlab side of Code :

```
delete(instrfindall)
S = serial('COM3', 'BaudRate', 9600,'Terminator','LF'); %38400
fopen(S);
pause(0.1);
vec_sent = input('Enter : ','s');
fprintf(S,'%s\n',vec_sent);
pause(0.1);
t_value = fscanf(S,'%d');
disp(t_value);
delete(instrfindall)

```

The above code is working, but what if i don't want to enter the string. I want to be predefined. For example in the above matlab code

```
vec_sent = '200,300,400';

```

If i convert this line

```
 vec_sent = input('Enter : ','s');

```

to

```
 vec_sent = '200,300,400';

```

it does not work. The RX pin on the Arduino blinks indicating something is coming on the serial, but TX pin is not at all blinking, and nothing appears in MATLAB except an error stating

```
 Warning: Unsuccessful read: A timeout occurred before the Terminator was reached..

```

I would be grateful if anybody points out what I am doing wrong. Thanks in advance.

# Answer
> 1 votes
To confirm that the cause of the connection problem is not the software, you can try to connect using reliable software. Do do this, download and install the MATLAB support package for Arduino hardware: http://www.mathworks.com/hardware-support/arduino-matlab.html

# Answer
> 0 votes
The Arduino parsing code seems to function correctly. If I just use the IDE Serial Monitor window and enter "200,300,400", the Arduino replies "200300400".

The error message says that you either did not get the LF, or the LF did not arrive within 0.1 seconds.

One thing to try, as I do not have MATLAB, is to change how the Arduino replies. On the Arduino, `Serial.println` will send a CR and a LF at the end. Perhaps you should just do the LF explicitly instead:

```
for (int i = 0;i<min(no_of_fields,field_index+1);i++)
{
  Serial.print(vec_to_hold[i]);
  vec_to_hold[i] = 0;
}
Serial.print( (char)10 ); // just LF, not CR/LF with println
field_index = 0;

```

This will test whether the CR is causing a line termination problem in MATLAB.

Another possibility is that the `pause(0.1)` is too short. The documentation states that this is highly dependent on the OS timer resolution. Try `pause(1)`. This will test whether the time is too short. At 9600, 0.1s is only 100 character times.

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


# Question
Title: Arduino Mega failure after first use of Mega Shield power connector
I have an XDRduino Mega clone with ATmega2560 and ATmega16U2 USB support chip. I also have a Sensor Shield (same vendor), which provides screw terminals to Vin and Ground.

I connected the board with USB, loaded "Blink", and then changed the time interval. Next I connected a 20x4 LCD using the Sensor Shield and a breadboard and loaded LCD "Hello world". All seemed fine with the new board.

Each time I powered on or reset the Mega, the TX and RX LEDs flashed a couple of times and then my sketch started running.

Then I disconnected it from the PC (no USB for power anymore) and connected a (working from another project) S-60-12 power supply, DC Output 12V 5A to the shield screw terminals. I verified polarity -V to GND, +V to VCC.

OK, I swear I hooked it up correctly. But if you tell me that hooking it up backwards would explain all the symptoms below, then yes I'll believe you that I screwed up {sob}.

(And yes, you're right, there is no diode protection on Vin, just on the dc power jack. Dummy me. Double dummy me, as there was a screw type power plug laying unused on the bench {groan}.)

About 4 seconds later, I heard a snap and immediately pulled the plug on the power supply. Yes, something probably smoked, but let's refine at bit, please.

I moved the Mega to my PC, (disconnecting the external power supply so to use only USB for power). It is no longer recognized as a USB device, and the Arduino IDE (1.6.5) no longer finds the USB serial port.

Voltages at 3.3V pin and 5V pin are correct. I've also probed the regulator and comparator and all looks well for the power circuitry. F1 is not blown (or there would be no power as USB is the only source).

Item: The TX and RX leads are on solid. I expected them to flash then turn off. (Power LED is on solid, which is normal.)

Item: The reset pin for the Mega reads 1.41 V. It's connected through a 10K pullup to +5 V (reads 4.63 at USB pin, 4.53 at the 5V pin). ***This seems way too low.***

Item: The reset pin for the 16U2 reads V+ (4.35) and is has a 10K pull-up.

Item: AREF is 50 mV. I believe it should be 1.1 V or 2.56 V.

Question: Is it reasonable to think the 2560 may be dead, and the LEDs are on because the 16U2 can't talk to it? **Any way to test this theory?**

(If the 16U2 were bad, it would still be possible to program the 2560 via the ICSP header, thus salvaging something...)

Question: The 16U2 won't do the USB connection dance with the PC because the 2560 is dead? **Should the 16U2 to try to connect no matter what the state of the 2560?.**

Question: **If the 16U2 is dead, should TX and RX LEDs be lit?**

Question: **If I had reversed the hookup, should not the regulator (P1117 chip) have saved me?**

Question: **Has anyone else had a failing component** (other than the 2560 & 16U2) **with these symptoms?**

# Answer
> 1 votes
I want to make this obvious to the casual reader: Mega Sensor Shields -- all versions I've data on -- run the power connector to +5V.

The power connector ***is not power in***, as defined by the base board. In fact, there is no direct way to get to the base board regulator from the shield. (A pin exists for Vin, but it isn't connected to anything on the shield. It's mechanical support.)

It's intended to supply more current to devices connected via the shield than the base board does.

There is a jumper that disconnects the sensor shield +5 rail from base board power to allow independent ***+5 volts distribution*** to the shield attached devices.

# Answer
> 0 votes
If what i read is correct, then you've probably cooked your duino.

As for what exactly failed, i'm going to guess from your description, that one or both of the capacitors failed. Usually when they blow, you'll hear a loud snap like you describe.

I would suggest testing those, and replacing them if they are faulty.. This is no guarantee that other components weren't damaged, but it's a good place to start.

As for why the LED's may still light up, that could be any number of reasons really, and not a particularly good indicator of what exactly failed.

---
Tags: sensors, power, shields, usb
---


title: Understanding transistor datasheets

text:
# Question
Title: Understanding transistor datasheets
I'm trying my best to understand and utilise questions that already exist as well as other websites, however I just wanted to check the circuit I've come up with (which is a very simple switch circuit) will work.

I plan on using a BD139 transistor, although I haven't purchased anything yet, so can change to anything really.

The fans are each 0.09A at 12V. I've calculated that R1 should be 360ohms. The 5V control will be coming from an Arduino. I believe it's within the specs of the transistor. Ic max is 1.5A.

Does the circuit look correct? Are there any changes I should make?

# Answer
For saturation you should assume hfe to be 10. This gives:

(5V − 0.85V) / ((0.09A ⋅ 3) / 10) = 154 Ω

Consider using a 150-220Ω base resistor instead. And since a fan is an inductive load, don't forget the flyback diode from the collector to the +12V rail. A 1N4000 series diode should be fine for this small a load.
> 2 votes

---
Tags: transistor
---


# Question
Title: Read Voltage at PWM off time, and Current at PWM on time
For a battery charging project, i am using an ARDUINO UNO which is driving a buck converter to provide the battery with the charging current. I am using external ADCs to measure the battery's charging voltage and current. The test setup is working fine, but right now i am just measuring the voltage and current at random time instants. However to measure it correctly, battery voltage reading should be done at an instant when the controller's PWM output is LOW (OFF duty cycle), and battery current reading should be done when PWM output is HIGH (ON duty cycle). So i was thinking how i can do that, since i am using analogueWrite() function to give PWM output, i thought if i could access analogueWrite() fucntion, may be i could there insert the function of read\_ADC\_Voltage() during the LOW time, and read\_ADC\_Current() during the HIGH time.

Is my approach right ? If yes then can please anyone tell me how can i access and use this analogueWrite() function ? And if someone has any other idea to do the readings correctly, please suggest. I shall be grateful.

# Answer
Add a pin-change-interrupt (PCI) handler (See eg PinChangeInt at arduino.cc); clear the flag and enable the interrupt whenever you want to take readings, and disable that PCI after you have the reading. As noted in the link, PCIs are available on all signal pins (possibly not on A6 and A7 on the 328), so are available on any of the PWM pins.
> 1 votes

# Answer
P.S I am writing it as an answer since my code wont fit in comment

I looked into interrupts and learned about them that there are 2 types of interrupts in Arduino namely "external", and "pin change". So i downloaded the "PinChangeInt Library" to test it. I wrote a small program where a PWM of 62.5kHz is being generated on pin3, and i am calling rising and falling edge triggered interrupts on this pin, i.e to display one value when rising edge occurs, and other value when falling edge occurs. My code looks like following:

```
    #include <PinChangeInt.h>
    #define pw 3
    int pwm;

    void setup() {
      // put your setup code here, to run once:
      pinMode(pw, OUTPUT) ;
      pwm_setup();             // Set PWM to a frequency of 62.5kHz

      PCintPort::attachInterrupt(pw,rise,RISING);    // call void rise() when PWM is HIGH
      PCintPort::attachInterrupt(pw,fall,FALLING);   // call void fall() when PWM is LOW

      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      pwm = 127;                                                // 50% duty cycle
      pwm_on(pwm);

    }
    void pwm_setup()
    {

      TCCR2A = 0x23 ;
      TCCR2B = 0x09 ; // mode 7, clock prescale by 1
      OCR2A = 256-1 ;  // 256 clock periods = 16us per cycle
      OCR2B =0 ;
      TCNT2 =0 ;

    }
    void pwm_on(double)
     {
        OCR2B = pwm ;
     }

    void rise()
    {
      Serial.println("RISE");
    }

void fall()
{
  Serial.println("fall");
}

```

But it is not working the way i think it should. It keeps on displaying "fall" every time, whereas according to me it should display "RISE" and "fall" alternatively, right ? However if i remove the "PCintPort::attachInterrupt(pw,fall,FALLING); " line, it starts to display "RISE" as it is supposed to.

Since its my first time programming with Arduino, and i am just a beginning level programmer, i might be making some stupid mistake here. So can you point it out please ?
> 1 votes

# Answer
No, in my opinion changing functions in the Arduino Core is not a good approach. You would have to change it back for any other project you are going to do and secondly, if you insert a function in the part where analogWrite is low it will result in a change in the duty cycle. Which may not be a big problem, but just don't.

My advice would be to use a timer to run a callback function every x seconds. Then in that function temporarily set the PWM to 0 and read your values. This is indeed not the most efficient approach, but we're talking about microseconds here... This approach is completely intterupt driven so you could run other things while it is running it's PWM and checking the voltage periodically.

It sounds as if you have gotten pretty far by yourself, so I'm not going to write you example code. You can a tutorial on how to use a timer to periodically call a function here.
> 0 votes

---
Tags: arduino-uno, pwm, analogwrite, adc
---


# Question
Title: Plotting a real time graph of sensor data from Arduino on Processing, MatLab or Python
I have an accelerometer connected to my Arduino Due to spit out data on my serial monitor as described in my earlier post. I'm trying to find a sketch I could use to plot a continuous real-time graph on either Processing, MatLab or using Python MatPlot.

The accelerometer data is stored in arrays of `xArray[k]` for the x-coordinate values, `yArray[k]` for the y-coordinate values and `zArray[k]` for the z-coordinate values. How can I plot a real-time graph of these values? Thanks in advance.

# Answer
I hope this is helpful to you.

First, you need to read about serial communication between matlab and arduino. You need to establish communication between those two first.

Then take note of the format of the data coming out of your Accelerometer. In my case, I'm working with IMU and my data format is as an example: #YPR = 2.34, 13.23, -2.20

Then, from Matlab, you need to write a script to be able to read this string and identify any floating-point value.

This is what I did in Matlab. YPR = Yaw, Pitch, Roll

```
data = fscanf(s);              %Read Data from Serial
[Y(count),P(count),R(count)] = strread(data, '#YPR = %f,%f,%f');

```

Then you have to set up the plot and force matlab to update the plot in real time.

```
%set() is used to set graphic object properties
       set(plotGraph1,'XData',time,'YData',Y,'color','r');
       set(plotGraph2,'XData',time,'YData',P,'color','g');
       set(plotGraph3,'XData',time,'YData',R,'color','b');
       drawnow;           %force matlab to updata plot instantaneously

```

The link below is a good place for you to get going. But you need to make some modifications to it though.

https://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/
> 1 votes

# Answer
```
 import serial #import Serial Library
 import numpy  # Import numpy
 import matplotlib.pyplot as plt #import matplotlib library
 from drawnow import *

 accelX = []
 accelY = []
 accelZ = []

arduinoData = serial.Serial('COM4', 115200)
plt.ion()    #Tell matplotlib you want interactive mode to plot live data
cnt = 0
def makeFig():         #Create a function that makes our desired plot
#plt.ylim(0,1000)                #Set the limit on the y axis
plt.title('Sensor data')         #Set the title
plt.grid(True)                   #Set The grid
plt.ylabel('Axis Acceleration')  #Label the y axis
plt.plot(accelX,'ro-', label='Raw X Acceleration') #Set the line plot
plt.ylim(0, 1000)
plt.legend(loc = 'upper left')
plt2 = plt.twinx()  #Create a new object of plt2
plt2.plot(accelY, 'b^-', label='Raw Y Acceleration')
#plt2.ylim(0,1000)
plt2.legend(loc='center right')
plt2.ticklabel_format(useOffset=False) #Compel matplotlib not to autoscale
#plt3 = plt.twinx()
plt.plot(accelZ, 'go-', label='Raw Z Acceleration')
plt.legend(loc='upper right')
plt.ylim(0,1000)

 while True: #While loop that loops forever
   while(arduinoData.inWaiting() == 0):   #Wait here until there is data
    pass #do nothing
arduinoString = arduinoData.readline() #read the line of text from serial
dataArray = arduinoString.strip().strip('\n')  #Split into an array
# Ensure that you are not working on empty line
if arduinoString:
    dataArray = arduinoString.split(",")
# Ensure that index is not out of range
if len(dataArray) > 1:
    xAxis = int(dataArray[0]) #Convert first element to int insert in xAxis
    yAxis = int(dataArray[1]) #Convert second element to int insert in yAxis
    zAxis = int(dataArray[2]) #Convert third element to int insert in zAxis
    print xAxis, ",", yAxis, ",", zAxis
    accelX.append(xAxis)   #Build our x axis array by appending to accelX
    accelY.append(yAxis)   #Build our y axis array by appending to accelY
    accelZ.append(zAxis)   #Build our z axis array by appending to accelZ
    drawnow(makeFig)       #Call drawnow to update our live graph
    plt.pause(.0000001)
    cnt=cnt+1
    if(cnt>50):
        accelX.pop(0)
        accelY.pop(0)
        accelZ.pop(0)

```
> 1 votes

# Answer
MATLAB has a free add-on for connecting to Arduino hardware.
> 1 votes

---
Tags: arduino-due, accelerometer, python, matlab
---


title: SIM900 Modem is not responding

text:
# Question
Title: SIM900 Modem is not responding
I'm working with arduino nano and it has interfaced with SIM900 GSM. I'm sending "AT\r" to GSM modem, but not getting response.

```
void setup()
{
  Serial.begin(9600);
  Serial.println("Setup is Ready");
}

void loop()
{
   Serial.write("AT\r");
   delay(1000);
   if(Serial.available() > 0)
   {
     Serial.println("Data received");
     Serial.println(Serial.read());
   }

}

```

Serial monitor:

Setup is Ready

ATATATATATATATATATATATATATATATATATAT

I've set the 9600 baudrate to modem and my rx and tx is connected correctly... What is the problem?

Thanks

# Answer
> 2 votes
You should not use the same Serial interface to debug and talk to your SIM900. You should use a SoftwareSerial interface to talk to the SIM900 and use the hardware Serial to send response back to your computer.

Try this code:

```
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of SIM900
const byte txPin = 3; // Wire this to Rx Pin of SIM900

// We'll use a software serial interface to connect to SIM900
SoftwareSerial SIM900(rxPin, txPin);

void setup() {
  Serial.begin(115200);
  SIM900.begin(9600); // Change this to the baudrate used by SIM900
  delay(1000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  SIM900.println("AT");
  delay(30);
  while (SIM900.available()){
     String inData = SIM900.readStringUntil('\n');
     Serial.println("Got reponse from SIM900: " + inData);
  }
}

```

# Answer
> 1 votes
You aren't talking to the SIM900. You are just communicating with the serial monitor.

---
Tags: serial, gsm
---


# Question
Title: Assemble or typecast byte array to float
The serial port on my Arduino Mega is receiving 3 floats as bytes (total of 12 bytes, 4 per float) over serial. Unfortunately I cannot assemble the 4 Bytes in a float, as the serial monitor only displays

`0.00`

`0.00`

`0.00` etc.

Here is the code:

```
void serialEvent2() {
  if (Serial2.available() > 11) {
    byte yawData[3];
    yawData[0] = Serial2.read();
    yawData[1] = Serial2.read();
    yawData[2] = Serial2.read();
    yawData[3] = Serial2.read();
    float yawAngle = *((float*)(yawData));
    Serial.println(yawAngle);

    byte pitchData[3];
    pitchData[0] = Serial2.read();
    pitchData[1] = Serial2.read();
    pitchData[2] = Serial2.read();
    pitchData[3] = Serial2.read();
    float pitchAngle = *((float*)(pitchData));

    byte rollData[3];
    rollData[0] = Serial2.read();
    rollData[1] = Serial2.read();
    rollData[2] = Serial2.read();
    rollData[3] = Serial2.read();
    float rollAngle = *((float*)(rollData));
  }
}

```

I made sure the data coming to Serial2 is not `0`.

**UPDATE:** The initial mistake was my byte array not being sized correctly. I fixed it. The values I print are fine until after about a second, they get totally weird. Dropped bits/Bytes maybe? Seems odd because a sample sketch written in Processing works perfectly while taking the exact same input.

# Answer
> 3 votes
I tried the code below and it worked for me, don't miss the `delay()` part:

**Sender Code:**

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

void loop() {
    float yaw = 10.5;
    float pitch = 20.15;
    float roll = 100.10;
    float ypr[3];
    ypr[0] = yaw;
    ypr[1] = pitch;
    ypr[2] = roll;
    Serial.write((byte*) ypr, 12);  // No new-line
    delay(1000);

}

```

**Receiver Code:**

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

void loop() {

}

void serialEvent() {
    if (Serial.available() == 12){
      byte yawData[4];
      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawAngle = *((float*)(yawData));
      Serial.println(yawAngle);

      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawPitch = *((float*)(yawData));
      Serial.println(yawPitch);

      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawRoll = *((float*)(yawData));
      Serial.println(yawRoll);
    }
}

```

**Results:**

# Answer
> 2 votes
If you must do it that way I'd recommend using a `union`:

```
typedef union {
    float val;
    uint8_t bytes[4];
} floatval;

floatval v;
v.bytes[0] = Serial2.read();
v.bytes[1] = Serial2.read();
v.bytes[2] = Serial2.read();
v.bytes[3] = Serial2.read();
Serial.println(v.val);

```

A better solution is to just write and read the raw float data:

```
// Sender:
Serial.write((const char *)&myfloat, sizeof(float));

// Receiver
Serial2.readBytes((char *)&myfloat, sizeof(float));

```

Even better still is to define a `struct` which is the packet of data you wish to send:

```
typedef struct {
    float yaw;
    float pitch;
    float roll;
} attitude;

attitude myatt;
myatt.yaw = 14.9;
myatt.pitch = 23.4;
myatt.roll = 11.49;

Serial.write((const char *)&myatt, sizeof(attitude));

// receive:

attitude myatt;
Serial2.readBytes((char *)&myatt, sizeof(attitude));
Serial.println(myatt.yaw);
Serial.println(myatt.pitch);
Serial.println(myatt.roll);

```

# Answer
> 0 votes
try use memcpy, i think it might work:

```
void serialEvent2() {
  if (Serial2.available() > 11) {
    byte yawData[4];
    float yawAngle = 0;
    yawData[0] = Serial2.read();
    yawData[1] = Serial2.read();
    yawData[2] = Serial2.read();
    yawData[3] = Serial2.read();
    memcpy(&yawAngle, &yawData,sizeof(float));
    Serial.println(yawAngle);

    // same for others ...
  }
}

```

# Answer
> 0 votes
What if you write

```
yawData[3] = Serial2.read();
yawData[2] = Serial2.read();
yawData[1] = Serial2.read();
yawData[0] = Serial2.read();

```

i.e. you change the endianness of the representation

---
Tags: serial, data-type
---


# Question
Title: How to destroy my Arduino with I/O pins?
What are the most common ways of destroying a Arduino using the I/O pins?

Also, in what situation would it be acceptable to attach the positive or negative end of a power supply to an I/O pin?

# Answer
There are many ways to destroy an Arduino, check out this article, 10 Ways to Destroy An Arduino.

> 1. Shorting I/O Pins to Ground
> 2. Shorting I/O Pins to Each Other
> 3. Apply Overvoltage to I/O Pins
> 4. Apply External Vin Power Backwards
> 5. Apply \>5V to the 5V Connector Pin
> 6. Apply \>3.3V to the 3.3V Connector Pin
> 7. Short Vin to GND
> 8. Apply 5V External Power with Vin Load
> 9. Apply \>13V to the Reset Pin
> 10. Exceed Total Microcontroller Current
> 1 votes

# Answer
> What are the most common ways of destroying a Arduno using the I/O pins?

Over-voltage and over-current.

Over-voltage involves putting too high (or too low) a voltage onto an IO pin. Over-current involves trying to source (or sink) too much current through an IO pin. Both can be fatal.

> Also, in what situation would it be acceptable to attach the positive or negative end of a power supply to an I/O pin?

**"Positive":** When that power supply is no more than 5V and shares ground with the Arduino and you want to know if it's on or not, or measure the voltage (Analog Input). Anything more than 5V will require a voltage divider to bring the voltage down to 5V.

**"Negative":** If by that you mean the ground terminal, and that ground terminal is shared with the Arduino ground, then you can do it any time - but why would you, since you'd just be connecting to the Arduino ground since they are one and the same. If it's not the ground terminal but a potential *below* ground, then never unless you use some circuitry to raise that potential above ground for measuring it.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Giving the impression of a dying device - making a vibrating motor slow down and stop
I'm trying to make a gag gift for a friend. The effect I'm trying to imitate is of a device that starts up for a moment and then putters out like something is wrong.

So I need it to: 1. Vibrate a motor for a second or two. 2. Make the vibration sputter out. 3. Light up an LED behind an error message on a paper screen.

I have very little hands on experience with anything electronic, but I have some programming and I took enough physics to know what a capacitor, etc is.

My questions are whether an Arduino is a good and cost effective way to accomplish this and is there any beginner friendly advice anyone can give me to get this accomplish

# Answer
> 1 votes
You can control the motor using PWM (Pulse Width Modulation) and make it run for full, then slowly decrease the speed till stop and after light up the led. This tutorial from Adafruit could be a good start if you are not familiar with PWM and have also some good advices: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview

Please be really careful about the supply source. Motors can easy draw more current then the limited available from the pins of arduino. Maybe a H-bridge could be helpfull here.(take a look at this for example of h-bridge: https://learn.adafruit.com/adafruit-raspberry-pi-lesson-9-controlling-a-dc-motor/lm293d )

---
Tags: led, motor
---


# Question
Title: How to send volume +/- on Mac/OSX from Leonardo
I saw this answer but I can't find the analog for Mac.

I've tried cycling thru keycodes from 0x01 thru maybe 0x500, and I went thru ascii a few times, also found brightness up/down, and `F11`, `F12`, but they get pressed **with fn key by default** which makes them do operations other than vol +/-.

# Answer
> 2 votes
Could you just untick the "Use all F1, F2, …" in System Preferences -\> Keyboard?

Just wondering if that would be an option and if doing so would create the desired outcome.

# Answer
> 1 votes
Unfortunately, `Fn` is hardware and it is handled internally by the keyboard to do something hardware-based without sending any code. So the short answer is: you can't simulate Fn key with arduino.

What I think of as a solution is:

* Create a program on your Mac that can listen for keyboard scan codes to do vol +/- or any other function.
* Send a custom scan code from Arduino to your Mac ( a scan code that isn't part of the standard scan codes ).
* When your listening program receives that code, it should do Vol +/- (or anything else )...

---
Tags: arduino-leonardo, keyboard, mac-os
---


# Question
Title: LCD Pin Numbering vs I2C Controller Pin Numbering vs Sketch
I've been playing with an Arduino Uno, trying to get a 16x2 LCD screen to work with an I2C controller. I've got this LCD screen and this controller. And I've been trying to get the sketch below to work.

```
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7,3,POSITIVE);//, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup()
{
    lcd.begin(16,2);
    lcd.backlight();
    lcd.setCursor(0, 0);
    lcd.print("Hello world!");
    lcd.setCursor(0, 1);
    lcd.print("Row number: ");
    lcd.setCursor(12, 1);
    lcd.print("2");
}
void loop()
{

}

```

I've used an address scanner to verify that the address is correct (39 \[0x27\]), but it still won't display anything. It lights up, and I've tried adjusting the contrast, but it just won't display any characters.

I'm wondering if the definition of which pins are which is correct, but I can't seem to find anything detailing how the numbers used in the sketch correlate to the pins on the controller, which then correlate to the pins on the LCD screen. If any body can give me some insight I'd appreciate it.

# Answer
> 1 votes
Yes, the pins can be different depending on the LCD and the controller. My favorite solution to this is to run a simple "i2c guesser" sketch that can be downloaded from the following forum thread (download link is at the bottom of the first post): http://forum.arduino.cc/index.php?topic=260510.0

With that sketch it usually only takes me a couple minutes to find the correct pin numbers.

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


title: ISR not working as it is supposed to

text:
# Question
Title: ISR not working as it is supposed to
For a battery charging project, i am using an ARDUINO UNO which is driving a buck converter to provide the battery with the charging current. I am using external ADCs to measure the battery's charging voltage and current. The test setup is working fine, but right now i am just measuring the voltage and current at random time instants. However to measure it correctly, battery voltage reading should be done at an instant when the controller's PWM output is LOW (OFF duty cycle), and battery current reading should be done when PWM output is HIGH (ON duty cycle).

I looked into interrupts and learned about them that there are 2 types of interrupts in Arduino namely "external", and "pin change". So i downloaded the "PinChangeInt Library" to test it. I wrote a small test program where a PWM of 62.5kHz is being generated on pin3, and i am calling rising and falling edge triggered interrupts on this pin, i.e to display one value when rising edge occurs, and other value when falling edge occurs. My code looks like following:

```
    #include <PinChangeInt.h>
    #define pw 3
    int pwm;

    void setup() {
      // put your setup code here, to run once:
      pinMode(pw, OUTPUT) ;
      pwm_setup();             // Set PWM to a frequency of 62.5kHz

      PCintPort::attachInterrupt(pw,rise,RISING);    // call void rise() when PWM is HIGH
      PCintPort::attachInterrupt(pw,fall,FALLING);   // call void fall() when PWM is LOW

      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      pwm = 127;                                                // 50% duty cycle
      pwm_on(pwm);

    }
    void pwm_setup()
    {

      TCCR2A = 0x23 ;
      TCCR2B = 0x09 ; // mode 7, clock prescale by 1
      OCR2A = 256-1 ;  // 256 clock periods = 16us per cycle
      OCR2B =0 ;
      TCNT2 =0 ;

    }
    void pwm_on(double)
     {
        OCR2B = pwm ;
     }

    void rise()
    {
      Serial.println("RISE");
    }

void fall()
{
  Serial.println("fall");
}

```

But it is not working the way i think it should. It keeps on displaying "fall" every time, whereas according to me it should display "RISE" and "fall" alternatively, right ? However if i remove the "PCintPort::attachInterrupt(pw,fall,FALLING); " line, it starts to display "RISE" as it is supposed to.

Since its my first time programming with Arduino, and i am just a beginning level programmer, i might be making some stupid mistake here. So can anyone point it out please ?

Your helpful comments and suggestions would be appreciated. Thankyou!

# Answer
> 1 votes
Here are a few items to consider.

1. From `#define pw 3` you are working with PD3, INT1. As one of the Atmega328 Uno's two external interrupts, INT1 supports RISING and FALLING events separately. Pin change interrupts (PCIs) on pins other than 2 or 3 of the Uno won't separate them and in the interrupt routine (one interrupt routine in that case, not two) you will need to test which occurs by reading the pin.
2. Serial communication depends on interrupts and won't work in an interrupt handler. Instead, set a flag (via a volatile byte variable) to test in your `loop()`.
3. For testing, put `pwm_on(pwm)` in `setup()` instead of `loop()`.
4. In `loop()`, compute `seconds = milli()/1000` and if `seconds != prevsec`, set prevsec=seconds, enable your PCI or external interrupt, then enter a loop that waits for a flag and takes a reading. Or, in the interrupt handler, both set a flag and take a reading into a volatile variable.
5. If you only need to measure the quantities a few times per second, or a few times per minute, you could just busy-wait for the condition, then trigger a sample-and-hold, then convert analog to digital via `analogRead()`.

Regarding sample-and-hold: Unless you change the ADC sampling rate, `analogRead()` will take up to 100 microseconds per reading. If your input waveform is 62.5 KHz, it will toggle about about six times while being measured, which if measured directly is likely to give a random result. However, if you use a sample-and-hold circuit, you can hold the ADC input constant until your measurement completes.

An alternative to using a sample-and-hold is changing the ADC sampling speed. See post #5 in thread Faster Analog Read? on forum.arduino.cc. If you get the sample time down to 8 to 12 microseconds you can do ok with a busy-wait method. Ie, when your code wants a reading, it has a loop that measures the PWM line over and over, and starts an ADC conversion shortly after the PWM gets to the state desired for the measurement.

---
Tags: arduino-uno, pwm, interrupt
---


title: Python script to toggle LED's

text:
# Question
Title: Python script to toggle LED's
I have 8 LED's connected to a shift register on my arduino uno r3. I am trying to write a Python3 script that will prompt a user to select one of the LED's and then prompt to toggle on or off.

Should be pretty basic but I cant seem to get this working.

I have already botched my code trying to get this running:

the jist of my python script is

```
import serial
import os
import time

os.system('clear')

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

while True:
    led = input("Which LED do you wish to operate? (press x to quit): ")

    if led >= '0' and led <= '7':
        print("Operating LED # %s" % led)
        ser.write(str.encode(led)) # sends the choice of led to arduino'
        on_or_off = input("Do you want to turn it on or off (press 0 for off and 1 for on): ")

        if on_or_off == '0':
            #send command to arduino to turn off the selected LED
            print("Command sent to arduino to turn OFF LED %s" % led)
            ser.write(str.encode(on_or_off))
        elif on_or_off == '1':
            #send command to arduino to turn on the selected LED
            print("Command sent to arduino to turn ON LED %s" % led)
            ser.write(str.encode(on_or_off))
        else:
            print("Please enter 0 or 1 to operate the LED. ")

    elif led == 'x':
        ser.close()
        break
    else:
        continue

```

For some reason Arduino is only dealing with the first input...

HEre is my loop code on the arduino

```
void loop() {
  if(Serial.available() > 0){
    led = Serial.read(); // from python script the led to operate
    led = led - '0';
    if(led >= '0' && led <= '7'){
      if(Serial.available() > 0){
        ledState = Serial.read(); // expects the led state next
        ledState = ledState - '0';
        if(ledState == '0'){
          shiftWrite(led,LOW);
        }else if(ledState == '1'){
          shiftWrite(led,HIGH);
        }
      }
    }
  }
}

```

shiftWrite is a function I wrote because there are 8 LEDS hooked to a shiftRegister

***update:***

I tried the state machine suggestion and it didnt work...

```
  void loop() {
  while(Serial.available()){
    led = Serial.read();
    led = led - '0';
    if(led>= 0 && led <= 7){
      state = 1; //We've received the LED # go to state 1
      Serial.println(led);
      Serial.println(state);
      Serial.println(ledState);
      continue;
    }
    if(state == 1){
      ledState = Serial.read();
      ledState = ledState - '0';
      if(ledState == '0'){
        shiftWrite(led,LOW);
      }else if(ledState == '1'){
        shiftWrite(led,HIGH);
      }
      state = 0; //Ended the operation return to state 0
    }
  }
}

```

With the serial monitor in the arduino IDE open (not running the python script) I tried this input: 4,1

This is my output on the serial monitor:

```
4
1
0
1
1
0

```

Any ideas? Basically the same problem as before...I actually thought the state machine idea would work...

# Answer
Try this code, it is working as intended:

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

int state = 0;
int led;
int ledState;

void loop() {

  while (Serial.available())
  {
    if (state == 0)
    {

      led = Serial.read() - '0';
      if(led >= 0 && led <= 7)
      {
        state = 1;
        Serial.println("Got LED number: " + String(led));
        break;
      }
    }
    if (state == 1)
    {
        ledState = Serial.read() - '0';
        if(ledState == 0)
        {
          Serial.println("LED n " + String(led) + " is now OFF");
        }
        else if(ledState == 1)
        {
          Serial.println("LED n " + String(led) + " is now ON");
        }
        state = 0;
    }
  }

}

```
> 1 votes

# Answer
You're assuming that the microcontroller is going to wait until you choose LED state, which is wrong. Try this:

```
int state = 0;
int led;
int ledState;

void loop() {
  while (Serial.available())
  {
    if (state == 0)
    {
      led = Serial.read() - '0';
      if(led >= 0 && led <= 7)
      {
        state = 1; // Here we have got the LED number, go to state 1
        continue;
      }
    }
    if (state == 1)
    {
        ledState = Serial.read() - '0';
        if(ledState == 0)
        {
          shiftWrite(led,LOW);
        }
        else if(ledState == 1)
        {
          shiftWrite(led,HIGH);
        }
        state = 0; // Here we ended the operation, return back to state 0
    }
  }

}

```

You need what we call a state machine, here I use `state=0` for the state corresponding to choosing LED number, `state=1` is for the state that waits for the operation ON/OFF.
> 1 votes

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


title: Arduino Part Needs Identified

text:
# Question
Title: Arduino Part Needs Identified
I do not know what part this is. I ordered an Arduino beginners kit and this part was not labeled. Please help!

# Answer
> 1 votes
It seems that it is an MPU6050 Module 3 Axis Accelerometer Gyroscope Module for Arduino.

Learn more: http://playground.arduino.cc/Main/MPU-6050

---
Tags: hardware
---


# Question
Title: How to connect MCP4141 digipot and a data logger shield to the same Arduino board
The main problem here is that they both need to communicate via the Arduino's SPI bus, and I know that each of the two devices will need its own CS pin (The data logger is hard wired to 10, so the digital potentiometer will need a different one)

This would be fine, except that the digital potentiometer has one pin for both SPI and SDO. I read that to connect this to the Arduino, the shared pin on the digipot needs to be connected to the MISI pin on the Arduino (pin 12) and then to bridge the MISO pin to the MOSI pin with a resistor.

Would anyone be able to tell if this will work. I do not want to try connecting the two devices like this just in case it breaks something in the board.

Thanks

# Answer
I have done the same thing in the past for a DS1302 RTC that uses the same communication system. Yes, it works. Will it interfere with the other communication though? Quite possibly. It works fine for *half duplex* communication, but could cause interference with something else on the bus that is *full duplex*.

If in doubt, and you're not worried about high speed or high efficiency (you're not changing the potentiometer's value often) then use three other pins and bit-bang your own half duplex serial interface - it's not hard.
> 1 votes

---
Tags: arduino-uno, shields, arduino-nano, spi
---


title: Problem with for loop

text:
# Question
Title: Problem with for loop
I'm having trouble with the syntax of code. I want to have the motor turn when the next average the program measures is 100 or more greater than the previous average it measured. I don't know how to write the if statement:

```
if(average == (average>=100)) {
for(pos = 0; pos <= 120; pos += 1) {
  sServo.write(pos);
  delay(50);
}
for(pos = 120; pos >= 0; pos -= 1) {
  sServo.write(pos);
  delay(50);
}
}

```

# Answer
> 0 votes
The motor should

> turn when the next average the program measures is 100 or more greater than the previous average it measured

So simply write it:

```
// Old average is called "average"
// Compute the new average and put it in next_average
if ((next_average - average) >= 100)
{
  // Turn the motor
}
average = next_average;

```

---
Tags: programming
---


# Question
Title: Diode lights generate false interruptions
I have spent quite a considerable time debugging my code that was triggering false interruptions. I have found out that the source of the error were the diode lights (on the picture). I would like to ask if anyone can point me to the possible source of such behaviour.

I will try to explain really briefly what the issue was providing only needed (from my point of view) details. If you would require more - tell me.

So, I have a board that looks like this:

You can see two reed switches (close circuit in the presence of a magnet) which leads the `INT0` (pin 2) and `INT1` (pin 3) on arduino to trigger an interruption on their `RISING` behaviour. The pull down resistors are 1kOhm. This cirquit works perfectly.

The original version of this circuit had lights in positions `D5-D10` and `D19-D24` (between the reed switches and the connections to the interruptor pins). The lights are these:

The part of the circuit with the red light (connected to `INT1`) worked flawlessly, while the circuit with the green light (connected to `INT0`) every once in a while triggered a false interruption in `INT1`. The lights, however were always blinking correctly.

I have nearly no experience with circuits and hardware, so a pointer on where to start reading to understand the issue is also welcome. Hope to hear from someone who knows what the cause could have been. I would still like to use the lights somehow, because they give a nice feedback on what is happening to the system.

Thanks!

PS. I do not think the code is necessary here, but I will post it too if you like. I am however quite confident that the bug is not on the software side.

# Answer
> 2 votes
Aaaaah, ok, now I see...

You put

> +5V - Reed - LED - input pin - 1k resistor - ground

right?

If so the problem is that a red led has (usually) a voltage drop of about 1.5V, while the green one has a voltage drop of 1.8V-2.0V. The Atmega 328P has a Vih (i.e. the minimum voltage needed for a reliable high) of 0.6\*Vcc, so for a 5V supply this value is 3V.

Consequently with a green LED you will have a value TOO CLOSE to the minimum acceptable value for the input pin. Note that the 2.0V value is an usual one, but different leds have different voltages.

Moreover the so-called high-brightness leds (the ones with a transparent case) have a more-than-3V voltage drop, so if you put for instance a blue led you will never receive a signal.

To solve the problem, you have three solutions:

1) use a (low brightness) red led also for the green path 2) remove the led from that path and drive it directly with the arduino (you will have also the notification that arduino has understood the command) 3) change the path to

> +5V - Reed - input pin - LED - 1k resistor - ground

(i.e. take the voltage BEFORE the led, not after)

I think it'll work then :)

EDIT: according to the data I found on the internet the red led is usually 1.8V, while the green one is usually 2.1V. This does not change my answer, anyway.

And... You won't "fry" your pins with the 5V you are prividing to the circuit....

---
Tags: arduino-uno, interrupt, debugging, resistor, components
---