Is it possible to read VGA with an arduino In this forum thread on arduino.cc http://forum.arduino.cc/index.php?topic=107375.0 they talk about it not being possible to get 800 x 600 video in color with the arduino.

My case is a bit different:

I don't care about color, it can be black and white / grayscale.
I don't need 800 x 600 just 640 x 480.
I can do with something like 2-5 frames per second.
I don't need it to be processed by the arduino, just transmitted through an ethernet shield.

In other words, it is possible to transmit simple video (just enough to handle eg. bios) remote?

Trying to capture analog video such as VGA and transmit it over Ethernet is going to be technically challenging, and of questionable wisdom (at least without compression).  A conventional ATmega-based Arduino is just about the worst contemporary platform you could choose for this job - even aside from the VGA issue, it is a poor choice for Ethernet requiring an expensive add-on.  But just for the sake of "can it be done" ....

If you can threshold your signal to a digital level (assuming a high contrast image) this probably can be done, crudely, but will be quite tricky.  The display is likely to be very blurred horizontally - really, it would only be worth doing for bragging points.

The first thing to realize is that the standard VGA 640x480x60 mode has a pixel clock of 25.175 MHz, and most others will be even faster.

One approach would be to try to write a program which samples a digital pin (directly, no Arduino abstractions) to memory as fast as possible.  This would not capture every pixel, but rather something like every 10th.  You would then have to send these over the network before you fill up your available memory.

The tricky part is that you then have to go back, and scan another frame of video with a slight offset, so that by getting every 10th pixel again, you effectively get the pixel adjacent to the first.   And then you do it again, and again, until you have collectively transmitted the entire screen, which hopefully hasn't changed much as you did it.

It's going to be tricky as you will have to work your delays from the sync signals, and you really want a delay which is a fraction of ATmega's clock - which won't happen without external circuitry (programmable delay buffer, etc)

The whole project would be a lot more feasible on an 80+ MHz ARM Cortex part, as you could then use a counter/timer to generate pixel-or-less-adjustable starting delays relative to the sync pulse.  An FPGA would likely be an even better choice.


How to write a sketch when adding more devices to an I2C data line? I am building a weather station, using a battery-operated outside unit, that transmits data from a DHT22 sensor to a unit inside my house.

The inside unit is using I2C communications from my Arduino Uno to my LCD display.

I would like to add a BMP180 sensor which also uses I2C communications.

My question is, how would you write a sketch to incorporate both the BMP180 sensor and the LCD display on to one I2C line?

Yes you can connect multiple devices on one I2C bus. Every device on the bus needs to have its own address. Some libraries have the default address included. Some do allow to change it. Others don't. For example the SE95 temperature sensor (page 10) does allow for setting a few bits of the address allowing more than one sensor on a bus.

You can use the Wire library from Arduino to request data from I2C. When you want to pull data from a sensor, you have to send a command depending on the specs than request data from the address.

Example: for the SE95 address 0x4F (you can repeat this for any address you have a sensor on your bus) the SE95 ranges from 0x49 to 0x4F depending on the pin settings:

//Please note that the example is not complete because Wire has to be loaded and initialized
byte address = 0x4F;
byte read1;
byte read2;
Wire.beginTransmission(address);
Wire.write(0x00);
Wire.requestFrom(int(address), 2);
if(Wire.available()) {
  read1 = Wire.read();
  read2 = Wire.read();
}

So depending on the libraries, this would be quite easy.


What's wrong with infinite loops inside loop()? I wanted to run the following code as something similar to Tone or pwm. However for some reason that I am unable to seek it doesn't work.

#define WAIT 3200UL

void setup() {
  DDRB |= B00000001;  // set pin8 as output
}

void loop() {
  unsigned long t;
  while (1) {

    PORTB &= B11111110; // clear pin 8
    t = WAIT;
    for (t = 0 ; t < WAIT; t++);

    PORTB |= B00000001; // set pin 8
    t = WAIT;
    for (t = 0; t < WAIT; t++);

    //            PORTB &= B11111110;
    //            delayMicroseconds(WAIT);
    //            PORTB |= B00000001;
    //            delayMicroseconds(WAIT);

  }
}

the code is pretty simple, just toggling a pin. If I use the commented section, it works fine but as is, it doesn't work.

I removed the "while(1)" statement since it was unnecessary for now, it started to work improperly, (changing the WAIT didn't have any effect and I'm not sure I'm getting a full swing).

Pin 8 is connected to an LED + R to ground and a piezzo in parallel to them. the LED seems to be steady on yet the buzzer makes a low noise. I measured a   voltage of 3.8v DC and arround 9v AC on the pin, other pins I ran the code for were similar.

As another attempt I put a Serial.print in the beginning of the while(1) but it printed out only once.

Also looked at the assembly code generated for a clue to find out what does delayMicroseconds() do but couldn't figure out what's wrong.

Appreciate your help.

First, I will give you some unsolicited advise about your coding style.
Instead of writing:

PORTB &= B11111110;
...
PORTB |= B00000001;

you could write:

PORTB &= ~_BV(PB0);
...
PORTB |= _BV(PB0);

These are standard AVR idioms, and they make it clearer that you are
toggling the pin PB0.

Then, to answer your actual question, your delay loop does not work
because it got optimized-out by the compiler. This has already been said
in Michel Keijzers' answer, but let me elaborate.

All modern compilers are optimizing compilers. This means they can
change your code in whatever way they see fit, as long as the visible
effects remain the same. The effects considered visible are usually
I/O and access to variables declared volatile. Quite importantly, the
slowness of the program is not considered a visible effect for the
purpose of optimization. And if you think about it, it makes good sense:
if the slowness of the program were to be preserved, then any form of
optimization would be impossible. Thus, a loop that has no effect other
than slowing your program down can legitimately be optimized-out.

The solution to your problem is quite simple: if you want a delay, then
call delayMicroseconds(). Or maybe even delay() if you are OK with
its low resolution. On the other hand, if you need sub-microsecond
resolution, you can call _delay_us(), from the avr-libc. This function
(or rather, macro) provides single-cycle resolution. If you write

#include <util/delay.h>

...
_delay_us(1.375);

you get exactly what you ask for, i.e. a delay of 22 CPU cycles
(on an Arduino Uno clocked at 16 MHz). The issues with this
function are that it is AVR-specific, and its argument must be a
compile-time constant.

It has been suggested to you to write your delay loop using a volatile
loop counter. I strongly advise you against doing that, for three
reasons:

Doing so will force the counter to be allocated to RAM, thus
consuming a scarce and valuable resource for no good reason.
Incrementing a RAM-based 32-bit counter takes 20 CPU cycles. Add
to this the time required to test the end-of-loop condition and you
will realize that your delay resolution is way worse than that of
delayMicroseconds().
Your actual delay will depend on the clock frequency, and probably
also on the compiler's version, making your code pretty fragile.


is it necessary to include libraries that are specified in the header file already? I am using the Adafruit BME280 library in my sketch. In the example sketches, they have included the Wire, SPI and the Adafruit_Sensor library. However, I see that in the Adafruit_BME280 library header file, these libraries are already included. So I tried commenting out them in my sketch and it still works. So I wonder if there are still cases or any specific reason to include them twice?
Additionally, if a library is included/referenced twice like mentioned above, wouldn't it increase the size of the sketch unnecessarily?

Example Sketch that comes with the library
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI

unsigned long delayTime;

void setup() {
    Serial.begin(9600);
    while(!Serial);    // time to get serial running
    Serial.println(F("BME280 test"));

    unsigned status;

    // default settings
    status = bme.begin();
    // You can also pass in a Wire library object like &Wire2
    // status = bme.begin(0x76, &Wire2)
    if (!status) {
        Serial.println("Could not find a valid BME280 sensor, check wiring, address, sensor ID!");
        Serial.print("SensorID was: 0x"); Serial.println(bme.sensorID(),16);
        Serial.print("        ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
        Serial.print("   ID of 0x56-0x58 represents a BMP 280,\n");
        Serial.print("        ID of 0x60 represents a BME 280.\n");
        Serial.print("        ID of 0x61 represents a BME 680.\n");
        while (1) delay(10);
    }

    Serial.println("-- Default Test --");
    delayTime = 1000;

    Serial.println();
}

void loop() {
    printValues();
    delay(delayTime);
}

void printValues() {
    Serial.print("Temperature = ");
    Serial.print(bme.readTemperature());
    Serial.println(" *C");

    Serial.print("Pressure = ");

    Serial.print(bme.readPressure() / 100.0F);
    Serial.println(" hPa");

    Serial.print("Approx. Altitude = ");
    Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
    Serial.println(" m");

    Serial.print("Humidity = ");
    Serial.print(bme.readHumidity());
    Serial.println(" %");

    Serial.println();
}

Historically it was necessary, yes. In times past the IDE would look only in your sketch to find the list of libraries to compile and link. However much progress has been made in recursive library searching, whereby the IDE can now find libraries that are included by other libraries.
I am not sure when that change was implemented, but it was a long time coming and is only recently that it's worked.
So if you are distributing code for other people to use then it's a good idea to still add the libraries in the sketch - just in case they're using an older version of the IDE that can't find the libraries included by other libraries.


What are the implications of running an ATmega328P at 8 MHz and 3.3 V with the Arduino system? I'm working on a custom arduino that will run at 3.3 V with no regulators or USB chips (for power consumption).  I've heard that overclocking the chip at 16 MHz/3.3 V is generally fine, but I'd like to stay within spec anyway.

First: to run at 8 MHz, do I just need to replace the crystal?  Or is there anything else I have to do?

Second: Do I need to make any code changes to reflect the new speed?  I'm using serial, SPI, and I2C connections in this project, along with the NilRTOS operating system and millis/delay functions.  Will any of these be broken?  Will the code run noticeably slower?

Third: How can I program the chip?  Is it ok to program it in an Arduino Uno at 16 MHz, then transplant it to the custom arduino?

Fourth: Will power consumption change at 8 MHz?

Thanks!

The formula seems to be volt*5.9-6.6=mhz (valid between 1.8v and 4.5v), so at 3.3v, this would give 12.8mhz. Be aware that, if you are running at 12.8mhz, ANY drop below 3.3v MAY cause problems (and very hard to diagnose, too!) or you MAY get away with it.

However, Arduino Atmega328p chips have a "brown-out" detection set at 4.3v - any drop below that, the chip shuts down. You can get an ISP (AKA ICSP) to change the fuses - go to http://www.engbedded.com/fusecalc/ to work out what to set fuses to. You can also use the ISP to read the current fuses, or indeed reprogram the chip without an Arduino board - all my projects have a 6-pin header. If you do this, before reprogramming using the Arduino board, you will have to "Burn Bootloader" (in the tools menu). Note that programming can still be done via Arduino IDE.

Alternatively, if you want to go "light" (and have an ISP), you can change the fuses to use the internal 8mhz clock - this frees up 2 extra pins, too! Be aware, however, that the internal clock may drift 1.2 hours per day (=5%), compared to 1.7 seconds per day (=20 parts per million) on a typical quartz crystal. If you don't use it for timekeeping, this probably doesn't matter.

You will need to make changes to the timing, for your code - you need to add a boards.txt with correct settings for your chip/clockspeed etc - you can copy the settings from the entry for the board, change the name, and change the setting "build.f_cpu"; restart (or start) your Arduino IDE, go to "Tools->Board" and select the board you added.

You can move the chip on/off the board, and reprogram it there (note that the board selected in Tools->Board is the FINAL board, not the programming board). Be careful plugging/unplugging it - eventually, you WILL bend the pins! Alternatively, you can use ISP (ICSP), as mentioned above - much recommended. ISP programming will also work if the chip is factory default, so long as it has a working clock.

How much power is used by the chip depends hugely on what you do with it - not just clock speeds, clock source, etc but also sleep modes. If you are sleeping a lot, it may draw less when running faster than running slower - if almost all your time is asleep, then the power consumption should be counted per clock cycle, not per second - if your clock is half the speed, and half current, then you draw the same current per instruction. Since the rest of your time is spent asleep, you get no benefit. See http://www.gammon.com.au/power for a very good breakdown of power usage, tips on how to save power, etc.

If you slow your clock down too much, serial and i2c may become unreliable (unless you slow down the speed), but I would expect to be able to go down to  1mhz before this to be a problem - a 1mhz chip trying to do 9600bps has 104 instructions per bit of data transferred. i2c runs at 100khz, so you get 10 instructions per bit (at 1mhz) - possibly pushing it. 8mhz should be fine. Test, test, test.

UPDATE:
There are 3 possible settings for the brown-out detection - there are 3 possible values for the AtMega328p: disabled, 1.8v, 2.7v, and 4.3v. I was under the impression (above) that Arduinos were normally set to 4.3v; apparently that is not the case (see comment below). I recall seeing somewhere that there was brownout detection. This is something to keep in mind, if your arduino resets, especially when putting larger loads on the battery (running motors, multiple leds etc).


Issues with connecting XBee to Arduino Uno R3 I have an Arduino Uno R3, Wireless Proto Shield and a XBee XB24-AWI-001 all hooked together. I'm using X-CTU software to access the XBee and change the properties of it. I did a little research and found out that if I want to access the XBee, I have to connect the GND to the RST pin (on the Proto Shield) or hold the RESET button on the board. This method works and when I do that, I can find the XBee on X-CTU.

The question is - why do I have to do that? I'm probably wrong, but as far as I understand, if I have my Arduino connected to the computer, I'm accessing the ATmega microprocessor and that's the reason I can't access the XBee, but when I do the reset, I'm constantly resetting the microcontroller and that's the reason why I can access the XBee? Hopefully someone can explain this...

The link where I found the information about resetting (or removing) the ATmega microproccesor, Using Arduino to Connect Xbee Serial to Computer.

I am slightly surprised that you can actually talk to the XBee from your PC over USB with the XBee in the shield. XBee shields are generally designed for the XBee to be used by the Arduino only. The fact that you can actually talk to the XBee from the PC using X_CTU with the XBee in the Arduino shield, by holding down reset, seems to either be a quirk or a feature of the shield1.
Generally to use X-CTU to talk to the XBee, one would use an XBee explorer board or a Development board. One would configure the XBee completely in the Explorer dongle and then transfer the XBee to the shield for the Arduino to use it.
See the thread on the Digi forums, xbee s1 xctu arduino:

The shield is not design for writing and reading firmware to and from
the XBee module. It is only designed for basic two way communications.
If you want to read or write firmware to the module, you need to use a
board that is designed for it such as the XBIB boards from Digi.

See also Can an XBee be programmed with an XBee Shield.
However, hopefully someone with more knowledge of the internals of an Uno and XBee shield than I, could explain the actual electrical reasoning behind this issue. I have attempted to explain it below in the footnote.

1 Having said all of that, looking at some of my XBee shields, a couple have a microswitch, that enables the XBee to talk to either the Arduino or the USB, but not both at the same time. So, I guess that the need to hold the reset on your shield is because you do not have such a microswitch.
So the reason being, is that the Arduino and the USB can not talk to the XBee at the same time, as there would be conflict on the Rx and Tx serial lines - see this thread, UNO + Sparkfun's Xbee Shield Always Reset if Receiving Data From X-CTU Terminal which hints at the same thing. Two comments of note from that thread are:

It would be a lot simpler to debug the issue if you put the switch in the other position, and used SoftwareSerial to talk to the XBee and Serial to talk to the PC. Using one port to talk to two devices IS going to frustrate you no end.

and

Note that a communication application connected to an arduino that opens a com port, sends data, then closes may cause the arduino to reset.

As a (really wild) guess, I would imagine that the USB-to-TTL IC's DTR line, or equivalent (?), is [logically] tied to the Arduino's RST line, so that if the PC tries to communicate to the XBee, it ends up resetting it, rather than signalling to the XBee that it is ready to communicate.
Note: The USB-to-TTL IC could be a FTDI, ATmega 4U2/8U2/16U2 or an FTDI clone, depending on the variety of Uno that you possess.
Addendum
I do wonder why the switch is there, if it doesn't end up working correctly. Regardless, I would still get a $3 explorer board clone to use with X-CTU. Be careful which one you buy as not all of them work with OS X, if you use a Mac, see the end of USB-TTL interface devices on OS X. That explorer,  XBee USB Adapter Bluetooth Bee FT232RL USB to Serial Port Module for PC Arduino, is good value for money and compatible with WinTel, LinTel and OS X machines:


Reading NFC card (PN532) with Arduino Uno I am trying to detect a RFID card using the NFC-PN532 module and Adafruit_PN532 library.

Initialization code:-

#include <Adafruit_PN532.h>
#include <Wire.h>

#define SCK  (13)
#define MISO (12)
#define MOSI (11)
#define SS   (10)
Adafruit_PN532 nfc(SCK, MISO, MOSI, SS);

void setup()
{
  Serial.begin(9600);
  Serial.println("Initializing please wait.......");
  delay(3000);
  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata)
  {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }

  Serial.print("Device Found PN5 Chip");
  Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware version > ");
  Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.println((versiondata>>8) & 0xFF, DEC);
  nfc.SAMConfig(); //Set to read RFID tags
  Serial.println("Waiting for RFID Card ...");
}

Main loop:-

void loop()
{
  uint8_t success = 0;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
  if (success)
  {
      Serial.println("Card Detected!");
  }
  else
  {
      Serial.println("Card Not Detected or Removed!");
  }
}

Whenever i place a valid card on the PN532, Card Detected! is printed on the serial monitor.

However, when i remove the card, Card Not Detected or Removed! does not get printed.

How can i make the program  to loop in such a way that it can detect when the card is present/removed?

The default behaviour of readPassiveTargetID is to wait "forever" for a card - which is why your code only sees when there is a card present

So, in setup() add nfc.setPassiveActivationRetries(0x10); as follows - comments came from my own code, but I'm sure they were originally in some example or other :p

// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.
nfc.setPassiveActivationRetries(0x10);

// configure board to read RFID tags
nfc.SAMConfig();

As for "detecting" removal

void loop()
{
  static bool wasSuccess = false;
  uint8_t success = 0;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
  if (success)
  {
      wasSuccess = true;
      Serial.println("Card Detected!");
  }
  else if (wasSuccess)
  {
      wasSuccess = false;
      Serial.println("Card Removed!");
  }
  else
  {
      // you may want to remove this, it will flood the output :p
      Serial.println("Card Not Detected!");
  }
}


Olimexino 32u4: Wire.endTransmission() hangs I'm trying to get a TAE5767 (FM radio) to work. According to this instructable I'm trying it on a 5V-Olimexino 32u4 (Leonardo-compatible) with following code (Arduino 1.6.3):

#include <Wire.h>

void setFrequency(float frequency) {
  unsigned int frequencyB = 4 * (frequency * 1000000 + 225000) / 32768;
  byte frequencyH = frequencyB >> 8;
  byte frequencyL = frequencyB & 0xFF;
  Wire.beginTransmission(0x60);

  Wire.write(frequencyH);
  Wire.write(frequencyL);
  Wire.write(0xB0);
  Wire.write(0x10);
  Wire.write(0x00);
  Serial.println("sending");
  Wire.endTransmission();
  Serial.println("sent");
}

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

  Wire.begin();
  setFrequency(89);
}

void loop() {
}

Unfortunately, it only prints

sending

First, I thought I'd damaged my chip, but I'm now using the second with the same result. I've also tried the I2C-Scanner from Nick Gammon, but it prints nothing. I've tried adding 2.2k resistors from SCL and SDA to 5V without success. Does someone has a clue what I can try?

I've did not got it working with Wire. Hence I've implemented a I2C protocol myself using bit-banging and then it works.

Update from 2017-September-16

The problem was not Wire.h but a specialty of the Olimexino 32u4 board. I've only found out by using a Real Time Clock connected to the UEXT port's I2C bus, that I have to switch on the power for the UEXT port by setting D8 to LOW. Otherwise SDA or SCL seem to be pulled down preventing any I2C communication.


Two Reed switch in two way directions Hi im a student having problem in coding
I  want to set two reed switch in two direction.
Example : 1. Reed switch 1 detect then reed switch 2 detect - led turns to yellow
2.If reed switch 2 detect first then reed switch 1 detect - led turns to red
 It should play in sequentially form. Can help me in coding?
So far i have done this..

const int REED_PIN1 = 2; // Pin connected to reed switch const int REED_PIN2 = 3; // Pin connected to reed switch

const int RED = 9; // LED pin - active-high const int GREEN = 10; // LED pin - active-high const int YELLOW = 11; // LED pin - active-high

int up = 0; int down = 0;

void setup() { Serial.begin(9600); // Since the other end of the reed switch is connected to ground, we need // to pull-up the reed switch pin internally. pinMode(REED_PIN1, INPUT_PULLUP); pinMode(REED_PIN2, INPUT_PULLUP);

pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(YELLOW, OUTPUT);

digitalWrite(RED, LOW);
digitalWrite(GREEN, HIGH);
digitalWrite(YELLOW, LOW);
}

void loop() { int proximity1 = digitalRead(REED_PIN1); // Read the state of the switch int proximity2 = digitalRead(REED_PIN2); // Read the state of the switch while (proximity1 == LOW) // If the pin reads low, the switch is closed. {

up  = up  + 1;
Serial.print(up);
Serial.print("        ");
Serial.println(down);

if(down < 1){
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}

else {
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}
} while (proximity2 == LOW) // If the pin reads low, the switch is closed. { up = up - 1; Serial.print(up); Serial.print(" "); Serial.println(down); if(up < 1 && down < 1){ digitalWrite(RED, LOW); digitalWrite(GREEN, LOW); digitalWrite(YELLOW, HIGH);

delay(3000);      }
else{
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}
} while (proximity2 == LOW) // If the pin reads low, the switch is closed. { down = down + 1; Serial.print(up); Serial.print(" "); Serial.println(down);

if(up > 1){
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, HIGH);

delay(1000);
}

else {
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}
delay(1000);
}
while (proximity1 == LOW) ;// If the pin reads low, the switch is closed. { down = down - 1; Serial.print(up); Serial.print(" "); Serial.println(down); if(up < 1 && down > 1){ digitalWrite(RED, HIGH); digitalWrite(GREEN, LOW); digitalWrite(YELLOW, LOW);

delay(5000);      }
else{
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);
delay(5000);} } }

Sorry, but your code is complete nonsense. The following code gives you an example. I have no access to a compiler at the moment, so there might be syntax errors and it is completely untested. Also, you gave no complete description of the things you want to do. e.g when to switch on the green LED or what the up and down variables are for.

And there might also be timing problems. In order not to miss a reed state change,
you should avoid adding delays and slow serial print outs.

I'm pretty sure, I did your homework. So my advice is to learn programming and try to understand. Homework was not ( only ;-) ) invented to enjoy the teacher, they help you through tests. ;-)

Your problem is similar to the decoding of a rotary encoder, so information about this subject might help you also.

const int REED_PIN1 = 2;
const int REED_PIN2 = 3;

// LED pins - active-high
const int RED    =  9;
const int GREEN  = 10;
const int YELLOW = 11;

int fixedState1 = HIGH;
int fixedState2 = HIGH;

void setup()
{
   // If the pin reads low, the switch is closed.
   pinMode(REED_PIN1, INPUT_PULLUP);
   pinMode(REED_PIN2, INPUT_PULLUP);

   pinMode(RED, OUTPUT);
   pinMode(GREEN, OUTPUT);
   pinMode(YELLOW, OUTPUT);

   digitalWrite(RED, LOW);
   digitalWrite(GREEN, HIGH);
   digitalWrite(YELLOW, LOW);
}

void loop()
{
  // AS LONG AS BOTH SWITCHES ARE ON AT THE SAME TIME,
  // THE PROGRAM FLIPS OUT ;-)
  int reedState1 = digitalRead( REED_PIN1 );
  int reedState2 = digitalRead( REED_PIN2 );

  if ( readState1 == LOW && fixedState1 == HIGH )
  {
    if ( fixedState2 == LOW )
    {
      digitalWrite( RED,    HIGH );
      digitalWrite( YELLOW, LOW  );
      digitalWrite( GREEN,  LOW  );

      fixedState2 = HIGH;
    }
    else
    {
      // setting the green LED is just a guess
      digitalWrite( RED,    LOW  );
      digitalWrite( YELLOW, LOW  );
      digitalWrite( GREEN,  HIGH );

      fixedState1 = LOW;
    }
  }

  if ( readState2 == LOW && fixedState2 == HIGH )
  {
    if ( fixedState1 == LOW )
    {
      digitalWrite( RED,    LOW  );
      digitalWrite( YELLOW, HIGH );
      digitalWrite( GREEN,  LOW  );

      fixedState1 = HIGH;
    }
    else
    {
      // setting the green LED is just a guess
      digitalWrite( RED,    LOW  );
      digitalWrite( YELLOW, LOW  );
      digitalWrite( GREEN,  HIGH );

      fixedState2 = LOW;
    }
  }
}


How do I implement a userspace bootloader on Arduino Due? Is it possible to use a custom bootloader, that loads and executes a main program stored for example on an SD card? The idea is to make it possible to update the Arduino remotely.

I tried this with a bootloader, which writes the program into the flash storage with a 32KB offset and then uses a function pointer with that address (0x88000) to continue execution there. The 0x80000 is as far as I am informed the address offset of the flash storage. It can be written on Due boards with this library: https://github.com/sebnil/DueFlashStorage. The problem was that this just hasn't worked, the Arduino simply stopped responding after the function pointer being executed. I would appreciate any information or hints on this topic.

The guys at Phoenard did just that with an AVR2560. They wrote a bootloader that loads and saves FLASH memory from/to the Micro-SD card. You can save HEX files on an SD card and then load one of them in the FLASH memory and run it.


Arduino Uno board works but Arduino Uno + Wifi is not being detected When I connect my Arduino Uno board it instantly detects the board and shows it in the list. But when I connect my new Uno + Wifi board it doesn't detect it. I also manually selected Arduino Uno Wifi but it still gives me the message

Error uploading check if the selected board is currently available

How can I fix this?

This is the one that's not working:

Arduino Uno + Wifi

While this one I got does work:

Arduino Uno

What you have there is a cheap Chinese clone. It uses the cheap CH340G USB chip instead of the proper ATMega16u2 that real Arduinos use.

Install the right drivers and it should start working.


How do I transform data for a column to data for a row, for a led matrix I have a 8x8 led matrix. I'm using LedControl.h library to control the matrix, which has 3 ways to light up the leds: setLed, setRow and setColumn. I've found that setColumn it's really slow, it's using setLed to print columns. With all my code, I can only print 3 times a second with setColumn. The function setRow is way faster, I'm guessing that the design of the matrix is allowing to print the rows directly. I can print more than 10 times a second with setRow, so I have to use it, since speed is crucial to my project. In my code, the data i have to print is stored in an array of 8 bytes. This is how it looks like when I use setColumn
for(int i = 7; i >= 0; i--)
    lc.setColumn(0, i, vector[i]);

i is the row to be printed, and vector[i] is a byte value, indicating which leds to be on or off. Column 0 is the left-most one, while column 7 is the right-most one, so i go from 7 to 0 to print from right to left, because that's what I have to do. My goal is to transform somehow to data in vector[i], to data that I can use it using setRow. So that's what I've done so far.
byte mask = 128, x;
for (int j = 0; j < 8; j++){
  x = 0;
  for(int p = 0; p < 8; p++){
    x = x | (valueVector[p] & mask);
    if (p != 7)
      x = x >> 1;
  }
  if (j != 7)
  mask = mask >> 1;
  lc.setRow(0, j, x);
}

Now i print the rows from row 0 to row 7, from top to bottom. Since I'm printing from top to bottom, this means I have to take the last bit of every column (last bit of every element in vector), and put it in a byte variable. I was thinking to make a byte mask = 128 (b1000000, do a AND logic between to mask and the vector value in order to take the bit I'm looking for, and then making a OR to put the bit in the x byte. After every mask operation, I shift the x variable to the right, in order to make space for the next bit. After i'm done with a row, I shift the mask to the right, in order to take the second bit from the value in the vector. The result I get, is quite odd, I can't explain it, it's not good at all. What I'm i doing wrong with the mask and shifts? I hope I explained well what I'm trying to do. If necessary, I can provide more information. Thanks.

You use a mask 10000000. With each iteration of the outer loop the 1 in the mask is shifted to the right. 01000000 -> 00100000 -> 00010000. Let's say we are in the 2nd iteration the mask is 01000000. x = x | (valueVector[p] & mask); takes the 2nd bit (counted from left) and sets it at the 2nd position in the x value. But this position contains the bit from the last iteration (as you shifted it to this position).
Possible solution: (I have no compiler at hand. So hopefully it is correct. ;-)
byte x;

for ( int j=0; j<8; j++ )
{
   x = 0;

   for ( int p=0; p<8; p++ )
     x = x | ((valueVector[p] & (1 << p)) >> p);

   lc.setRow(0, j, x);
}


Serial.print changes serial output before it is called I'm making a project with an sd card where the user enters a file name over the serial port, and then the aduino does thing to that file. Right now i'm working on getting the serial input to work, but one Serial.print() is somehow changing a variable/output of another Serial.print(), but before it is even called.
Here is my code:
char input, output;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Ready\nEnter input text");
  while (!Serial.available()); // wait till serial available
  delay(2000);
  byte avail = Serial.available() - 1;//extra newline char at end that we don't want
  char inBuf[avail];
  //Serial.println(avail);
  Serial.readBytes(inBuf, avail);
  Serial.read();
  Serial.print("'");
  Serial.print(inBuf);
  Serial.println("'");
  delay(1000);
  Serial.println(avail);//problematic line
}

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

}

When i have the line uncommented, the output is:

Ready
Enter input text
'asd&.'
4

When all i have typed is 'asd' (no quotes).
With the line commented out, the output is as expected:

Ready
Enter input text
'asd'

I have no clue how it is happening, and should be physically impossible, since it is changing code before it is called.

Your string needs to end with a null character '\0'.  I think yours does not because of the way that you filled the buffer, so you're getting whatever junk is in memory next to your array printed in addition to the array itself.


Serial.println() cuts off characters I want to print a string together with number. My code is

Serial.println("Test " + index++);

(In setup() I initialized variable index to 0.) In Java it would output

Test 0
Test 1
Test 2
Test 3
...

But I get this output instead:

Test
est
st
t

Can anybody explain it to me please?

Serial.println() prints the value of one expression. The expression you passed it was `("Test " + index++).

In C/C++ a character literal such as "Test " evaluates to the memory address its first character. Adding 1 to that address gives the address of the next (or 2nd) character. Adding 2 to it gives the address of the 3rd character, and so on.

To get what you were expecting, the value of the literal, AND the value of the index, you would write:

Serial.print("Test ");
Serial.println(index++);

If you had created a String variable with the value "Test ", then the String expression, ("Test " + index++) would have been evaluated differently: The "+" operator would have concatenated the String "Text ", with the String equivalent of the current value of "index"; but that isn't the way a character literal is treated. There is a C++ String library among the Arduino libraries but it's use is not recommended because Strings get reallocated and copied when they get concatenated, resulting in excessive memory use, and the Arduino has very little memory.


Arduino-ESP8266 socket I am programming an ESP8266 module via Arduino IDE. I basically have to use it as a server that can light up a led when a client sends a request.

This is okay but I have to implement it with a NONCE and AES encryption system to prevent replay attacks. My problem is that my esp server has to send a value to a client but I only saw the ESP as a data receiver and I can't send custom strings.
This is my code but it does not work because I have problems with the serverClients[i].write(randomstr,4); function

I highlighted the non working part of the code

#include <ESP8266WiFi.h>

#define RANDOM_REG32  ESP8266_DREG(0x20E44)
#define MAX_SRV_CLIENTS 3
const char* ssid = "********";
const char* password = "********";

WiFiServer server(7000);
WiFiClient serverClients[MAX_SRV_CLIENTS];

void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
delay(5000);
Serial.print("\nConnecting to "); Serial1.println(ssid);
server.begin();
server.setNoDelay(true);
Serial.print("Ready! Use 'port ");
Serial.print(WiFi.localIP());
Serial.println(" 7000' to connect");
}

void loop(){
uint8_t i;
if (server.hasClient()){
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (!serverClients[i] || !serverClients[i].connected()){
if(serverClients[i]) serverClients[i].stop();
serverClients[i] = server.available();
continue;
}
}
//no free spot
WiFiClient serverClient = server.available();
serverClient.stop();
}
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
if(serverClients[i].available()){
while(serverClients[i].available()) Serial.write(serverClients[i].read());

//THIS IS THE NON WORKING PART
long randNumber = RANDOM_REG32 % 10000;
 Serial.println(randNumber);
String randomstr = String(randNumber);
 serverClients[i].write(randomstr,4);
}
}
}

if(Serial.available()){
size_t len = Serial.available();
uint8_t sbuf[len];
Serial.readBytes(sbuf, len);

for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
serverClients[i].write(sbuf, len);
delay(1);
}
}
}
}

I guess I have some problems with char arrays, strings, etc... but I can't make it work

Replace the non working code with this and it will compile:

long randNumber = RANDOM_REG32 % 10000;
Serial.println(randNumber);
size_t length = 4;
char randomstr[length];
itoa(randNumber, randomstr, 10);
serverClients[i].write(randomstr, length);


Is the C++ STL fully supported on Arduino? I don't yet own an Arduino board to run code on, and as the title says, I'm curious if the C++ STL is fully supported on Arduino and already part of the Arduino IDE. The STL is probably the most efficient, fully tested, and resource-minimal (which is a slightly redundant phrase, as I already mentioned efficiency) publicly available C++ code out there, and would make life much easier to code for Arduino.

If the STL is not a part of Arduino IDE, then how to include specific libraries such as <algorithm> and <utility>? (I'm very tempted to ask "why isn't it included?" but that seems too broad.)

The STL is not a part of Arduino IDE.

Although efficient by desktop standards, the consensus is it doesn't fit comfortably in an Arduino's limited space.  That said, here's someone who seems to have done it:

https://github.com/maniacbug/StandardCplusplus

Check out the forks, they seem more up to date


attiny85: ISR not triggering for PCINT2? I am using an attiny85 to read the fan speed reported by a pair of 4-wire fans. I had planned to attach the TACH output from the fans to pins 1 and 2, but I ran into a problem: I was able to handle interrupts on pin 1 without a problem, but I can't get the ISR to trigger for changes on pin 2.  Code demonstrating the problem looks like this:

#define PIN_LED 0
#define PIN_TACH2 2

void setup() {
  cli();
  pinMode(PIN_TACH2, INPUT_PULLUP);
  pinMode(PIN_LED, OUTPUT);

  GIMSK |= _BV(PCIE);
  PCMSK |= _BV(digitalPinToPCMSKbit(PIN_TACH2));
  sei();
}

void loop() {
  digitalWrite(PIN_LED, 1);
  delay(2000);
}

ISR(PCINT0_vect) {
  byte tach2;

  tach2 = (PINB & _BV(PIN_TACH2));

  if (! tach2) {
    digitalWrite(PIN_LED, 0);
  }
}

If I replace the definitions of PIN_TACH2 and PIN_TACH2_INT with
pin 1, such as...

#define PIN_TACH2 1
#define PIN_TACH2_INT PCINT1

...it works just fine (interrupts also works for pins 0 and 3).

Why can't I handle pin change interrupts for pin 2?

for @chrisl

This is just testing code. The LED remains on until the ISR fires, at which point it will go out for up to 2 seconds.  With interrupts attached to pins 1 or 3, it works as expected: a falling edge on the pin causes the LED to go off.

On pin 2, the ISR never triggers.

So, it turns out that it was a really stupid problem and entirely my fault, but I'm going to leave this question here in the hopes that it will prevent someone else from running into the same issue.

The answer is...

DISCONNECT THE PROGRAMMER BEFORE TESTING YOUR SKETCH

That's it.  With the programmer disconnected, it all behaves as expected.


Sound quality is poor using a piezo in TinkerCad I did a quick search and couldn't seem to find this question posted already, but I'm sure it must have so forgive me if it's a repeat.

I'm using a piezo and Arduino on TinkerCad to produce notes using the tone function, and the quality is not great (it's as if I can hear beats while the note is playing). I vaguely remember a colleague telling me this was an issue with the way my computer speakers handle square waves (I have a Macbook Air if that makes any difference), but I'm not positive. Has anyone had success in using TinkerCad to produce nicer sounding notes? If not, can anyone explain what the issue is to me?

Thank you!

To pack the comments into a proper answer to the question:

As Majenko stated in the comments, Tinkercad is a simulation. The codes doesn't get compiled and uploaded to hardware. Instead Tinkercad interprets the code on the fly. Simulations are not perfect clones of the real hardware, so you cannot expect the same performance from it as from the real Arduino. Also it is not build for producing high quality sound. The focus is entirely on simulating how the Arduino works.

If you are using this with a real Arduino you most likely will not have the glitches in sound.

What you are currently hearing is not a problem of Arduino, but of Tinkercad. You could file a problem with the developer, but probably they will not think this is an issue, or they will give it a very low priority.


How to store gps values in EEPROM arduino? I have two successfully working individual programs,
1.GPS coordinate extract program.
2.EEPROM saving and reading program.
now all I want to do is combine them both, whenever GPS location is updated ,I want to save that latitude data to EEPROM memory repalcing the previously saved data, but I guess my program is unable to save it,its just showing blank spaces when reading EEPROM,please help me guys..here is my code.

#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#define RXPin 8
#define TXPin 9
#define GPSBaud 9600
#define ConsoleBaud 9600

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

// The TinyGPS++ object
TinyGPSPlus gps;
#include <EEPROM.h>
int address = 0;
int read_value = 0;
char data;
void setup()
{
  Serial.begin(ConsoleBaud);
  ss.begin(GPSBaud);
  Serial.println("Previous value stored :");
  for(address = 0; address < 25; address ++)        // read the entire EEPROM memory
  {
    read_value = EEPROM.read(address);
    Serial.write(read_value);
  }
  Serial.println("\n");

}

void loop()
{

  while (ss.available() > 0)
    gps.encode(ss.read());

  if (gps.location.isUpdated() || gps.altitude.isUpdated())
  {
    Serial.print("Location: ");
    Serial.print(gps.location.lat(), 6);
    Serial.print(",");
    Serial.print(gps.location.lng(), 6);
    Serial.println("\n");

    data=(gps.location.lat(), 6);

    for(address = 0; address < 25;  )
    {
      EEPROM.write(address, data);
      address ++;
    }
  }
}

Consider TinyGPS++ over TinyGPS only if you are running on Due or processor which can take advantage of the higher precision of 64-bit “double” floating-point.

char data; should be double data;. You're wasting resources otherwise.

data=(gps.location.lat(), 6); isn't how you do it. You only need to specify precision when writing to Serial, like Serial.print(gps.location.lat(), 6);. Make it data = gps.location.lat();.

address ++; should be address = address <=512-sizeof(address) ? (address + sizeof(data)): 0 ;

address <=512-sizeof(address) ensures that the last value written to the EEPROM is written in it's entirety.

Alternatively, I would recommend this to save you data structure directly to EEPROM, and what @jfpoilpret mentions.


Doesn't Arduino reports DSR (Data Set Ready) correctly? I was told, that when computer opens port, it sends DTR (Data Terminal Ready) signal to Arduino, which initiates Arduino reboot.

This looks like part of DTR / DSR flow control. According to this, in response to DTR, Arduino should no only reboot, but also raise DSR (Data Set Ready) signal when it is ready to receive data

And computer should wait for it.

Does it happen so?

No, it does not, and can not for the simple reason that there is no DSR line connected to the processor.

Generally host software / serial driver configuration ignores DSR.

On the boards with an 8u2/16u2 the custom firmware therein can report whatever virtual state of the signal it is programmed to. On those with hardware USB-serial they will report however the pin is hard wired, or whatever value it is pulled to or floating at.

None of these (possibly excepting a Leonardo type board or an ARM one with native USB) reflect anything about the state of the target processor, so software hoping to talk to an Arduino should ignore the DSR signal.


Arduino Countdown without using delay() I am working on a project which requires countdown from 30sec to 0sec. I can't use delay() function because I am taking input from keyboard during countdown. millis() function wont help because my board will be active for more than 50 days. I require something like counter which I can reset after or before completion of 30sec.

Background

The function millis () returns an unsigned long, which is the number of milliseconds since the processor was reset (until it overflows).

See: http://arduino.cc/en/Reference/Millis

Example:

unsigned long startTime = millis ();

Since there are 232 bits in an unsigned long it can count from 0 to 4294967295.

Computing this in terms of days we have:

2^32 / 1000 / 60 / 60 / 24 = 49.710 days

So, the number returned will overflow (go back to zero) after around 49 days (almost 50 days, as the reference page says).

Is this bad?

No. Is it bad your clock overflows (goes back to zero) at midnight? No it isn't.

Let's clear up some misconceptions:

The processor does not reset when the timer overflows.
The timer does not stop.
Nothing "bad" happens.

All that happens, on a timer overflow, is that it goes back to zero and starts counting up again. Just like your clock does.

How do I time an event?

There are two ways of timing something (eg. a minute from now). You can add or subtract. Because of the way that unsigned arithmetic works, subtracting is the correct way.

Example of adding - not recommended!

I want to detect a minute in the future...

unsigned long startTime = millis ();
unsigned long whenToStop = startTime + 60000;

...

if (millis () >= whenToStop)
  {
  // do something
  }

This will work most of the time, but not when the timer overflows. Let's see why:

Say the timer will overflow in 50 seconds, that is, it is currently:

2^32 - 50000 = 4294917296 (0xFFFF3CB0)

Now we add 60000, and get:

2^32 - 50000 + 60000 = 10000 (0x2710)

Our "whenToStop" variable has overflowed and is now quite small. And thus it is immediately less than the current time, and our check for when a minute is up fails, it appears to be up immediately.

Example of subtracting - recommended

I want to detect a minute in the future...

unsigned long startTime = millis ();
unsigned long interval = 60000;

...

if (millis () - startTime >= interval)
  {
  // do something
  }

This will work all the time. Let's see why:

Say the timer will overflow in 50 seconds, that is, it is currently:

2^32 - 50000 = 4294917296 (0xFFFF3CB0)

In 50 seconds the timer wraps around and goes to zero. Subtracting now gives us:

// millis () - startTime   = elapsed interval
    0        - 4294917296  = 50000 (0xC350)

The subtraction "wrapped around" and gave us a small number. If you use a scientific calculator and try the above you may get a result of 0xFF0000C350. The initial 0xFF is the "extended sign bit", in effect, however as the field is unsigned, and only four bytes long, the sign bits are dropped, giving a small positive number, not a large negative one.

Demo using the Mac Calculator app:

In 60 seconds the timer goes to 10000. Subtracting now gives us:

// millis () - startTime   = elapsed interval
    10000    - 4294917296  = 60000 (0xEA60)

So the elapsed interval (the difference) is now 60000, which is what we wanted.

Directly after we set up startTime and millis we will see a sequence like this:

millis ()   -  startTime    =  difference
                             (modulo 2^32)
4294917296     4294917296               0  <-- we start timing here
4294917297     4294917296               1
4294917298     4294917296               2
...
4294967295     4294917296           49999  <-- largest unsigned long value
         0     4294917296           50000  <-- wraps here back to zero
         1     4294917296           50001  <-- keeps counting up
...
      9999     4294917296           59999
     10000     4294917296           60000  <-- time's up!

Recommended method

Use unsigned long (not just long) for "time" variables.
Record the start time of some event (eg. a debounce, when you start feeding the fish, etc.)
Subtract the start time from the time now, giving a difference.
See if the difference exceeds the desired interval.

eg.

startedFeedingFish = millis ();

...

if (millis () - startedFeedingFish >= 20000)  // feed them for 20 seconds
  {
  // stop feeding the fish
  }

Can't I just reset millis?

You can, but you don't need to. Plus it may well throw out any library you are using that does not expect millis to be reset. Plus you have to decide exactly when to do it. It would need to be a time when you aren't using millis. For example if you happened to be feeding the fish in the above example, and your code reset millis, then the fish will get an awful lot of food!

What about micros?

The function micros() returns the number of microseconds since reset. This also wraps around, however since there are 1000 microseconds to a millisecond it will wrap around faster.

 2^32 / 1000 / 1000 / 60  = 71.58 minutes

http://arduino.cc/en/Reference/Micros

However you can use exactly the same technique to keep track of time to the microsecond interval. Be aware that you can't time more than 71.58 minutes this way though.

Also be aware that the resolution of micros() is four microseconds (because of the timer prescaler) so you won't ever be able to time a one or two microsecond interval.

Limitations

If you are using millis() you cannot time more than 49.71 days, and if you are using micros() you cannot time more than 71.58 minutes, without extra code to detect the wrap-around. For long intervals I suggest a real-time clock, since that would be more reliable during power failures, or when you replace batteries, etc.

Reference

This answer taken from my page http://www.gammon.com.au/millis


How do I repeat else if (cmd == '3') until I press another cmd? This code is for automatically opening and closing a window using a motor with senors such as dust, humidity, temperature, and rain sensor with bluetooth module through phone. With this code if I press 1,2 it would close or open the window and 3 would let the window open or close regarding the measures that the  sensor reads. Right now pressing 3  would only simulate this once and then turn off untill I press it again
So I would want this part
 else if (cmd == '3')
to repeat itself until I press another cmd button so the window keeps opening and closing.

//////////////////////////////////////////////////////////////////////////
#include <SoftwareSerial.h>
#include <Stepper.h>
#include <DHT.h>
#define DHTPIN A1
#define DHTTYPE DHT11
#define D_IN 3
#define A_IN A0

int Txpin = 7;
int Rxpin = 8;
int stepsmotor = 1024;
const int stepsPerRevolution = 64;
SoftwareSerial BTSerial(Txpin, Rxpin);
DHT dht(DHTPIN, DHTTYPE);
int measurePin = 0;          // measurePin을 0으로 설정합니다.
int ledPower = 2; // ledPower를 2로 설정합니다.
int samplingTime = 280;    // samplingTime을 280으로 설정합니다.
int deltaTime = 40;           // deltaTime을 40으로 설정합니다.
int sleepTime = 9680;       // sleepTime을 9690으로 설정합니다.
float voMeasured = 0;      // voMeasured를 0으로 설정합니다.
float calcVoltage = 0;       // calcVoltage를 0으로 설정합니다.
float dustDensity = 0;       // dustDensity를 0으로 설정합니다.

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

void setup()
{
  Serial.begin(9600);
  BTSerial.begin(9600);
  myStepper.setSpeed(550);
  pinMode(ledPower,OUTPUT);
  pinMode(D_IN, INPUT);
}

void loop()
{
 if (BTSerial.available())
  {
    char cmd = (char)BTSerial.read();
    if(cmd == '1'){
      for(int i=0; i<(32*3-6); i++){
    myStepper.step(stepsPerRevolution);
      }}
    else if (cmd == '2')
      for(int i=0; i<(32*3-6); i++){
    myStepper.step(-stepsPerRevolution);
   }
    else if (cmd == '3'){
     int dIn = digitalRead(D_IN);
  double aIn = analogRead(A_IN);
    int h = dht.readHumidity();
    int t = dht.readTemperature();
digitalWrite(ledPower,LOW);
  delayMicroseconds(samplingTime);

  voMeasured = analogRead(measurePin);
  delayMicroseconds(deltaTime);
  digitalWrite(ledPower,HIGH);
  delayMicroseconds(sleepTime);

  calcVoltage = voMeasured * (5.0 / 1024.0);

  dustDensity = (0.17 * calcVoltage - 0.1) * 1000;

    Serial.print(dustDensity);
    Serial.println(" ug/m3");
  Serial.print("Digital Input = "); Serial.println(dIn);
  Serial.print("Analog Input  = "); Serial.println(aIn);
  Serial.println();
    Serial.print("humidity:");
    Serial.println(h);
    Serial.print("temperature:");
    Serial.println(t);
    delay(1000);

    if (t >= 25 or h >= 70 or dustDensity >= 100 or aIn <= 50)
     for(int i=0; i<(32*3-6); i++){
    myStepper.step(stepsPerRevolution);
    }
    else
     for(int i=0; i<(32*3-6); i++){
    myStepper.step(-stepsPerRevolution);
    }

  delay(3000);
    }
    else if (cmd == '4'){

    }
      }
    }

I would suggest to rewrite your program as a Finite State Machine (FSM). It's a simple but powerful concept. You first model your program into multiple states, that are connected through state transitions. It is a good way to first draw this as a graph. You can see one example in my answer to this question.

For your case I would use your "modes" as states for the FSM plus an idle state, where simply nothing happens. You would start in the idle stat and then change to different states depending on the Serial input. In the states/modes 1 and 2, which are only one time actions, you would execute the action in the state and then directly change to the idle state again.

From the programming side a FSM can be implemented in multiple ways. I have seen FSMs using a variable and switch cases, but also FSMs, that use a function pointer. The last is elegant, but not as easy to understand for beginners. So I suggest you use the switch-case variant, as you can see in the answer linked above. Basically you use a variable (something like int or char) to represent the current state. In your loop() function you then build a switch-case statement for different values of your state variable. Often an enum is used as variable type to make the code more readable. In each case statement you write the code for the corresponding state. In your state/mode 3 you would check your sensors and close/open the window as needed, then leaving the case statement. When the next iteration of the loop() function happens, the FSM will still be in this state, checking again the sensors. In your states/modes 1 and 2 you would check, if the window already has the needed state and - if not - drive to motor to close/open the window. Then - still in the case statement - you would set the state variable to the idle state, then leave the case statement. So in the next interation of the loop() function the FSM will be in the idle state, doing nothing, making the states/modes 1 and 2 a one-shot everytime, that you activate them.

In contrast to the code in the linked answer, I would read the Serial data outside of the switch statement, since you will write directly to the state variable in there.

I strongly suggest, that you try to implement this. It is an important principle, that makes your more structural sound and easier to extent. A great learning experience.


External Flash Memory for ATtiny85 I'm designing a lightweight circuit, but the ATtiny85 micro-controller I'm using to power it doesn't have nearly enough flash memory to store the code for the devices I'll have hooked up to it (It has 8kb of flash). I was wondering if it'd be possible to have the ATtiny use compiled code from an external flash memory chip of larger capacity elsewhere on the board like its own internal memory. Thanks in advance.

No, it's not possible.

AVR chips can only execute code from their internal flash.


Retrieve value from ThingSpeak using ESP8266 with Arduino setup I just started learning ESP8266 and in my first project I am successfully able to send data to ThingSpeak.com using ESP8266 with following code:

uploadData() {
  String apiKey = "ESDS8678890SDDS";
  String myData = "45.5"; // example of data to send
  if (espClient.connect(server,80)) {
    String postStr = apiKey;
    postStr +="&field1=";
    postStr += String(myData);
    postStr += "\r\n\r\n";
    espClient.print("POST /update HTTP/1.1\n");
    espClient.print("Host: api.thingspeak.com\n");
    espClient.print("Connection: close\n");
    espClient.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
    espClient.print("Content-Type: application/x-www-form-urlencoded\n");
    espClient.print("Content-Length: ");
    espClient.print(postStr.length());
    espClient.print("\n\n");
    espClient.print(postStr);
    Serial.print(postStr);
    Serial.print("My Data: ");
    Serial.print(myData);
    Serial.print("\n");
  }
  espClient.stop();
}

But I have no idea how to retrieve data from ThingSpeak using ESP8266.

// Using XXXXX here as my channel is private
GET https://api.thingspeak.com/channels/XXXXXX/fields/1.json?results=2

I think I have to use the above GET string to get the fields data. But I don't know how to create the request string.

Help would be appreciated.

Thanks.

Connect to the server as usual with espClient.connect(). The following request should return a JSON object containing your channel description and the first 2 entries in your feed:

espClient.println("GET /channels/CHANNEL_ID/feeds.json?results=2 HTTP/1.1");
espClient.println("Host: api.thingspeak.com");
espClient.println("Connection: close");
espClient.println();

If it's a private channel, then you must supply your Read API key like this:

espClient.println("GET /channels/CHANNEL_ID/feeds.json?api_key=<your API key>&results=2 HTTP/1.1");

Notice that I use println() and not print() in order to implicitly terminate each request line properly. You should end each line not with \n but with \r\n. You only need to type this yourself if you use print().

To read the returned JSON data:

while (espClient.available() == 0);  // wait till something comes in; you may want to add a timeout here

unsigned long lastRead = millis();  // keeps track of last time a byte was read
while (millis() - lastRead < 2000) {  // while 2 secs havent passed since a byte was read
  while (espClient.available()) {
    Serial.print(espClient.read());
    lastRead = millis();   // update last time something was read
  }
}
client.stop();  // close socket

To parse the JSON string, you either get a library from GitHub or you parse the string yourself.


How does this eBay relay board connect to the Arduino I bought a single channel relay on eBay and besides the NC/COM/NO, it has six pins and a jumper.

It is not possible to see the labels on the image, but the labels are:

X  X--X  X  X  X
VCC   -IN+   GND

The default jumper position is shown above with a - mark.

Which pins should I use for VCC, GND and ARDUINO? Is the jumper on the correct position?

Your module consists of both an optocoupler (large black rectangular device) and a P-channel MOSFET driver circuit for the relay.

VCC and GND are used to power the MOSFET and relay, and so should be connected to a power source suitable for driving the relay (if it's a 5V relay then the +5V and GND pins of the Arduino - if it's a 12V relay then a 12V power supply).

The interface to the Arduino is through the optocoupler. The Arduino sees that as just an LED, so you can wire it up just like any other LED.  The circuit contains a current limiting resistor already, so you don't need to worry about that at all.  So you connect the - of the input to GND and the + to an IO pin, or connect the + to +5V and the - to the IO pin, depending on which polarity of drive you want to have.

The jumper is optional to allow you to create one of those two links on the board - say connecting - to GND or connecting + to VCC so you don't need the extra wire.


Why won't my motor run? I am trying to run a small 3v motor with a Keyestudio MEGA 2560(which is the same as the Arduino MEGA 2560). I am getting a consistent 5 volts everywhere I check with a multimeter. The voltage drops to 0.01-0.05 once I connect the motor. The motor runs once it is connected directly to the Arduino's 5v output pin. The motor draws about 600mA consistently when we connect it directly to 5v.
My code is rather basic, which just sends voltage out pin 5.  I am not using any shield. controlling the speed is not my main concern here, though later on in my project I would like the motor to be able to reverse as well.
I found this circuit diagram in "Arduino for dummies," and found this same diagram on many other websites too.
void setup() {
  pinMode(5,OUTPUT);
}

void loop() {
  digitalWrite(5,HIGH);
}

simulate this circuit – Schematic created using CircuitLab

An NPN bipolar transistor requires a current to flow from base to the emitter which is then multiplied by the beta of the transistor controlling the maximum current which flows from the collector to the emitter.  A 2n2222 beta is about 100.  Let us calculate the amount of current which will be allowed to flow from the collector to the emitter of the 2n2222 transistor.  First calculate the current from the base to the emitter:
I(be) = (5.0 volts- 0.7 volts) / 1,000 ohms
I(be) = .0043 Amps

Use this current to find the maximum current flowing from the emitter to the collector:
I(ce) = 100 x I(be) = 0.430 Amp or 430mA

We see that the transistor does not provide enough current to drive a 600mA motor.
We need to reduce the value of R1 such that I(ce) is at least 600mA which means that I(be) needs to be at least 6mA.  Rearranging the earlier equation to find R1:
I(be) = (5.0 volts- 0.7 volts) / 1,000 ohms
I(be) = (5.0 volts- 0.7 volts) / R1
R1 = (5.0 volts- 0.7 volts) / I(be)
R1 = (5.0 volts- 0.7 volts) / 0.006 Amps
R1 = 716.67 ohms

However, because of the large amount of I(ce) current necessary to drive the load, we find the transistor reaching it's limits and the beta of the transistors drop apprecably:

This diagram is a little hard to understand.  And there is no curve for 600mA.  But we can get an idea of what to expect if we look at the 500mA curve.  We see that in order to get less than a volt drop across the transistor (V(ce)) we need to pump in more than 10mA (I(be)).  To get similar results for 600mA we would likely approach 20mA and now we are dangerously close to the processor pin current driving capabilities.
A common alternative is to use a Darlington Transistor configuration:

The resulting beta is essentially the product of the individual transistor's betas.
Let's do some rough calculations.  If the 2n2222 that switches the load current has a lower beta of about 10, we would need about 60mA to switch a 600mA current.  To generate 60mA through the transistor connected to the processor, we would need about 0.6mA from the processor.  That's really small and we can afford to triple it to ensure reliable operation.  So let's pick 3mA:
R1 = (5.0 volts- (2 * 0.7 volts)) / 0.003
R1 = 1200 ohm

So a 1K ohm resistor should likely work.


Arduino Uno with crystal Are there Arduino UNO R3s which use a crystal instead of a ceramic resonator?

(Frankly, I don't understand this cheapness: if you really want to save on component cost you can run both AVRs on the same crystal. The 16U2 always has a crystal.)

Some of the Freeduino boards use crystals although the newer ones now use a cheaper USB to serial chip (the CH340) instead of the Atmel chip used on the Arduino Uno.

The diavolino is another build-it-yourself board that has a crystal. I am sure there are many others. The ruggeduino is another that uses a crystal and also markets itself as being practically indestructible. Their "How to Destroy an Arduino" is well worth a read for things to avoid doing to your Uno.


Two Arduinos get out of sync after a few seconds I built a small PCB that has some LEDs (bare NeoPixel 5050) and an IR receiver on it. The microcontroller is an ATtiny85, and the PCB is powered by a LiPoly battery (3.7V). The circuit normally stays in ULP sleep mode until a pin change interrupt wakes the circuit. The pin change interrupt is tied to the IR receiver so when the receiver gets a signal from a remote (38kHz modulated IR burst) a lighting sequence is triggered. I have multiple of these PCBs running the exact same code (shown below). When the PCBs receive an IR signal they all start at the same time, but then after a few seconds they start to drift apart. The lighting needs to be synchronized. What is the reason for this drift and how can I eliminate it? Is it due to different battery voltages? That would be the only physical difference between any two PCBs. Thanks for your help.

#define IR_PIN      4
#define LIGHT_PIN   0
#define DELAY_TIME  200

#include <Adafruit_NeoPixel.h>
#define NUM_PIXELS  2
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_PIXELS, LIGHT_PIN, NEO_GRB + NEO_KHZ800);

#include "avr/interrupt.h"
#include "avr/sleep.h"

void setup() {
  pinMode(IR_PIN, INPUT);
  strip.begin();
  pixelsOff();
}

void loop() {
  sleep();

  for (int i = 0; i < 5; i++) {
    pixelsOnRed();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
    pixelsOnGreen();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
  }

  for (int i = 0; i < 5; i++) {
    pixelsOnBlue();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
    pixelsOnRed();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
  }

  for (int i = 0; i < 5; i++) {
    pixelsOnGreen();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
    pixelsOnRed();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
  }
}

void pixelsOff() {
  strip.setPixelColor(0, 0, 0, 0);
  strip.setPixelColor(1, 0, 0, 0);
  strip.show();
}

void pixelsOnRed() {
  strip.setPixelColor(0, 255, 0, 0);
  strip.setPixelColor(1, 255, 0, 0);
  strip.show();
}

void pixelsOnGreen() {
  strip.setPixelColor(0, 0, 255, 0);
  strip.setPixelColor(1, 0, 255, 0);
  strip.show();
}

void pixelsOnBlue() {
  strip.setPixelColor(0, 0, 0, 255);
  strip.setPixelColor(1, 0, 0, 255);
  strip.show();
}

ISR(PCINT0_vect)
{
    //This is not needed for the current sketch
}

void sleep() {
    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
    PCMSK |= _BV(PCINT4);                   // Use PB3 as interrupt pin
    ADCSRA &= ~_BV(ADEN);                   // ADC off
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

    sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
    sei();                                  // Enable interrupts
    sleep_cpu();                            // sleep

    cli();                                  // Disable interrupts
    PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
    sleep_disable();                        // Clear SE bit
    ADCSRA |= _BV(ADEN);                    // ADC on

    sei();                                  // Enable interrupts
}

What is the reason for this drift and how can I eliminate it?

two solutions:

1) try using crystal oscillators;

2) try driving on arduino with the other arduino's clock output.


Arduino UNO code ignores variables selectively This is the first code I wrote for my UNO R3 just to feel out the functions and I've already got some jankiness. Throughout this description I am referring to the first two if statements one inside the other one.

I'm trying to increment i every time the signal is activated and then j is used to create a small space of time where the button being pressed will not increment i. My problem is my if statement involving j seem to be totally ignored. I've tried multiple configurations of the if statement structure to no avail.

Here is where things get interesting. So upon setting up the serial connection back to my PC to debug this irritating problem and printing out the actual value of j (to see why it was triggering my if statement prematurely) it magically fixed the problem. It's like until the program literally acknowledges j's value in the print statement it doesn't exist but if it does it works. Any ideas on this?

Note: the serial monitor in both picture depicts consecutive iterations with the signal activated the entire time.

This picture shows the serial monitor after running with the button pressed but the print statement commented out

This picture shows the serial monitor at a space where the button was pressed and held (same time frame as image 1) but in this one it increments i to 3 and then continues incrementing j. How is this happening?

Its hard to see you code, but I think I can make a pretty good guess from your description what is going on.

It seems that you are using the time it takes to increment a value as a way to slow down your code. I think you are underestimating the speed of the arduino. The time it takes to count to 200 (if I'm reading your pictures right) is almost instant; However, you then start printing to with serial each time. Once the serial buffer is full, Serial.print() will wait until there is room in the buffer to place the new value. This time is still small, but making the code wait for it to pass 200 times will take much longer than just waiting for a number to increment to 200.

I think that having added a print statement is slowing down the code enough that your increment based delay is having a noticable effect. What you should do is use the void delay(unsigned long milliseconds); function to cause the code to stop for a bit after it first detects the button has been pressed, and then see if its still pressed afterward. You can also use delayMicroseconds(unsigned int) for shorter but more precise timing. Or better yet, use the unsigned long millis(); function to grab and store the time when the button was activated, and continue polling the current time until the desired delay has been acheived. That way is more code, It allows the code to do something productive while it waits or keep looping.


What do the TinyGPS++ output parameters mean? TinyGPS++ give many output parameters. Where can I find explanation what do all output parameters mean? I don't understand what is the meaning of the following parameters:

  Course Speed Card  Distance Course Car

UPD

2365 is distance to London

wnw is the direction to London: https://en.wikipedia.org/wiki/Points_of_the_compass#Compass_point_names

0.00 - Vertical speed?

0.06 - Horizontal speed?

294.06 - ???

As you can see when you look at the source code of the FullExample.ino that is part of the TinyGPS++ library, the values you marked are:

Course Speed Card*: The current speed (in km/h), course (in degrees) and cardinal course (which is the course translated to a cardinal direction on a compass, i.e. N,S,E,W, NE, NNW, etc.) of the GPS receiver (i.e. you).
Distance Course Card**: The distance (in km) and course and cardinal course to some location or waypoint (London in this example).

After the information you added in your edit, this means the following:

0.00 is your current course over ground (i.e. due North)
0.06 is current current speed over ground (i.e. as good as stationary)
N is your current cardinal course
2365 is the distance to London (km)
294.06 is the bearing to London from your location
WNW is the cardinal bearing to London

* this is also known as SOG (Speed Over Ground) and COG (Course Over Ground, which is used in (aero)nautical navigation) or Bearing.

** this is also known as DTG and CTS (Distance to Go and Course to Steer) when navigating to a GPS waypoint.


Use LDR with 220 ohm resistor I have read many tutorials on LDR(Light dependent resistor) with Arduino which includes a 10 kilo ohm resistor but can i use it with 220 ohm resistor or even without resistor.

Unless properly filtered, an LDR has a spectral sensitivity very
different from the human eye, which makes it unsuitable for any kind of
photometric measurement. It is also typically very loosely specified,
so you won't know the illuminance it receives better than a factor two
even if you measure its resistance very accurately. Thus, if you really
need accurate illuminance measurements like, e.g., for complying with
legal requirements, then forget the LDR and get a real luxmeter with a
calibration traceable to the SI lux standard.

Now, if you only want to tell apart substantially different illuminance
levels, like sunny and cloudy, then the LDR is fine. And don't let
Majenko scare you into believing you really need to know the resistance
of your pullup: it doesn't really matter.

That being said, you will get the best sensitivity if your pullup has a
resistance in the same range as the resistance of the LDR in the typical
conditions you will use it. Thus, if your LDR is nominally 10 kΩ, I
would avoid pulling up with 220 Ω, as the sensitivity would be very
poor. A 10 kΩ pullup resistor would be ideal, but the internal
pullup of the I/O pin (20 – 50 kΩ, 30 kΩ typical) should
be fine.

Many tutorials on LDRs use the ADC reading to compute a resistance, for
which you need to know the resistance of the pullup. If you want to
follow this path, just assume a 30 kΩ pullup. All your numbers will
be somewhat off, but that makes absolutely no difference, because you
don't know how to relate the resistance to the illuminance anyway.

I would suggest you forget about computing the resistance. Just look at
the raw ADC readings instead. Take some test readings in the typical
conditions that are of interest to you: now you have a baseline to which
you can compare further readings against. Keep in mind, though, that the
ADC readings get lower as the illuminance gets higher. And beware
that the resistance of the pullup, and probably that of the LDR also,
can be sensitive to temperature variations. You may do a hairdryer test
to check whether it gets really bad.

Example code? This one is pretty trivial:

/* Connect an LDR between A0 and GND. */

void setup() {
    pinMode(A0, INPUT_PULLUP);  // enable pullup for the LDR
    Serial.begin(9600);
}

void loop() {
    Serial.println(analogRead(A0));  // print out a reading
    delay(1000);                     // delay for one second
}


Sensor for underground water tank level In a similar way to the question  "best way to determine if a 5 gallon water jug is getting empty", I'm looking for a way to measure water in a container. This is so it can be connected to an Arduino for logging and reporting.  But it's a very different container.

I have a home with the household water supplied from an underground concrete tank (around 3000 US gallons, 11000 litres).  Although there is a float switch cutout when it gets empty (to protect the pump), I'd like to know it's gettting low long before that (as it takes a while before a tanker delivers a fresh load).  Ideally something that measures exactly or in steps (at least in eights of a load), so software can predict when it'll run out based on average usage, and it can be monitored online when away.

The tank has a heavy concrete hatch, and a small hole that has an existing primitive dipstick, so access is limited.  It's in a harsh desert environment, but the pump room and power are only a few feet away.

Some ideas I had:

suspend an array of float switches with strings of different lengths from a bar inside the tank, and wire them all back to a controller.  Hard to install, ugly, low tech. Or something similar on a vertical pole.
contacts (like a US 2 pin plug) on a vertical pole that again are connected back to a controller (probably using a ribbon cable).  Corrosion/anodes might be a problem, although power could just be a short pulse at times.  Condensation, spiders webs and dead bugs may give false readings.
run a fully insulated cable vertically down it, and use as an antenna to send a pulse through, and use the difference between how it works as an antenna in air, and in water, (like an SWR meter) to calculate how far down the water is.
ultrasonic (or light?) distance finder mounted under the hatch.  Range needs to be up to 2 metres (6 feet).
depth finder (sonar) on a float.  Biggest challenge here is getting the signal out (long cable might get tangled when the tank fills).

The last two would be even better if they were wireless (to save running a cable that might get damaged) but I don't think I'd get the battery life I'd like (1 year or more).

Any other ideas?  Has anybody ever done this?

http://playground.arduino.cc/Main/Waterlevel

The above link had a nice approach.

The principle is the same as traditional pneumatic level gauge, excepted that the dial indicator is replaced by a pressure transducer, and the manually-operated pump is replaced by an aquarium air pump.

When the pump is on, air flows through the weighted PVC pipe to the bottom of the tank, where bubbles appear. At this moment, the air pressure in the PVC pipe is equal to the hydrostatic pressure at the bottom of the tank. As the water pressure at the bottom of the tank is directly proportional to the water level, the same goes for the air pressure in the PVC tube. The air pressure is then converted to an analog voltage by the pressure transducer. This voltage can be read easily by the arduino.

A big advantage of this method with regards to other existing techniques is that no electronic or metallic parts needs to be placed in the tank, where the environmental conditions (mainly humidity) are not favorable. This avoids any risk of corrosion.


How to fix Arduino restarting when two servos are powered by an external power? Can anyone help me fix this? It always restarts when I power the servos with an external battery. I connected one battery to Arduino and one battery to servos, each 5V, but my Arduino keeps restarting.

You will need to fix this on your own but I can suggest some things that you will likely need to investigate.

Evaluate what exactly causes the AVR to get reset. It is highly likely that long wires and current surges as loads are applied is causing either the GND or the VCC to the AVR to be compromised and initiating a brown out reset in the MCU.
Driving inductive loads without proper design may be putting high voltage spikes into your design that create havoc with proper software execution and/or risking serious damage to the silicon components. Make sure you take steps to eliminating such with clamp diodes, filter caps or zener diodes.
You will have to check your exact MCU data sheet but many parts have a reset reason register that your software can read to see what particular thing initiated the reset.
Lastly the most important thing is to make sure you have the proper tools for debugging problems like this. It is very common that you should have access to an oscilloscope so you can find the problems and learn how to fix them. The best way to learn how to design in a way that you avoid problems like this on the next project is to see first hand what went wrong and learn from it.


Over-the-air upgrades? I'd like to be able to upgrade software on an arduino without physically touching the device or stringing a cable. Can it be done?

Will pick wireless protocol that makes that easiest.

The best and easiest solution I've found is to use the Bluefruit EZ-Link from Adafruit.  They have a module you plug into the Serial/Power/reset pins (link here) or a shield for the uno (link here).  They've also got a great description and how-to guide (link here) that is pretty good.  It basically appears as a serial bluetooth link in the arduino IDE and you program it like normal.  It has the added benefit of being of use not only for programming, but also for sending and receiving data.


How to start serial monitor on Windows startup How can I get Windows to start the Serial Monitor window after a restart? Is there something I have to copy into the Windows startup folder for my account? Thanks

You can't.  You would need to have some way of telling the Arduino IDE to open the serial monitor and connect to a certain serial port. That can't be done.

Instead you would need to use some other third party serial communication program. How you would configure that depends on what the software is.

For Windows 10 you can make a program run at startup by following these instructions. You still need to configure the software to automatically connect to the right port at the right speed, of course.


Looking for help with WiFi modules I'm completely new to using modules for the Arduino, so I'm sure some people have more knowledge about this topic than me.
Here's the thing, I want to stream audio over my home wifi, so I'm in need of some rather high-speed modules, I'm aiming for 1-1.5 mbps for some proper compressed audio, including the overhead.

I've looked online for some well known wifi modules, but the only one I've managed to find that is popular is the esp8266, and that thing is definitely not for streaming anything.

Before anyone asks, yes, it is critical for it to work over wifi.
Has anyone done something like this? What gets the best results?

I cant comment so I'm going to post as an answer.  Arduino is most likely not capable of running any sort of audio unless you have an mp3 shield to support it.  As far as the wifi module, I suggest using Ethernet shield as that will run a lot better compared to wifi module.


ATMega328p (Arduino) Timer1 set-up I am trying to measure AC power using an Arduino with an Atmega328p.
In summary, I want to use timer1 to make an interrupt every 400us where I measure two ADC channels (A0 and A1) and put them into an array. The problem is that instead of measuring five mains periods (mains frequency = 50Hz so 20ms * 5), I get instead 13 of these periods (260ms). What am I doing wrong?

volatile int sample_incremental = 0;

void setup() {
      Serial.begin(115200);
      pinMode(voltagePin, INPUT);
      pinMode(currentPin, INPUT);
      set_sample_interrupt();
      sei();
    }

void set_sample_interrupt() {
  //Count to 400us
  OCR1A = 99;
  //Mode 4, CTC
  TCCR1B |= (1 << WGM12);
  //Enable interrupt
  TIMSK1 |= (1 << OCIE1A);
  //Prescaler 64
  TCCR1B |= (1 << CS11) | (1 << CS10);
}

ISR (TIMER1_COMPA_vect) {
  // action to be done every 400 usec
  current_sample[sample_incremental] = analogRead(currentPin) - 504;
  voltage_sample[sample_incremental] = analogRead(voltagePin) - 512;
  if (sample_incremental < (SAMPLES * PERIODREADS))
    sample_incremental++;
  else {
    //Disable interrupt
    TIMSK1 &= ~(1 << OCIE1A);
    sample_incremental = 0;
    finishedReading = true;
  }
}

Where after I do one reading, I stop the interrupt, and SAMPLES * PERIODREADS = 250.

The Arduino core library configures the Timer 1 for phase-correct PWM at
about 490 Hz. Then you are setting some configuration bits in the
timer's control registers without clearing the bits that had previously
been set by the Arduino core. If you want to use the timer for your own
purposes, and configure it by yourself, you should completely overwrite
the core's configuration with your own. For that, use the = operator
rather than |=, as in:

OCR1A  = 99;                         //Count to 400us
TIMSK1 = (1 << OCIE1A);              //Enable interrupt
TCCR1A = 0;
TCCR1B = (1 << WGM12)                //Mode 4, CTC
       | (1 << CS11) | (1 << CS10);  //Prescaler 64


MCU to MCU communication over UART What would be the best way to send the following information from one MCU to another?

Now I'm just sending the sentence over as is eg. Serial.print(sentence in here)

Example sentence: 1306,60.123456,50.123456,23.765382,40.897558,245,85,20.3,5,65,1500,0.9

Many thanks.

It depends actually on your requirements what is 'best'.

If (transmission) speed is an issue, there are mainly some things you can do to improve this:

Increase the transmission speed (this depends on the distance of the wires and the noise).
Decrease the start/stop bits (this reduces the certainty the values will arrive ok)
Pack your data (takes more processing time possibly, and more programming work, but can be faster).

About the third option: since you are mostly sending values, you can make some improvements. So you can send them as float (by sending the float data, with the length of sizeof(float)). However, note there could be inaccuracies in the last digit.


XBEE WiFi S6B RSSI for Smartphone localization I am building an early prototype, proof of concept, network monitoring tool.  A big part of it uses localization of a Smartphone.  It seems that the best way to do this is using RSSI from multiple points.  I plan to do this using several Arduino Fios with Xbee WiFi (S6B) cards.

My current setup has a network running from my smartphone (it is running DHCP) with a laptop monitoring all the traffic on the network.

What I need is for my Fio Xbees to dump the RSSI of the "access point" (Smartphone) onto the network so my laptop can pull the data.

Thus, to/from is not important as far as the packet is concerned, I just need the data dropped on the "wire" for my laptop to later parse, which is good because Serial.print* sends out a broadcast to 255.255.255.255:fffff.

I can make my devices broadcast any integer, but when I go into AT mode nothing aside from the initial DHCP handshake gets put on the wire.  Any ideas?

void setup() {
  Serial.begin(9600);
  Serial.flush();
  delay(1000);//enter AT mode start
  Serial.print("+");//AT
  Serial.print("+");//AT
  Serial.print("+");//AT
  Serial.flush();
  delay(1000);//enter AT mode finish
  while(Serial.available()>0){
    Serial.write(Serial.read());
  }

}

void loop(){
  Serial.println("ATDB");

  while(Serial.available()>0){
    Serial.write(Serial.read());
  }
  delay(750);//3/4 a sec
}

Note, Serial.println("ATDB"); should cause the xbee to drop the RSSI on the wire; see
XBee_WiFi_AT_Commands.pdf
at digi.com.

The three "+"s at the start are how you move the device into AT mode; see
Digi_International_90002124_G.pdf at mouser.com.

Once again what I am trying to do is get the collected RSSI information dropped onto a wifi connection from multiple xbee WiFi S6B equipped Fios.

Just incase anybody stumbles onto this page googling, I am posting my solution below (I think it will work for any xbee radio)

Basically for some reason the RSSI values are getting nulled out before I can read them, both in my API mode tests and AT commands.  I'm not convinced that there is not some way around this in API mode at least, but it is irrelevant for my current purpose.

What I did was wire pin 6 on the xbee to a digital pin on the Arduino (I used 7) then use a pulse detector to find the period of the wireless signal coming in.

int pin = 7;
unsigned long period;

void setup(){
  Serial.begin(9600);
  pinMode(pin, INPUT);
  Serial.println("Getting started");
}

void loop(){
  delay(100);
  period = pulseIn(pin, HIGH);
  Serial.println(period);

}

It is not perfect, but for now it works, might help someone else in the future.


pin numbering for non-standard chips so i replaced the mainboard in (what was) an anet a8 3d printer with a proper RAMPS setup. there was nothing wrong with it, (or at least it wasnt damaged, there are a number of severe design flaws) so i thought it might be a good start point for a remote controlled crawler/bot thing. it already has four a4988 drivers on board, plus a few mosfets and other bits which will be great for accessories (planning headlights, horn, maybe light sensor). its built around the atmega1284p, which is something of an oddball inbetween the 328 on the uno and the 2560 on the mega, but is the same product line. ive already worked out the libraries/drivers for the ch340 or whatever it is that is needed to flash code to the board,it already has already been added to the arduino ide, i have successfully flashed sketches to it before, but not my own. what im wondering is how to declare pins when im writing my own code. the bottom right of this schematic lists connections to the main chip, is it reasonably safe to assume that the digital pin numbers listed there can be used like the normally labeled headers on a standard board? how exactly are those numbers determined?

ok so what ive found is that pins are declared in a file, pins_arduino.h. for each board/chip/variant another file is added(or created, if writing your own) to the arduino hardware files. in my specific case the numbers in the graphic are consistent with those listed in the hardware file, so im good


Manchester Library Won't Compile for Attiny85 I am creating a wireless sensor using an Attiny85.  I want to send the data to an arduino uno, so I purchased the 315mhz rf link kit from spark fun.  Since the Attiny85 does not have a TX I decided to use the Manchester library however it won't compile on the Attiny85.

I followed the steps from this blog :
http://mchr3k-arduino.blogspot.mx/2012/01/wireless-sensor-node-part-2.html?showComment=1338749638806#c853067277980266192

Here is the code I am using:

    #include <WProgram.h> //otherwise it says it can't find Arduino.h
    #include <Manchester.h> //include the library to comunicate
    #define TxPin 2 //the pin that is used to send data

 int sensorPin = 4;
 int ledPin = 3;
 int count = 50;

 void setup(){
  pinMode (ledPin, OUTPUT);
  man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
  man.setupTransmit(TxPin, MAN_1200); //set transimt pin
}

void loop(){
  if (count == 50){
   digitalWrite (ledPin, HIGH);
   count = 0;
   }
   int data = analogRead(sensorPin);
   man.transmit(data); //transmits and reads the data
   delay (100);
   count ++;
 }

Here is the error message:

/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp: In function 'void MANRX_SetupReceive(uint8_t)':
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'TCCR2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'WGM21' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'TCCR2B' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'CS21' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:369: error: 'OCR2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'TIMSK2' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'OCIE2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:380: error: 'TCNT2' was not declared in this scope

attiny is missing an option required to allow the Manchester library to function properly on ATtinyX5 devices, specifically definition of __AVR_ATtinyX5__ when a device is selected. In fact, it's missing quite a few things.

The package I use for ATtinyX5 support is arduino-tiny. I have verified that it defines that symbol properly. I recommend that you dump your current support package and install arduino-tiny instead.


SainSmart CO2 sensor module use? I purchased this CO2 sensor a while back: SainSmart MG811 Gas CO2 Carbon Dioxide Sensor Module Sensor Module for Arduino UNO R3 Raspberry Pi

The module has four pins, Vin, GND, Dout and Aout. I assume Dout and Aout are digital output and analog output, respectively.

Other than that, the sensor came with no datasheet, instructions, or tutorial. I also searched online but fail to find anything useful.

I'm going simple for now, just hooking up the sensor module to Arduino board. I know I can probably connect the output pins to the analog pins, and analogRead them, but what I am looking for is how to convert the raw data readings into CO2 levels in PPM. Like a formula.

Also, I'm curious as to how the digital output works...

The Dout is a TTL threshold indicator; basically it goes high when a certain threshold of the sensor is reached, which is adjusted by the pot.  The Aout is the VRef of the sensor.

Now the MG-811 is not the best sensor in the world; I did look at the datasheet which shows this sensor outputs mV in relation to the PPM so a map function could be used such as 100-600mV maps to 400-10000ppm CO2, see MG-811 CO2 Sensor Module, so you could feed this into a map() function and get the result but since there is a signal conditioning circuit consisting of a op-amp I'm not sure what it does to the raw sensor voltage.

Now the sandbox electronics module may not be identical to the SainSmart module, so you may need to reverse engineer the module you have to determine what is going on or use the schematic from the sandbox site to build your own and de-solder the MG-811 from the SainSmart module.


Common wireless gadget with rotary encoder to connect with Arduino I'm looking for a common "wireless gadget" with a rotary encoder that can be accessed by an Arduino. Background: I need a portable rotary encoder to create a simple way to control model railway locomotives. The only one I have found so far is a wireless mouse where the scroll wheel can be easily used as rotary encoder.

But they usually are using USB on the PC side which is not that easy to handle by Arduino. Does anybody knows about other common "wireless gadgets"?

That sounds like a candidate for building your own.  It shouldn't be too hard.

There's plenty of low-cost Arduino-compatible wireless modules available.  My choice for this would probably be the nRF24L01 - dirt cheap, reasonable range, well supported.

Attach that to an Arduino Mini or Arduino Nano (for instance) and connect a rotary encoder of your choice.  Write the sketch.

Add another nRF24L01 to your main Arduino to receive whatever you send.

Due to the way the nRF24L01 works you could quite easily have a number of remote modules talking to the Arduino through the same channel.  I'm sure you could think of other things you could do with that wireless channel :)


Can the Leonardo Arduino be used as a USB HOST for CDC Com devices? I am trying to connect a CDC communication device to the Leonardo USB port and have communication with it via the TTL com port. Basically I want to echo to the TTL port whatever is transmitted over USB and vice-versa.

ASCII data is transmitted out the USB from the CDC device into the USB port of the Leonardo Aurduino. The Arduino needs to xtransfer this info over to the UART pins D0 (RX) and D1 (TX) that are connected to the UART of another micro-controller. I should be able to test it by connecting an FTDI TTL-RS232 cable and see results and have comms in my terminal program.

I came across this sketch that appears to be basically what I want, but I think the "hosting" portion is not being set up:

void setup() {
  Serial.begin(9600);  // rx/tx pins
  Serial1.begin(9600); // USB port
  Serial1.write("2nd Version");
}

void loop() {
  // copy from virtual serial line to UART and vice-versa
  if (Serial.available()) {
    char c = (char)Serial.read();
    Serial1.write(c);
  }
  if (Serial1.available()) {
    char c = (char)Serial1.read();
    Serial.write(c);
  }
}

What am I missing? Note I am NOT trying to do HID but CDC. Basically I want to eliminate using a PC as a Host device and use the "bridge" between my CDC device and another micro-controller.

No, the Leonardo cannot be a USB Host. You may be able to use a USB Host Shield in conjunction with the Leonardo, though I have never tried it and cannot vouch for compatibility with the Leonardo.

USB is a host->device protocol, not a peer-to-peer protocol. You cannot just connect two devices together. Only a USB Host can communicate with a USB device.


How to use variables and functions across multiple .ino files I have 2 .ino files (2 tabs) for one Arduino project/sketch: MySketch_File1.ino and MySketch_File2.ino.

I declared in MySketch_File2 variables and functions which I want to use in MySketch_File1, but I get this error massage:

  error: 'a' was not declared in this scope

//MySketch_File1.ino
void setup(){
Serial.begin(9600);
Serial.println(String(a));
}

void loop(){

}

Second file:

//MySketch_File2.ino
int a;

How can I declare variables and functions one time in one .ino file and use it across multiple .ino files?

When you compile multiple files in the Arduno IDE the files first get concatenated together.

It happens in alphabetical order, except the main INO file (the one named the same as the folder it's in) is placed first.

In C the order in which things appear in the file matters. Basically you have to make sure that things (like variables, functions, etc) are defined before they are used.

This gets more complex when you have a hidden thing like file concatenation messing things up.

The Arduino IDE tries to hide some of it from you too by making function prototypes, so it doesn't matter what order you define functions in - however that "helpfulness" means you don't learn about the proper structure of a C program.

So what can you do? Well, simply make sure that all your global variables are defined in the main file, unless you know they are only going to be used within the file they are defined in.