text:
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.

void main(void) {   #include <util/setbaud.h>  This caught my eye. It's quite unusual to do an include within the code? I'm not sure if it might cause issues.

Also, I'm not sure how watchdog is related to this question? You can disable it's fusebit?

and your if (data) PORTB |= (1<<PB5); will flip the LED on and off whenever data is set to something. You should reset the value? Even though the while(!( might block it from happening.

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

No, Like I said in my answer on EE, this has nothing to do with the Bootloader or the WDT. You seem to not understand fundamentally how this whole thing works...

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.

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);
  }
}

This may be related to a strange thing I was seeing when manually compiling that I just couldn't fathom - there seemed to be no crt0 being linked in, except if you had a global variable, which caused just the BSS portion of the crt to exist. If I added another function to the program suddenly that function became the entry point instead of main(). It was all messed up and completely brain melting.  And yet I was calling the same compiler and command line options as compiling for the Arduino API. It made no sense at all.

Actually I just solved my problem - and it will probably solve yours too.  I'll post an answer with the detail.

@Majenko: Yes, it solved the problem!

@Majenko: But I did not understand the reason why it spontaneously starts to reset itself, and what your commands do to fix it. Could you please give some recommendations for further reading to understand what causes the problem and how it is cured?

With the WDT, once it has started firing it's almost impossible to disable it. You can only disable it from "cold" so it never gets a chance to fire.  Also without the proper startup code (crt0) it's anyone's guess what will actually happen with the program when it's run - variables won't be initialized, exception vectors won't be set up, etc etc.


text:
Algorithm to detect motion using ultrasonic sensor
I have a PIR sensor which sometimes give false readings and I have added a ultrasonic sensor to compensate for that. I think my algorithm can work, however currently it is very prone to give false positives.
Algorithm theory
My idea is to have an arduino which will obtain six samples and wait 25 milliseconds between each sample and then calculate the variance. If the variance exceeds a specific threshold, which I have set to a thousnad, it will send an motion event over the serial bus.
Problem with the algorithm
Ultrasonic sensors can give faulty responds which usually isn't hard to detect. My HC-SR04 sensor can only accurately read the distance between 2 cm and 400 cm. All the faulty readings are usually way over 400 cm or lower than 2 cm, therefore if is not within these boundaries a new try will be made to get a value within the boundaries, if it fails for three times it will assume the distance is exactly 400 cm.
It is redundant to wait for more than 23280 µs because 400*29.1*2 is the corresponding microseconds it would take for the distance to be 400 cm. pulseIn has a timeout value which can be used for this.
In theory this sounds great to me but very often this algorithm will erroneously send motion events. My belief for this is that when the ultrasonic sensor transmitts a wave and wait for it come back, pulseIn will timeout and retry and yet again ask the sensor to send a wave. This happens before the first wave has come back thus the distance will be incorrect and vary from time to time making the variance higher than my threshold.
If the distance is much lower than 4 metres my algorithm works very well.
What I tried
I figured I might be able to block for some time until the echo pin on the ultrasonic sensor turns low or a time of 100ms has passed. The code hanged and I couldn't communicate with my arduino any more. I can't see the problem with my code to obtain the distance pursuant to the ultrasonic sensor.
for(tries=3;tries;--tries) {
  digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
  delayMicroseconds(2); // Let signal settle.
  digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
  unsigned long time = micros();
  while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
    if((micros() - time) >= 100000) {
      continue;
    }
  }
  if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
    return ((float)(duration)/2.0) / 29.1;
  }
}
return 400.0f;

This just blocks my program indefinently and I had to upload a new program removing that code for my arduino to respond again.
So my question boils down to: how can I resolve this issue where my algorithm very frequently sends motion events erroneously? Is there a better way to detect motion with an ultrasonic sensor?
(EDIT: I was really tired when I wrote the code above and Majenko corrected me, I changed the code for this
for(tries=3;tries;--tries) {
  digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
  delayMicroseconds(2); // Let signal settle.
  digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
  unsigned long time = micros();
  while(PINB & 0b00000010) { // ECHO_PIN is PB1 or digital pin 9
    if((micros() - time) >= 100000) {
      goto retry;
    }
  }
  if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
    return ((float)(duration)/2.0) / 29.1;
  }
  retry:
  continue;
}
return 400.0f;

The main blocking part of your code is this bit:
while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
  if((micros() - time) >= 100000) {
    continue;
  }
}

That is saying "While the echo pin is low, check the time.  If too much time has passed then carry on with the loop".
So basically that will loop until the echo pin goes high, regardless of the time.
The continue command means to jump back to the beginning of the loop that it's in, be that a while, for, or do loop.  In this case it jumps back to the beginning of the while loop it's in.
Instead you should consider using break, which means "Terminate this loop and carry on with what comes next".

Ultrasound sensing with pulseIn(), while simple to perform is rarely particularly accurate.  Any interrupts that occur during the sensing will affect the outcome, and it's only as accurate as the micros() function allows it to be.
If you need a more precise and reliable measurement you should consider using one of the Input Capture modules in the ATMega.  I don't know if there is a library to do it off hand, but programming it through the registers shouldn't be that difficult - just read the datasheet to find out how it all works.
Briefly the operation of IC is:

Send trigger pulse
Start IC timer counting
Pulse arrives
IC stops counting automatically and interrupt is triggered
Read counter value and convert to microseconds.
Set flag to indicate a result is available

The timing source is the main system clock and counting happens in the background completely parallel to the operation of the CPU, so nothing can interrupt it or delay it. Even if the execution of the IC interrupt routine is delayed by another interrupt running the counter value will have already stopped incrementing, so it will have been "captured" and give the correct result every time.

Thanks it didn't give me any better results though, see my updated question please.

@Linus I have added an edit to my answer about doing more reliable and accurate measurements.

Thanks, I'll definently look in to Input Capture modules. Is it gauranteed to never give faulty values? Should I still check the boundaries and clamp to 116 and 23280 ?

@Linus It can't hurt to check the boundaries.  It should always give good results, but of course it's somewhat dependant on the reliability of the ultrasound module. It will certainly give more reliable results than pulseIn().

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


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

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.

Yes I'm going to solder it manually as I got it from a local store for $4. I also got an active antenna (this one : http://www.aliexpress.com/item/1575-42MHZ-Magnetic-base-GPS-active-Antenna-with-SMA-Plug-connector-for-GPS-receivers-and-Mobile/1531700595.html ) and I'll really appreciate your help if you can tell me how to connect this antenna with above mentioned gps module again I do not have any breakout module and I have to done it manually.

that is an active antenna so it means you need to connect more than one pin to the gps module. At page 11 you can see the small schematic to connect the antenna

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Arduino Nano v3.0 with ESP8266
I am attempting to connect and use an ESP8266 board with my Arduino nano v3.0 and I am not have much luck.
I have read a bunch of tutorials and articles, the most recent is http://elektro-blogger.blogspot.co.nz/2015/07/arduino-and-esp82666.html
Any help would be greatly appreciated.
I have connected it like below and am using some simple code to try and get it working.

Code:
#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);

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

  Serial.flush();

  esp8266.print("AT+RST\r\n"); // reset for esp8266
  delay(500);
  esp8266.flush();//clear serial1
  // Check AT
  esp8266.print("AT"); // reset for esp8266
  esp8266.print("AT+CIFSR\r\n");// learn the ip which token for esp8266
  delay(500);
  if (esp8266.find("ready"))
  {
    esp8266.flush();
    esp8266.print("AT+CIFSR\r\n");
    delay(500);
    Serial.println("CIHAZ IP ADRESI:" + esp8266.readString()); // print esp8266 ip

  }
  else
  {
    Serial.println("there is no internet connection");
  }
  esp8266.print("AT+CIPMUX=1\r\n");//ser mux 1 so we want to connect as multiple users
  delay(500);
  if (esp8266.find("OK"))
  {
    Serial.println("Mux ok");
  }
  else
  {
    Serial.println("MUX failed");
  }
  esp8266.print("AT+CIPSERVER=1,23\r\n");// set esp8266 as server
  delay(500);
  if (esp8266.find("OK"))
  {
    Serial.println("SERVER started");
  }
  else
  {
    Serial.println("SERVER failed");
  }

}
void loop()
{

  if (esp8266.available())
  {
    Serial.print(esp8266.readString()); // get message which comes from clients.
  }
}

At a glance, your picture shows that you've connected RX to RX and TX to TX. They need to be swapped, so that each module receives what the other transmits.

To expand on that, I'm not sure if the logic lines of the ESP can handle 5V of the arduino. (5V exceeds the 3.3V, that could cause some problems)

@FuaZe are you suggesting separate 3.3v power ?

@Rennex Thanks for that. I will test it out tonight.

@Yonkee I'm suggesting a TTL logic converter or a resistor-divider on the logic lines. As the logic (Rx/Tx) may not be 5V tolerant.

Did you get anywhere with this?

I'm using this exact combo of nano and esp8266 but I picked up these real cheap to handle the 5v to 3.3v difference. http://amzn.to/1Qz27S2  You should too or eventually you'll blow the esp8266.

The Esp8266 module has different firmware, the old one was running at 9600 and the new one is running at 115200.
Try to upload this code on  your arduino Nano and send AT commands over the Serial monitor of the Arduino.
If you send AT it should returns "OK", if not, try to swap RX to TX and try to play around with the baudrate 9600, 57600, 115200.
It might be that your Wifi module doesnt have any firmware loaded which might need to be done.
#include <SoftwareSerial.h>

SoftwareSerial wifi(10,11); // RX, TX

void setup()
{
Serial.begin(9600); // FTDI
wifi.begin(9600); // GPS; 9600 first time, 38400 second time
}

void loop()
{
if (Serial.available())
wifi.write(Serial.read());
if (wifi.available())
Serial.write(wifi.read());

}

Thanks for the answer. I will test this out when I get home. I will reflash my ESP board to make sure the firmware is up to date.

I have the same problem. I had no results in running your code. Do you know how to load a new firmware on to the ESP board?

If I am not wrong, you need to short a pin then you power it, the device boots up in a special mode where you can upload a different firmware. Further info you might want to see some youtube videos.

Do not Connect your ESP8266 Module Directly to an Arduino Board, Always try your best to use Divider resistors for better communication. you need to use Arduino IDE serial Monitor Window for ESP8266 setup instead of writing At Commands in Source Code. I successfully Setup My ESP8266 Module by using just Arduino Nano and Arduino IDE Serial Monitor.
Download Simple Source Code and List of Necessary AT Commands

Remember that ESP8266 Uses 3.3v logic and arduino 5v. So use a voltage divider to get 3.3v at esp8266 rx pin. Also esp8266 must be connected rx->rx tx->tx to communicate with pc and rx->tx tx->rx to communicate with arduino.

I would suggest against using nano provided 3.3V. Instead use regulator separately to power it up and connect grounds. ref bbs.espressif.com/viewtopic.php?t=133


text:
Battery Solution for ESP8266 and HC-SR04
I'm working on a project that includes an ESP8266 (requires 3.3v input (250 mA peak)) and a HC-SR04 (requires 5v 20 mA peak). I'm making it battery/solar powered.
I'm trying to keep costs down as well as make a system that works reliably and has good longevity.
I'll be waking the device every 15 minutes and keeping it in deep sleep at the other times.
Originally I was going to use a battery source over 6v, like a 6 cell AA rechargeable battery pack, a 10v or so solar panel, and a breadboard type voltage regulator that conveniently provides 3.3v and 5v on the same board. This seems to waste a decent amount of power though.
Right now I'm looking into using a 2 AA rechargeable NiMH batteries, a 5v solar panel, a 3.3v step up voltage booster, and a 5v step up voltage booster. 5v step up voltage boosters are everywhere and cheap because of their uses for portable cell phone chargers. 3.3v step up voltage boosters on the other hand are more expensive and harder to find.
Looking for any advice or affirmation that I'm on the right path. Thanks!

You can probably reconfigure a boost converter for 3.3v, and definitely find one intended more for the sort of thing you are trying to do, though perhaps not as a discount module.  You may however need to put some thought into the enable input for the boost converter, what it may draw when inactive, what you are going to cause the timed wakeup, and what that is going to run on.

You could use a 5v boost converter, and then use a voltage regulator to bring it down to 3.3v. I'd probably use a higher voltage battery and go with a buck converter. I think those are a bit more efficient. Also take a good look at the quiescent current of those voltage converters. As the quiescent alone can drain your battery pretty fast with nothing attached.

A time a go when searching for some circuit to provide power to ESP and also being capable of charging batteries I came across this reply here. Is intended for usb charger/Li-Ion batteries but maybe it could suit your needs too and be adapted. In the output the circuit presented there, you could use some LDO like  MCP1825S (or even the MCP1825 with extra information possibilities). Never test the circuit yet, so can not provide any good answer about how long it provides juice to ESP.


text:
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 :

JEELIB
ENERLIB
SLEEP_N0M1
NARCOLEPTIC
ADAFRUITSLEEPY_DOG
LOW_POWER_MASTER

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?
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 ?
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 @!

"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.
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.
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).

So if I right for question 2. the answer is that 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 ?

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 ?

Tank you very much for your answers my friend !


text:
Unsure how to connect the anode in this circuit
I am making a game of X and O’s and ran out of pins on the Arduino. After searching on the internet I found out about connecting it in a grid connecting all the anodes in columns and the different colours in rows but I don't know how to connect the anodes so it only turns on only one of the LEDs rather than the other 2 in the grid if they are all connected to ground. The wires I am unsure to connect are the orange ones in the diagram below (bottom left corner). Note the Red on the RGBs are not used so don't need to be connected

Firstly, you have made the classic rookie mistake with your circuit regarding your LED current limiting resistors.  You have one per LED group instead of one per LED within a group.  The arrangement you have at the moment means that at best some LEDs will be dim or not light at all, and at worst will result in LEDs burning out.
There should be a resistor in every red, green and blue wire in your diagram.
As for what to do with the three orange wires (once you have re-arranged the resistors) they connect to three spare IO pins on the Arduino - you then turn each column on or off as you need - only one column is on at a time.  If you need more than 20mA for a column (which is highly likely with up to 9 LEDs on at a time) then those lines should be connected to either +5V or GND (depending on if you are common anode or common cathode) via transistors and the transistors should be switched by the IO pins.

So you just connect it to the 3 analogue pins and how would you code it if it would normally go to the ground

If they are common cathode (normally connect to ground) then set a pin HIGH to turn a column off, or LOW to turn it on.  Cycle through them nice and fast.

Thanks for the help but I ended up abandoning this project in the end


text:
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?

you can definitely use a somewhat small transistor (600mA) for that. search the web for "arduino relay interface", choose a circuit, subsitute the relay with your solenoid, and you're done.

That ebay solenoid does not distinguish in its "datasheet" between its pull and hold power consumption; not does it list real and apparent/total power. Good luck sizing a transistor for that. Also if I multiply their stated current and voltage (presumably to get total power), I get less than their stated real power.

@RespawnedFluff: Since it's a DC solenoid there'll be no difference between its pull an hold power consumption except for the moment when it's first connected to the 12 volt supply.  Also, since it's DC,  it'll have a power factor of 1 and there won't be any "apparent power" associated with it. Finally, 12volts, DC, times 0.6 amperes is 7.2 watts, precisely what they state.

@EM Fields: They state 7.5W. Also look up some real solenoid datasheets and see that the activation voltage is a few volts below the nominal one, which makes their calculation even more dubious. And no, even for a DC solenoid you have different pull and hold currents. http://electronicdesign.com/analog/what-s-all-solenoid-driver-stuff-anyhow

@RespawnedFluff: Agreed on the 7.5 watt number. However, since there'll never be anything pulling on the plunger, the hold power will be irrelevant and all that'll matter will be the 7.2 watt pull-in power required to get it moving against the spring.

@EMFields: Are you saying the hold power is zero? What makes the lock return when the solenoid coil is deenergized? Some spring maybe? Doesn't the Hooke force of that need to be defeated by the solenoid in its hold position?

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.


text:
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;
}

}

If you smelled burning, doesn't it maybe stand to reason that there might be a hardware issue? And yet you show us code in some unknown API that no one else here has a hope of knowing what it is. I suggest you re-think your question...

Well yes, but I included the code just in case. The fact is that I can't find any hardware issues. There are no shorts in the wires, everything is grounded. I'm stumped with the hardware so I included the code in case someone could see a glaring mistake.

How can we tell? No one else but you and your tutor knows that API. Maybe you should SHOW us your hardware so we can be the judges of if there is something wrong or not.

Did the magic smoke come out? If not, there's still hope.

Have you tried loading the 'Blink' sketch to just the Nano, without anything else attached?

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:

Your port is not working so simply switch to a different USB port
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.


text:
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("");
    client.println("");
    client.print("Value: ");
    if (valueReady()) {
      client.println( getValue() );
    } else {
      client.println( "Not available" );
    }
    client.println("");
    client.println("");

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?

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.

It's often a good practice to send debug information (flashing LED's or sending a string) at startup. The vaguest problems (, power issues and some memory issues) can be spottend this way.


text:
Counting minutes in arduino
I have a dipswitch of 4 steps to get a binary number that will turn out to decimal from 0 to 15, So I need to get that number and make it the ammount of minutes to make something and also be aware of some input while the time runs out.
So I was thinking of having a variable being equal to millis() and then dividing it by 60,000 which is a minute in millis and If I get an integer that must mean a minute has passed, the problem is that I don't know how to check if the result is an integer or a float.
any advice?

Your method is completely wrong.
You need a variable that contains the value of millis() at the start of your period, whenever that may be (when the switches change? when a button is pressed? since the Arduino was powered up?) and compare that value to the current value of millis().  When the difference between them is greater than or equal to 60000 * 15 then 15 minutes have passed.
Look at BlinkWithoutDelay in the Examples menu in the IDE - it showcases the technique for you.

well, the input from the dipSwitch is received in the void setup, as soon as you turn on the arduino. I've tried to use the blink without delay but I'm not sure how to count the minutes, i've even tried changing the interval to the input of the dipSwitch but it's only driving me crazier

To my understanding you want to make some sort of device that will count X min. To get X you configure the 4 dip switches to get the time (0000 - 1111 or 0 - 15). The easiest way is to configure 4 pins to INPUT_PULLUP then you wire your switch to those pins and to ground. If the pin is grounded (switch in the on state) it will register a 0 and if the pin is NOT grounded (switch in the off state) it will register a 1.
note: if all switch are "off" you will get a max value of 15 based on my example.
long startTime;
void setup(){
    pinMode(7, INPUT_PULLUP); //8bit
    pinMode(6, INPUT_PULLUP); //4bit
    pinMode(5, INPUT_PULLUP); //2bit
    pinMode(4, INPUT_PULLUP); //1bit

    startTime = millis();
}

void loop(){
    long inputTime = 0;

    if(digitalRead(7))
        inputTime += 8;

    if(digitalRead(6))
        inputTime += 4;

    if(digitalRead(5))
        inputTime += 2;

    if(digitalRead(4))
        inputTime += 1;

    inputTime = 60000*inputTime;

    if(millis() - startTime <= inputTime){
        //X min has passed -- Do something here if you like

        startTime = millis(); //reset the timer
    }else{
        //Time not yet reached -- Do something here if you like
    }
}


text:
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

Could you add the value of Input to the serial print?

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.

you are right jwpat7. after changing the value of Ki. the output works very well, and the value of it is setting to the max which is 200.

@zakaria, I meant to call the first parameter Kp instead of Ki (and your 0 value for Kp was why I referred to "without proportional control") and have now corrected that in my answer.  That is, the parameter order in the PID constructor is (&inputreading, &controloutput, &setpoint, Kp, Ki, Kd, direction).  Glad it worked!


text:
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?

Are you sure the shield takes 12V? You didn't supply a  link to its circuit diagram. I suspect it is intended for 5V.

The shield is just a giant break-out box.
It contains no active and only two passive components (LEDs and their current resistors) replicating those on the Arduino itself (because installing the shield hides them).
All the rest is header pins and edge connectors and PCB traces.  For example, the power terminals I used to connect the supply just feed back to Vin and Gnd.

@jippie
I lied.  There is also a push button switch replicating the reset button on the base Audrino because the shield covers the base.
BTW, the shield was "clean".  I'd removed all the leads to my breadboard, so only the pins were showing.  And there wasn't a paper clip or wire shard visible (to me) that could have shorted the pins.
The shield still works, to the extent that the power led lights (on both the shield and the Arduino itself).
Link to shield board.

How did you verify the power strip is connected to V(IN)?

Excellent question.  I trusted the internet instead of metering it out.  DummyPoints++.  Taking meter in hand, power goes straight to +5v.  It doesn't go to Vin.  Much is explained!!!

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.

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.

You're right, it's cooked.  Both chips got 12v right through Vdd/Vcc, cause I didn't verify that "power" meant Vin.  LEDs must be on because the chip pins/paths "melted" to ground.


text:
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.

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.


text:
How to read a higher voltage digital input?
Lets suppose I have a circuit with a car battery, a switch and a led. The led will turn on when the switch is closed, and turn off if it's not. I want to remove the led from the circuit and put an Arduino in that place to "read" when the circuit is closed or open.
I'm a good programmer, so the code is not the real problem. I only want to know how to do this without damaging the board.
How can I do this?

Lookup voltage dividers.

@Gerben What should be the destination voltage to enter into a digital input pin on the arduino? 5v?

5v indeed. But I'd leave a bit of margin.

As @Gerben says, voltage dividers are a good place to start. To elaborate on the topic, you can use a combination of voltage dividers, zener diodes and clamping diodes.
This EE.SE post has some good info about this, related to ADC, but still the same.
First off, a voltage divider circuit is easily found on the internet,

Google
Wikipedia

This circuit from Hyperphysics shows the basics:

To add more protection to this so as not to go over the max I/O voltage of the MCU, you can add a zener diode on the Vout.
That would give you something like this(Olins):

This will give you the desired range to give legitimate High and Low on an I/O.

If you wanted to forgo the voltage divider and zener you can use clamping diodes to the microcontroller supply voltage Vcc. This will give a range that will not damage the I/O.

simulate this circuit – Schematic created using CircuitLab
The 10k resistor is there to limit the current through the diodes, which are Schottky diodes.

Another method, which I have used before and is reliable, is to use a diode and two resistors like below:

The logic is that, when the input IN is > Vcc(5V) the signal on the I/O _IN will be the voltage of the pull_up resistor R2, if it is low or floating the signal will be low. R1 also gives a known logic state if the input floats.
Edit: Changed the image to proper logic flow.

Be careful that the IN and _IN pins in the last circuit are "logically" swapped, i.e. the signal goes RIGHT to LEFT: IN is the input, _IN is the microcontroller

@frarugi87 - I copied it straight from a schematic I'm working on(makes sense to me, as I did it ;)), thanks for pointing it out, I will edit it tomorrow when I get a chance.

Of course, but it took me a while to understand it ;) anyway thank you for sharing, I'll tkeep it in my mind next time I'll need this kind of converters ;)


text:
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.

Is your hope to get just the content of field2 via the HTTP request? Or are you looking for a way to parse the data to get the content of the field?

I woud like to get just the content of field2 via HTTP request to integrate data into an array of chart library that only accepts thins kind of data.

Where you wrote, “i would like to get only values stored in a field.Is there any way to get this in a csv http request?.When you call a csv http url,you get: created_id,entry_id,field1,field2 2015-10-22 19:30:00,14878,18,5 ,what i am trying to get is only the value in field2: 5 without headers”, does  “csv” stand for comma separated values or is it some other acronym?  Please edit your question and make it more understandable.

The csv url data comes with comma separated values and all data is the first field when they opened with excel.I have edited the question and added a picture to show the format.

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

Hello. Thanks for your reply. I already tried that option through the following url:https://thingspeak.com/channels/(channel_id)/fields/field2.csv?key=***&results=1 ,but the final result is:
created_at,entry_id,field2 2015-10-22 19:30:00,14878,5,so i don't know if there is more url options to get only 5 value.
Thanks.

It seems there are no options like that, but you can always try my answer.


text:
Occasional incorrect time returned by NTP
I have an Uno with CC3000 wifi shield and am trying to use the sntp.h library to get NTP time. I have been experimenting with a modified version of the ntpTest code from the library which fetches the time every minute. In the serial monitor I get the correct time MOST of the time. However at random intervals, the time will display 3 hours and 14 minutes ahead of the current MST time.
the SNTP client constructor looks like this:
sntp mysntp = sntp(NULL,"time.nist.gov", (short)(-7 * 60),(short)(-7 * 60), true);

The time will display correctly for two to ten minutes and then display one of the erroneous times once then revert to correct time.
EDIT
Here is the pared down code from the Adafruit CC3000 WIFI shield ntpTest example. Note that the only reason I was getting the time so often was just teaching myself how it worked and I noticed this odd behavior. My intent was not to make an application that would, in the end, access NTP servers more than once per day.
    /***************************************************
  This is an example for the Adafruit CC3000 Wifi Breakout & Shield

  Designed specifically to work with the Adafruit WiFi products:
  ----> https://www.adafruit.com/products/1469

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Kevin Townsend & Limor Fried & Rick Lesniak for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

/*

This example does a test of the SNTP (Simple Network Time Protocol) client:
* Initialization
* SSID Scan
* AP connection
* DHCP printout
* SNTP time synchronization
* Extract and print current time and date information

*/

#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
//#include "utility/NetTime.h"
#include <string.h>
#include "utility/debug.h"
#include "sntp.h"

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                                         SPI_CLOCK_DIVIDER); // you can change this clock speed but DI

#define WLAN_SSID       "CompsciWifi"   // cannot be longer than 32 characters!
#define WLAN_PASS       "005276DA"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

//Arguments to SNTP client constructor:
//  1 - Primary Network Time Server URL (can be NULL)
//  2 - Secondary Network Time Server URL (also can be NULL)
//  3 - Local UTC offset in minutes (US Eastern Time is UTC - 5:00
//  4 - Local UTC offset in minutes for Daylight Savings Time (US Eastern DST is UTC - 4:00
//  5 - Enable Daylight Savings Time adjustment (not implemented yet)
//
//sntp mysntp = sntp(NULL, "time.nist.gov", (short)(-7 * 60), (short)(-7 * 60), true);
sntp mysntp = sntp(NULL, "time-a.timefreq.bldrdoc.gov", (short)(-7 * 60), (short)(-7 * 60), true);

// Type SNTP_Timestamp is 64-bit NTP time. High-order 32-bits is seconds since 1/1/1900
//   Low order 32-bits is fractional seconds
SNTP_Timestamp_t now;

// Type NetTime_t contains NTP time broken out to human-oriented values:
//  uint16_t millis; ///< Milliseconds after the second (0..999)
//  uint8_t  sec;    ///< Seconds after the minute (0..59)
//  uint8_t  min;    ///< Minutes after the hour (0..59)
//  uint8_t  hour;   ///< Hours since midnight (0..23)
//  uint8_t  mday;   ///< Day of the month (1..31)
//  uint8_t  mon;    ///< Months since January (0..11)
//  uint16_t year;   ///< Year.
//  uint8_t  wday;   ///< Days since Sunday (0..6)
//  uint8_t  yday;   ///< Days since January 1 (0..365)
//  bool     isdst;  ///< Daylight savings time flag, currently not supported
NetTime_t timeExtract;

#define pF(string_pointer) (reinterpret_cast<const __FlashStringHelper *>(pgm_read_word(string_pointer)))

const prog_char   janStr[] PROGMEM = "January";
const prog_char   febStr[] PROGMEM = "February";
const prog_char   marStr[] PROGMEM = "March";
const prog_char   aprStr[] PROGMEM = "April";
const prog_char   mayStr[] PROGMEM = "May";
const prog_char   junStr[] PROGMEM = "June";
const prog_char   julStr[] PROGMEM = "July";
const prog_char   augStr[] PROGMEM = "August";
const prog_char   sepStr[] PROGMEM = "September";
const prog_char   octStr[] PROGMEM = "October";
const prog_char   novStr[] PROGMEM = "November";
const prog_char   decStr[] PROGMEM = "December";

PROGMEM const char* const monthStrs[] = { janStr, febStr, marStr, aprStr, mayStr, junStr,
                                          julStr, augStr, sepStr, octStr, novStr, decStr};

const prog_char   sunStr[] PROGMEM = "Sunday";
const prog_char   monStr[] PROGMEM = "Monday";
const prog_char   tueStr[] PROGMEM = "Tuesday";
const prog_char   wedStr[] PROGMEM = "Wednesday";
const prog_char   thuStr[] PROGMEM = "Thursday";
const prog_char   friStr[] PROGMEM = "Friday";
const prog_char   satStr[] PROGMEM = "Saturday";

PROGMEM const char* const dayStrs[] = { sunStr, monStr, tueStr,  wedStr,
                                        thuStr, friStr, satStr};

/**************************************************************************/
/*!
    @brief  Sets up the HW and the CC3000 module (called automatically
            on startup)
*/
/**************************************************************************/
void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  //Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitialising the CC3000 ..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    while(1);
  }

  /* Optional: Update the Mac Address to a known value */
/*
  uint8_t macAddress[6] = { 0x08, 0x00, 0x28, 0x01, 0x79, 0xB7 };
   if (!cc3000.setMacAddress(macAddress))
   {
     Serial.println(F("Failed trying to update the MAC address"));
     while(1);
   }
*/

  /* Delete any old connection data on the module */
  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  /* Attempt to connect to an access point */
  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);

  /* NOTE: Secure connections are not available in 'Tiny' mode! */
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /*Serial.println(F("UpdateNTPTime"));
  if (mysntp.UpdateNTPTime())
  {
    Serial.println(F("Current local time is:"));
    mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);*/

    /*Serial.print(timeExtract.hour); Serial.print(F(":")); Serial.print(timeExtract.min); Serial.print(F(":"));Serial.print(timeExtract.sec); Serial.print(F("."));Serial.println(timeExtract.millis);
    Serial.print(pF(&dayStrs[timeExtract.wday])); Serial.print(F(", ")); Serial.print(pF(&monthStrs[timeExtract.mon])); Serial.print(F(" ")); Serial.print(timeExtract.mday); Serial.print(F(", "));Serial.println(timeExtract.year);
    Serial.println(timeExtract.yday + 1);
  }

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

    mysntp.UpdateNTPTime();
    mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);
    Serial.print(pF(&dayStrs[timeExtract.wday])); Serial.print(F(", ")); Serial.print(pF(&monthStrs[timeExtract.mon])); Serial.print(F(" ")); Serial.print(timeExtract.mday); Serial.print(F(", "));Serial.println(timeExtract.year);
}

void loop(void)
{
    mysntp.UpdateNTPTime();
    mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);
    Serial.print(timeExtract.hour); Serial.print(F(":")); Serial.print(timeExtract.min);

    delay(60000);
    Serial.println();
}

Try to figure out if it is either corrupted data, or a math overflow.  3 hours and 14 minutes isn't quite as interesting a number as four hours and 15 minutes would be, but could still be intriguing.  Are you certain the intervals are truly random?  It would be great if you could somehow monitor the data directly from the wifi shield (or else at at the access point) and even better if you could set up a fake server to repeatedly cycle through the same times and see if it is repeatable.  But the real solution may be careful inspection of the whole chain of operations.

Here's what I suggest you do: Make a copy of your code, and remove, a little at a time, any code not directly related to your sntp issue. There are two possible outcomes: either the problem will vanish, in which case, find the minimum change to make the problem vanish. If the problem does not vanish, post the remaining code here - I would expect you would have maybe 10-20 lines left (if you get that far).

PS - you probably shouldn't be polling time servers too often - unless your device powers down, you should be keeping a local clock. NTP is for stopping your clock from drifting, not to save you from having to keep a local clock. I would not expect an Arduino to need to poll NTP more than once a day. By keeping a local clock, you can also check if the clock is off - it shouldn't drift 3 hours, between polls.

@AMADANON-inc I I think the code is pretty minimal already but I will try removing what I can and see what happens. I agree that the end product has to be using NTP as intended. This was just a weird phenomenon I  observed while exploring the use of a wifi shield. It made me concerned that I must be missing something that would be important when eventually using NTP to correct time drift.

@ChrisStratton that sounds a little above my skill set. It might be good to try but I am going to try and eliminate other possibilities first. Thanks for the insight though.

@techkilljoy, once you are down to minimal code, post it here, so we can try to reproduce the problem. Usually in a case like this, there is a subtle problem with code; when you are working on the code, it's often hard to see exactly what's wrong.

@AMADANON-inc, sorry for the holiday-induced delay but here is the pared down code listed below the EDIT line above

It may be easier to start by building the minimum NTP application and confirming that that works. Use just the NTP library and a sample sketch or an example from the NTP library. Start with something that is as simple as possible or that is known to be good.

The updated NTP test sketch assumes that the communication with the NTP server will not fail but as the NTP protocol is based on UDP the reply package can be lost. A possible correction to the updated sketch is to check the return value from UpdateNTPTime().
void loop(void)
{
    if (mysntp.UpdateNTPTime()) {
        mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);
        Serial.print(timeExtract.hour);
        Serial.print(F(":"));
        Serial.println(timeExtract.min);
        delay(60000);
        Serial.println();
    }
}

Cheers!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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.

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.


text:
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

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


text:
Should long wires be kept separated from each other, to reduce interference?
Let's say someone has four CAT5 cables that are running along the ceiling for the length of a room (30 feet), of which most of the twisted pairs are connected to Arduino input/output pins on one end. Would it be okay to keep these wires bundled together when running along the ceiling? Or is it safer to keep them separated by a few inches? Is interference usually a problem only in very specific situations, or should it be considered for all long wire runs?
How about if there is a telephone cable (hooked up to a landline telephone) running along the same length? Is there any chance of interference if this is too close to the Arduino cables?
How about if there are 120v mains lines running the same length? Should these be kept at a distance from the Arduino cables?
On the other end of the cables that are hooked up to the Arduino, some of the following are connected: temperature sensors, light sensors, servo motors, LCDs, relays, and push-buttons.

Wouldn't it be better to have another Arduino at the sensors, and have this Arduino communicate with the other using e.g. RS485? That way you only need 4 wires (2 for power, 2 for communication). You also fix in case of RS485 (differential pair), or at least have the interference only on a single protocol. Alternatively use shielded CAT5/6 cables.

I like this idea, and try to use it whenever possible (I already have 1 Arduino at the other end to control an LCD, so that it only needs 4 long wires instead of 9). But because I reprogram the main Arduino so frequently, and because it needs to be connected via ethernet, that's why I need it close to the computer for now.

I just wanted to note that I'm not currently having any interference issues. I was just interested in learning what the best practice is. I'm planning on running another long CAT5 cable soon when I expand my system (planning on implementing an automatic indoor-garden control), and I just wanted to make sure I wasn't setting myself up for trouble later on.

A benefit of using CAT-5 is that the pairs are twisted.  You would want to look at how you are using the pairs so that you're not introducing cross talk inadvertently, but the twisted pairs tend to resist RFI which is why its used.  Telephone wire, however, can be a completely different story.  You may find some that is twisted pair, but most if it is simply flat cable.  Worse, much of it is very cheap flat cable with what amounts to a piece of thread with a very thin foil wrapped around it.  This is very high loss and very vulnerable to RFI.

Twisted Pair only "resists" interference if the right signals are used - i.e., differential signals (LVDS, RS485, RS422, etc). Anything else and it's just like any other wire but with the disadvantage that the wires in a pair have closer coupling with each other than with other wires, so can increase crosstalk.

It depends on the frequency/frequencies you care about transmitting on your cables. One simple approach is to put on both ends a filter that lets pass only those frequencies you care about.
You can also consider using some error detection/correction encoding or check if there is some existing library that suits your needs. This last approach will work if you do not get too many interferences and your application can tolerate that data is re-transmitted every now and then, making the communication timing not 100% deterministic.

CAT5 should work well with what you are trying to do, however stay away from power lines unless they are in a grounded conduit.  The phone lines would most likely generate interference when the phone is ringing as there is a lot of voltage transients on the line at that time.
To get the full benefit of the twisted pairs send and receive your signals with differential transceivers, one transceiver per pair.
Personally I will not connect a microprocessor pin to the outside world without some type of buffering isolation etc.  Those pins were not designed to drive long lines, although it may work eventually it will fail, that may be momentary to many years in the making but it will fail.
Lines connected directly to the microprocessor pins will all act as bidirectional antennas. They are not only are sustainable to interference they also generate it.  Remember the wires are small inductors which can generate some huge voltages when the transition time is short.
I typically use Schmidt devices such as a 74C14, 74HC etc. as my input receivers for switches etc.  I normally use an active low input signal, this help to keep noise out of the power supply. The input to the gate is pulled up to the 12VDC with a 10K resistor, this keeps a minimum of about 1 mA through the contact. The other end of the resistor is connected to a 100K resistor that in turn connects to the microprocessor input pin. You can add a cap to de-bounce at the gate if you want. The software is easier as it is looking for an active high which is a logic "1".  This circuit has been replicated hundreds of thousands of times and is very stable and reliable.
What you are doing will work for dorm room, testing etc...


text:
Broken Score on Game Sketch
I have modified the code for Flappy Duino to give me a score at the end of the game. Here is the code:
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>

Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);

#include "Sprite.h"
#include "Chym.h"
#include "Bar.h"

Chym player;
Bar bar; Bar bar2;
int gameScore = 0;
int highScore = 0;
int KNOCK_PIN = 2;
int LED_PIN = 8;

boolean clicked = false;

void loop(){}

void resetGame() {
  player.respawn();
  bar.setPos(0, 20);
  bar2.setPos(50, 30);
  gameScore = 0;
}

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

  display.begin();
  display.setContrast(50);
  display.clearDisplay();
  display.display();

  digitalWrite(LED_PIN, HIGH);

  pinMode(KNOCK_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);

  resetGame();

  while(1) {
    getInput();
    player.update();
    bar.update(); bar2.update();
    drawLCD();
  }
}

void getInput() {
  int knock = digitalRead(KNOCK_PIN);
  if (knock == 0) { // push down
    clicked = true;
    gameScore = gameScore + 1;
    Serial.println(gameScore);
  }
  else {
    clicked = false;
  }
}

void drawLCD() {
  display.clearDisplay();

  if (!player.isDead()) {
    int ht1 = bar.hitTest(player.getX(), player.getY());
    int ht2 = bar2.hitTest(player.getX(), player.getY());
    int die = ht1 + ht2;
    if (die == 1) {
        // game over
        player.die();
    }

    if (clicked) {
      player.flyUp();
    }
    else {
      player.cancelJump();
    }
    player.render();

    bar.render(); bar2.render();
  }
  else {
    if (gameScore >> highScore) {
      highScore = gameScore;
    }
    display.setCursor(0, 0);
    display.setTextSize(1);
    display.print("ur Score- ");
    display.println(gameScore);
    display.print("HI Score- ");
    display.println(highScore);
    if (clicked) {
      resetGame();
    }
  }

  display.display();
}

The first time the game runs thru the gameScore is greater than highScore so gameScore and highScore print as the same. However every other time the function is called up the highScore doesn't change even when the following statement is true:
if (gameScore >> highScore) {
          highScore = gameScore;
        }

What am I doing wrong?

if (gameScore >> highScore)

You have the wrong operator there.  >> is right shift, so you are right shifting the gameScore by highScore bits, which if it's more than 16 will end up as 0.
Instead you just want > for greater than:
if (gameScore > highScore)

Does the same apply to operators such as ||, &&, ==? Could I have used >=?

Full list of operators: http://www.tutorialspoint.com/cprogramming/c_operators.htm


text:
What could make an LCD stop working permanently after being connected for 5 seconds to Arduino?
I was using a 20x4 LCD connected to Arduino Uno via a common I2C adapter board. Everything was working perfectly, including the LCD. I had it running like this for a couple of days without any problems.
My next step was to connect the LCD to a Nano instead in order to make the package smaller. The exact same code from the Uno was uploaded to the Nano, and I connected the wires in the exact same way. The major difference here was that I soldered the wires onto the Nano, because I didn't want to use headers. I did a continuity test for shorts and the connections seemed to be fine. There are only 4 wires between the Arduino and LCD adapter board: 5v, ground, SDA and SCL.
The Nano powers up fine, and the LCD powers up fine, but immediately the LCD shows the following:

That had never happened when I had the LCD connected to the UNO.
After that, the LCD stops working completely, even when I move it back to the UNO. It just constantly displays those 2 lines. (Adjusting the contrast makes the boxes appear or disappear).
After the first LCD seemed permanently broken like that, I tested it on a 2nd brand-new LCD. First I connected it to the same Uno with the same code, and everything was working perfectly. I re-uploaded that same code again to the Nano, just to make sure everything was in sync. Then upon connecting the 2nd LCD to the Nano, immediately it displayed those 2 lines. I disconnected it right away (within 5 seconds), and tried to put it back on the Uno, but still the display is corrupted. I've tried other sketches, but both of these displays seem to be broken and never display anything except for those 2 lines.
Even if I just connect 5v and ground to the LCD, no matter from what source, it just constantly displays those 2 lines.
Any ideas as to what could "break" an LCD so quickly like that, and if it's possible fix it?
Edit:
As per Gerben's suggestion, I removed the I2C backpack and hooked the LCD up directly. This was the 2nd one I had broken, the one where I'm more certain of its entire (short) history. I ended up with the exact same result. Adjusting the pot only makes the boxes appear or disappear. I tried skipping the Arduino completely and giving it 5v power from an adapter, and it still has the same result.

Is this on the end of your long wires in your other question?

The first LCD was, but for the 2nd LCD I tested it with short 6" jumpers. I never put the 2nd LCD (which also broke right away) at the end of the long wires.

Also I have a 16x2 LCD (smaller) connected to a Nano via the same I2C adapter, with more complex code, and at the end of a 10' cable, and that has been working perfectly for a few weeks now.

Try removing the backpack, and connect the LCD directly to an Arduino. That way you know if it's the backpack or the LCD that's broken.

I just tried removing the backpack and connecting it directly, and I ended up with the same result. I added the new information to the bottom of my post.

Do you get the same results in both 8-bit mode and 4-bit mode?

It took me a while to figure out how to use 8-bit mode (followed these instructions: https://electrosome.com/interfacing-lcd-arduino-uno/, where it seems that the unused pins are just pulled to ground), and I got the same result. I want to note that the boxes show up on the LCD immediately when it's powered, whether from an Arduino or from a 5v adapter, before the LCD even has time to read anything from the Arduino.

I am having exactly the same problem. I reordered a new LCD (looks identical to yours) and it worked first time, then started displaying those lines. Did you manage to solve this?

Try in your code lcd(0x27,16,2); insted of lcd(0x3f,16,2);

It's unlikely that you have killed the unit as this is pretty hard to do from the data interface and your picture is typical for an LCD that has not gone through the initialization sequence.  A dead LCD driver will usually display nothing and what your picture shows is that the LCD controller itself is operating.  If anything is dead, I would suspect the I2C interface board as this would yield the same result you are seeing.  It may also be that the timing of the I2C interface is right on the edge which may explain why a long cable'd setup is working.
Note that if the initialization is not done, no other commands will work.  Note also that the initialization timing and sequence of events is ABSOLUTELY CRITICAL and missing any single step or time requirement will give the result you are showing.
Starting at page 10 of this instructional PDF is my favorite and the basis of my driver that I have been using since the 80's.

The driver I use works on every display I have ever hooked to it, regardless of changes in the particular project's processor clock speed because I paid strict attention to the worst case timing requirements.  If the timing of the I2C interface violates one LCD it may not violate another, i.e. one display can tolerate bad timing while another can't.  There are also issues if the LCD driver uses the busy flag or not:  Blind data transmission without reading the LCD's busy state will work if the LCD is fast enough and the driver is slow enough, otherwise 'No bueno!' plus the interface is not going to operate at its maximum speed.  When using the busy flag (Bit 7 of the interface) there is solid handshaking which confirms (Instead of "Trusts") that the LCD is ready for the next cycle and allows operation right up to the limit of performance.
What I would suggest is that you put the interface on a logic analyzer and verify that the timing is not being violated.
Timing tolerances and variation between parts is like lug nuts on a car... If you car has 5 lug nuts per wheel, it will probably work with 3 or even 2 but NOT UNDER ALL CONDITIONS.  SOME LCDs will be happy with bad timing but ALL LCDs NEVER will be.

Thanks! This is some amazing information. I need to read more about this, and later on I'll try some experiments, but I was wondering if anyone can answer these questions: Why would LCD initialization get messed up with the Nano but not the Uno? Also why would it get messed up with a 20x4 LCD, but not with a 16x2 LCD (which works fine with the exact same code on both the Uno and Nano, but obviously the last few characters and 2 lines are missing). BTW once I searched for "Arduino LCD initialization", I found some posts on SE and the Arduino forum about the same issue.

Thanks for the excellent additional information. I'll accept this as the answer once I have more time to experiment and understand it fully. It seems that this information might be relevant to many people who are having this problem. I'm also interested in seeing/learning an Arduino-specific solution, for example a library that is more reliable or a modification to existing popular libraries.


text:
Arduino number detection
I am planning for a project but i am stuck with a task and hope you could help me. My work is to note down a number which is actually a set of readings displayed on a meter and store it on a arduino. My problem is that i need a detection technique so that i could record the number or extract the number from a image or video if u suggest to use a camera or recorder or purely can be a sensor. Thank you guys, waiting for you.

What kind of meter? Analog, digital, leds, lcd, ...?

What exactly is it you are trying to do? What does this "meter" measure? What form does that measurement and display take?

Abstraction is (often) a good thing. But for this question, we're going to need the details of this specific meter. How does the display work, can we wire into the display? How does the end sensor work, can we just replace it? Best would be if you upload an image and description of the sensor.

"Number detection" sounds like you're trying to interpret a 7-segment digital display - is that correct? One way would be to place 7 photo-detectors (times the number of digits), one per segment, on or at the face of the display. Sample the photo-detectors and create a 7-bit code representing the lit segments, into a byte. You could start with a simple lookup table that translates from code to the digit it represents. You might need to get clever about interpreting codes that shouldn't appear, but do, due, perhaps to light leakage, ambient lighting, or noise. The "lit" segments may only be lit for a fraction of second at a time, and only one at a time, if the display is multiplexed, so your sampling algorithm will have to take that into account. Must the display remain visible? You might need optics or optical fibers to view the segments without obstructing them.

+1 for the extreme "hacky" end-product that can be placed ontop of an 7segment and read it's value. But how is this superior to just reading the pins/lines that go to the 7segment? (If we have access to them, I would suggest reading those out).

Thanks! And of course, it isn't better. I tried to guess what the real requirement was based on the OP's question - is this a design-course exercise? - and to answer that. If I could have connectivity to the system, I'd do as you suggest. If I could have access to its firmware, I'd transmit the values by, e.g. serial.  In any case, we can't answer for real without a better spec.


text:
Ultrasonic sensor returns random values on external power supply
my Problem is, that I get random values from my ultra sonic sensor if my arduino is connected to any external power supply (vin port 30) on my arduino nano.
If I power up from the laptop usb port, I get consistent values.
I have tested 3 different power supplies between 7-17V and up to 2000mA.
I have tested this on 2 different nano boards.
Also tested with an extra 2000uF capacitor between vin and gnd
pls help if you got an idea :)

What voltage are you reading on a +5 pin? (Ie "pin 27" in your 30-pin numbering scheme, or pin 6 on the ICSP header.)  Also, what model of ultrasonic sensor do you have, and which sketch is running?  And do some other sketches seem to work ok with external power?

I got the HC-SR04 Ultrasonic Sensor and the basic demo code. I found the solution see below. Thanks for your comment anyway :)

I've been facing this problems as well. Different readings with different power supplies. In fact, i get wrong readings with a good 5v 2A power supply, but get good reading with a cheap 5v 1 A power supply. Not sure why this is happening. Similar results with ultrasonic library mentioned above as well.

as I wrote above, this seems to be a floating ground thing. On the good supply the mains ground is routed through to the arduino (-) ground so it is not floating. I would have expected to get invaild readings in floating condition, but it seems to be the other way around. On pc USB you also have proper ground and you also get invalid results with newPing.

I was running into this issue as well. For me I was plugged in via USB to my computer, and i had my breadboard powering the sonic sensor through a 30v lab supply tuned to 5.02v.(5v at the other end of the meter). I solved my spurious ranging by "giving" the 5V back to my arduino by plugging my lab bench supply and the 5v pin on the arduino to the same rail.

So i tried to used a stable 5V input on the 5V input pin and got the same more or less random values (jumping all around... especially on targets more than 1m away)
So I changed form newPing lib (http://forum.arduino.cc/index.php?topic=37712.0) to Ultrasonic lib (http://forum.arduino.cc/index.php?topic=37712.0).
Now the values are correct on each power supply and even more accurate on high distance than with newPing on USB power supply.
Don't know whats broken with the newPing v1.7 lib -.- but this works!

Glad the library helped. I think perhaps the problem had to do with reference voltages. If you are using two supplies, you need to make sure they are grounded together very well. One library could stand the different voltages and the other couldn't. But the key to using two power supplies for anything is to make sure they are grounded together.

Is it possible that one library reports instantaneous values, and the other uses averaging?  Or even if both use averaging, that one is synchronous with 60Hz mains?

the arduino side (dc) don't has access to the mains frequency (ac), so I don't think this is the difference. The only obvious difference seems to be the ground level as @SDsolar wrote below. I don't have access to my setup anymore but you could test this by temp connecting main ground to the arduino gnd and see if the values change.


text:
Chat between Xbee and Arduino
I'm very new with this devices so I'm a bit confused. I've got two Xbee modules series 1 and an Arduino UNO. I want to make like a chat between the two Xbee modules, one of them connected to the PC through a Xbee Explorer USB and the other one assembled in the Arduino Board through a shield.
I've configured the two Xbee modules with the same PAN ID and Channel, and the Xbee module 1 has MY = 0 and DL = 1 and the Xbee module 2 has MY = 1 and DL =0.
I've connected the Xbee module 1 to the PC through the Explorer and the Xbee module 2 connected to the PC through Ardunino+Shield.
I've uploaded the following code to Arduino:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(4, 5); // RX, TX

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

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

In my shield the jumper of the RX digital is the 4th pin and the TX jumper in the 5th pin.
When I open the serial monitor window I get the message "Goodnight moon!" but when I send a message from the XCTU console or from the serial window I don't get that message in the other interface (XCTU console or serial monitor window).
In the shield (this one http://www.seeedstudio.com/wiki/XBee_Shield_V2.0) I've 4 leds: first one (power) is on, the second one (signal strength) is off, the third one (association) blinks all the time, and the fourth one (on/sleep) is on.
Why I don't get the messages like a chat? What am I missing?
Thank you!!

Are both Xbees in AT mode (instead of API mode)? Do both have a baud rate of 9600?

Yes, they are in AT mode and 9600 baud rate

Did you try switching rx and tx pins mySerial(5, 4);? Are they in broadcast mode? What is the led flash rate of each?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Where do avrdude parameters get defined in the Arduino IDE?
I am interested in learning how the Arduino IDE handles parameters in order to correctly upload hex files with avrdude.
I found this in boards.txt:
uno.name=Arduino/Genuino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
uno.vid.2=0x2A03
uno.pid.2=0x0043
uno.vid.3=0x2341
uno.pid.3=0x0243

uno.upload.tool=avrdude
uno.upload.protocol=arduino
uno.upload.maximum_size=32256
uno.upload.maximum_data_size=2048
uno.upload.speed=115200

uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0x05
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

uno.build.mcu=atmega328p
uno.build.f_cpu=16000000L
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

There is this in platform.txt:
# AVR Uploader/Programmers tools
# ------------------------------

tools.avrdude.path={runtime.tools.avrdude.path}
tools.avrdude.cmd.path={path}/bin/avrdude
tools.avrdude.config.path={path}/etc/avrdude.conf

tools.avrdude.upload.params.verbose=-v
tools.avrdude.upload.params.quiet=-q -q
tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.program.params.verbose=-v
tools.avrdude.program.params.quiet=-q -q
tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.erase.params.verbose=-v
tools.avrdude.erase.params.quiet=-q -q
tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uefuse:w:{bootloader.extended_fuses}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude.bootloader.params.verbose=-v
tools.avrdude.bootloader.params.quiet=-q -q
tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.platform.path}/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m

This line is particularly interesting:
tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

It seems like these variables are corresponding:
{cmd.path} --> tools.avrdude.cmd.path
{config.path} --> tools.avrdude.config.path
{upload.verbose} --> tools.avrdude.upload.params.verbose
{build.mcu} --> uno.build.mcu
{upload.protocol} --> uno.upload.protocol
{serial.port} --> ?
{upload.speed} --> uno.upload.speed
{build.path} --> ?
{build.project_name} --> ?

It seems these are likely used in the Java code for the IDE. There are obviously a few I am unsure of. I would guess these are considered user inputs in the IDE. Though I am by no means a Java or JavaScript programmer.
Where are these variables explicitly defined in the Arduino library? (e.g. {runtime.tools.avrdude.path}, {path}, {cmd.path} ....) Or how do they get defined by IDE?

where can I find,
Boards.txt
Platform.txt
programmers.txt file. I use - Mac Mojave 10.14.6
Arduino iDE - 1.8.12 When I run the data logger code (to save in SD card) I am getting /Users/placidafernando/Library/Caches/Homebrew Error. I reinstalled Brew and Avrdude. I. see it has installed under when I look via Terminal. Cannot see from MAC apple man /Users/myUserID/Library/Caches/Homebrew But my sketch and Arduino is in /Documents libraries Following message is due to IDE or Arduino-CLI unable to fine the avrdude.tar file in the current directory? I am npt a big mac user. How can I set the path

@ShaunChristianFernando you should probably just ask your own question.

There are 3(or 4) places that you need to look at to know how to upload.
There is the boards.txt file and the platform.txt file.
You can consider a platform.txt file line
tools.avrdude.path={runtime.tools.avrdude.path}

as (in linux in windows replace ${xx} by %xx%)
set tools.avrdude.path ${runtime.tools.avrdude.path}

and the board.txt for the selected board like
uno.bootloader.tool=avrdude

as
set bootloader.tool avrdude

The arduino ide uses the following string to know the upload command environment variable
tools.${bootloader.tool}.upload.pattern

This way it knows the command to upload is
"{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

{cmd.path} is hardcoded as tools.${bootloader.tool}.cmd.path which equals {path}/bin/avrdude
where {path} is to be understood as tools.${bootloader.tool}.path wich equals {runtime.tools.avrdude.path}.
{runtime.tools.avrdude.path} is defined by the boardsmanager based n the json file and the location where the boardsmanager extracted the download.
So that makes 3 files: boards.txt, platform.txt and json file and some hard coding.
A 4th file comes into play when you use the "other upload commands". These are located in the programmers.txt file.
IMHO Arduino IDE core team did not opt for the simplest solution to define these things. They also change the way they work from time to time.
If you use a makefile know that a lot of people have done this already so it may be a good idea to "reuse other peoples work" instead of "reinventing the wheel". It is not so easy or straightforward.
Note I know all these things because I implemented the Arduino eclipse IDE. As far as I know none of this is documented.

The Arduino library is about what runs on the target, while the "IDE" (not sure if it can still be called IDE, as now they try to do also command line) is about everything else.
But my impression is that if you are ready to ask these sort of question, you could consider dropping the IDE and moving to a more standard Makefile approach. Or Maybe Eclipse, where you still have the IDE, but you can define everything in a more standard way.
The Arduino approach is good to get people with little experienced started, but after a while one started to feel its limitations.

I've used a makefile approach. So I am now interested in finding out how and where the parameters that get sent to avrdude are defined. More specifically the variables involved in tools.avrdude.upload.pattern.

Not sure I understand you. Do you want to know how to invoke avrdude by replicating what the IDE does?

I want to know how to choose the parameters that need to be sent to the avrdude program for a given board type. I have found where the flags are settools.avrdude.upload.pattern. I am unsure of how they are set. Please see the block in my post with arrows signifying "corresponding". All the variables prefixed with uno, I understand where those values come from (boards.txt). But the variables prefixed with tools and the ? marks, I am unsure of where those are defined. I would like to know where those are defined.

Ok, my bad, I should have asked an open question. Next try: what are you trying to achieve with this? Why do you want to know this?

I want to know this because I want wrap the Arduino C library for use with Python. I want to know this because it is part of the design for how the wrapper would work, i.e. the upload process.

I'm a bit confused. The Arduino C library, AFAIK, is something that is compiled for the target (AVR mostly). Then there is a java (afaik) implementation of the IDE, which relies on various tools, like avr-gcc and avrdude. If you want to use them, why not just executing them from python? As you must have seen, they work even from Makefile.

I understand I could execute from Python but I want to wrap the Arduino library. I want to be able to write in Python, not just compile from it, e.g. Blink.py not Blink.cpp.

I have done my share of python bindings for C libaries, but they always rely on having a python interpreter running on the target. That is simply not possible on a basic AVR like the 328p. The closest you might get is with https://wiki.python.org/moin/PyMite but it seems abandoned. Or go for a targeted implementation like https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers/posts/1198333. Of course you might achieve python-like syntax wit lots of work on the parser/compiler, but that's a different story.

I am looking to use Cython to convert Arduino.h into an Arduino.so, so I can then import Arduino in a Python script. For now, I think it I will then output a cpp from the Python script, which will then compile and upload via an upload command.

Let us continue this discussion in chat.