IR communication not consistent I have an IR Receiver hooked up to my arduino and a remote with an IR Trasmitter in it. I have some code to decode the values that are received but the values change even when I am pressing the same button!

Here is the code I am using:

#include <IRremote.h>

int IRpin = 8;
IRrecv irrecv(IRpin);
decode_results results;

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

void loop()
{
  if (irrecv.decode(&results))
    {
      Serial.println(results.value, HEX);
      irrecv.resume();
    }
}

and here is me pressing the same button 10 times and the output for it:

  9C01C8E1
  FFFFFFFF
  82A6A14C
  FFFFFFFF
  FFFFFFFF
  70D67871
  FFFFFFFF
  BCB5C227
  FFFFFFFF
  B358F5ED
  FFFFFFFF
  FFFFFFFF
  FFFFFFFF
  FFFFFFFF
  FFFFFFFF
  FFFFFFFF
  58EE9A27
  FFFFFFFF
  90750A0D
  FFFFFFFF
  FFFFFFFF
  FFFFFFFF

Get TSOP1738 or any good IR receiver to decode. Above code is appropriate and does not need any changes. you will surely get some fluctuations and different decoded hex codes but it would provide only 2 different values for single button so that while controlling any device using ir , you can use 'or' operator in conditional statement and hence you will get desired results.
Getting absolute results from a cheap IR receiver is a myth.But it will work well for your project at lower level.I had worked with that and my device is working in my room with no difficulty.


DC-DC converter with Arduino not working I've got a program running on the Arduino that is supposed to turn on and off a pump.  currently, I am outputting the reads of the components that need to be read and it shows when the port (port 13) is supposed to turn on and when it's supposed to turn off.  When I use a multimeter between the port 13 and ground, everything works as expected.

When I start the program and the port is off, I get a reading of 0.03v @20v max (to be more precise, I get 14.0 at 200mV) - Shouldn't this be zero? or is there always going to be some electricity flowing?

When the port is turned on: digitalWrite(airPump, HIGH); (and yes, airPump is set to 13), the voltage reads between 4.0 and 4.51 with spikes down to 3.65 on my multimeter set at 20v max.  is it ever stable? (pictured below)

So, the main question is: I'm supposed to be sending the power from port 13 to a DC-DC converter.  I tested the converter on a separate bread board just by itself.  I used a DC power supply and set it to 4.5v, then ran the power through the vIn, grounded the ground pin and ran the vOut to the multimeter (then to ground with the multimeter) and I got it set to output only 2.5v with a constant 4.5 running into it. (pictured below)

I also tested whether or not changing the voltage input would change the output at all and it seems it does not, from 1.5-15v, the converter stays steady at 2.5v

Now when I do the exact same set up on the arduino with the power from port 13 running into the voltage in on the DC-DC converter, it gives me a reading of 0.01v.  Any idea why this is happening?

I've checked probably over 30 times and rearranged everything just as many, but nothing seems to help.  I can't get a stable 2.5V output from the converter with the arduino...

UPDATE: Below is a simple wiring diagram:

The image shows what it is supposed to do, but for testing purposes I made it so if the rH is higher than average (I just breath on it) then the pump will turn on.

The arduino output pin cannot provide enough current to drive the pump. The DC-DC converter is not designed for this use.

You need external power supply with enough current to drive the motor that you switch on and off with the arduino output pin.

Search for "Arduino 3V DC motor control" for examples of how to do this, there are many options.


How can I set up a watchdog interrupt vector timer on the Arduino Redboard/Uno? I'm trying to set up a watchdog timer interrupt to execute a routine in the WDT_vec ISR at some recurring interval. I don't want the processor to reset, just to execute the code in the interrupt and return to "normal" operation. I have the following test jig appropriated from the 'net that claims to set that up:

#include <avr/wdt.h>

 void setup_WDT() {
      noInterrupts();  // disable all the interrupts
      MCUSR = 0;       // ensure that the reset vectors are off

      /* Disable and clear all Watchdog settings. */

      _WD_CONTROL_REG = (1 << WDCE) | (1 << WDE);
      _WD_CONTROL_REG = 0;

      /* Setup Watchdog for interrupt and not reset, and a approximately 500ms timeout */
      _WD_CONTROL_REG = (1 << WDIE) | (1 << WDP2) | (1 << WDP0);

      interrupts();  // re-enable interrupts
    }

void setup() {
  setup_WDT();
  Serial.begin(9600);
  Serial.println("Startup");
}

void loop() {
}

ISR(WDT_vec) {
  Serial.println("Watchdog Interrupt");
}

The output indicates that the processor is just resetting repeatedly and never reaching the ISR. Also I get the following warning on compilation from the IDE (Arduino 1.8.2):

  warning: 'WDT_vec' appears to be a misspelled signal handler, missing
  __vector prefix [-Wmisspelled-isr]  ISR(WDT_vec) {

Two errors:

The watchdog interrupt vector is named WDT_vect, not WDT_vec.
The statement _WD_CONTROL_REG = 0; serves no useful purpose, and
will likely mess up with the timed sequence for changing the watchdog
setting. Just remove it.


Adafruit gps breakout module help I am intending to show the initial, searching for signal..., screen until the location is updated and then show the location on the lcd. However, even after the led on the gps indicates a satellite fix, the screen never leaves the searching for signal screen. Any help would be greatly appreciated-- very new to microcontroller programming. Sorry for the poorly formatted code block as well, I am in a rush.
Thanks in advance.

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
#include <TinyGPS++.h>

#define RXPin 2
#define TXPin 3
#define GPSBaud 4800

SoftwareSerial ss(RXPin, TXPin);
TinyGPSPlus gps;
LiquidCrystal lcd(12, 11, 10, 7, 6, 5, 4);

double latt;
double lon;
int screen;

void setup(void);
void loop(void);
void readGPS(void);
void update(void);
void render(void);

void setup() {
     //variable initialization
     latt = 0.0;
     lon = 0.0;
     screen = 0;

     //lcd initial setup
     pinMode(9, OUTPUT);
     analogWrite(9, 100);
     pinMode(13, OUTPUT);
     digitalWrite(13, HIGH);

     //display intial screen
     lcd.begin(16,2);
     lcd.clear();
     lcd.setCursor(0,0);
     lcd.print("Searching for");
     lcd.setCursor(6,2);
     lcd.print("Signal ...");
     ss.begin(GPSBaud);
}

void loop() {
    readGPS();
    update();
}

/** Receives data from the gps if available */
void readGPS() {
    while (ss.available() > 0) {
        gps.encode(ss.read());
    }
}

/** Processes the data read by readGPS() */
void update() {
    if (gps.location.isUpdated()) {
        latt = gps.location.lat();
        lon = gps.location.lng();
        render();
    }
}

/** Displays the current screen on the lcd */
void render() {
    if (screen == 0) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Lat:");
        lcd.print(latt);
        lcd.print(" Lng:");
        lcd.print(lon);
        lcd.setCursor(0,1);
        lcd.print("Sats:");
        lcd.print(gps.satellites.value());
    }
}

Adafruit GPS breakout has their own library setup.
Below is the code I use for my telemetry. Notice I'm using HardwareSerial though.
You can just change that into SoftwareSerial.

#include <SoftwareSerial.h>
#include <Adafruit_GPS.h>
#define GPSECHO false // Disables GPS breakout debug

boolean usingInterrupt = false;

HardwareSerial gpsSerial = Serial1;
Adafruit_GPS GPS(&Serial1);

SoftwareSerial XBee(2, 3); // For wireless

unsigned int REFRESH = 20;

double lat_deg, lon_deg, lat_min, lon_min;
char lat, lon;

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

  GPS.begin(115200);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_5HZ); // Either 1HZ or 5HZ
  GPS.sendCommand(PMTK_API_SET_FIX_CTL_5HZ);
  GPS.sendCommand(PGCMD_ANTENNA);

  useInterrupt(true);
}

SIGNAL(TIMER0_COMPA_vect)
{
  char c = GPS.read();
#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;
#endif
}

void useInterrupt(boolean v)
{
  if(v)
  {
    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  }
  else
  {
    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

void loop()
{
  if(GPS.newNMEAreceived())
  {
    if(!GPS.parse(GPS.lastNMEA()))
    {
      writeData(1, true);
      Serial.print(GPS.hour, DEC); Serial.print(F(","));
      Serial.print(GPS.minute, DEC); Serial.print(F(","));
      Serial.print(GPS.seconds, DEC); Serial.print(F(","));
      Serial.print((int)GPS.fix); Serial.print(F(","));
      Serial.print((int)GPS.fixquality); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999"));
    }
    else if(GPS.fix)
    {
      writeData(1, true);
      parseGPS(GPS.latitude, GPS.longitude);
      Serial.print(GPS.hour, DEC); Serial.print(F(","));
      Serial.print(GPS.minute, DEC); Serial.print(F(","));
      Serial.print(GPS.seconds, DEC); Serial.print(F(","));
      Serial.print((int)GPS.fix); Serial.print(F(","));
      Serial.print((int)GPS.fixquality); Serial.print(F(","));
      Serial.print(lat_dd, 8); Serial.print(F(","));
      Serial.print(lon_dd, 8); Serial.print(F(","));
      Serial.print(GPS.speed); Serial.print(F(","));
      Serial.print(GPS.angle); Serial.print(F(","));
      Serial.print(GPS.altitude); Serial.print(F(","));
      Serial.print(GPS.satellites);
    }
  }
  delay(REFRESH);
}

void parseGPS(float _latitude, float _longitude)
{
  lat_deg = (int) (_latitude / 100);
  lon_deg = (int) (_longitude / 100);

  lat_min = _latitude - (lat_deg * 100);
  lon_min = _longitude - (lon_deg * 100);

  lat_dd = (double) lat_deg + ((double) lat_min / 60);
  lon_dd = (double) lon_deg + ((double) lon_min / 60);

  lat = GPS.lat; lon = GPS.lon;

  if (lat == 'S') lat_dd = -lat_dd;
  if (lon == 'W') lon_dd = -lon_dd;
}

void writeData(float data, boolean next)
{
  Serial.print(data);
  if (next) Serial.print(F(","));
}


Routing Arduino Mega output to either one of two serial ports I have an Arduino Mega controller that normally communicates via Bluetooth (HC08 Bluetooth module) to an Android device. In case there is a problem on the Android side I wish to have a fallback ability to communicate via the USB serial port. The choice of serial port is determined by a hardware switch that the Arduino can read. Currently I have:
HardwareSerial & Terminal = Serial;
HardwareSerial & BTPort = Serial1;

Is there a way to route an output to either BTPort or to terminal, dependent on the state of the switch? Ideally I would like to do something like this:
HardwareSerial & OutputPort
if(switch_is_on)
  OutputPort = Terminal;
else
  OutputPort = BTPort;

Obviously the above code does not work. I have no idea of how to proceed.

I can think of three distinct ways (and one that is similar to another) of doing what you want.
But first a note on polymorphism.  The HardwareSerial class is itself a child of the Stream class. It's this Stream class that provides all the read/write functionality (it, itself, is a child of the Print class which provides all the print(...) functions).
If all you want to do is print then you should be working with the Print class. if you want to do both reading and writing then the Stream class is what you want. You should only use HardwareSerial if you need to use the Serial-specific functions like .begin(baud).
So with that in mind you could:
1. Assign a pointer
Print *printer;

void setup() {
    Serial.begin(115200);
    Serial1.begin(115200);
    printer = &Serial;
}

void loop() {
    printer = &Serial;
    printer->println(millis());
    delay(100);
    printer = &Serial1;
    printer->println(millis());
    delay(100);
}

This is by far the most efficient method from a purely machine perspective.
Note the use of -> instead of . when calling a function on a pointer.
2a. Use a wrapper function
uint8_t stream = 0;

void printit(const char *text) {
    switch (stream) {
        case 0:
            Serial.print(text);
            break;
        case 1:
            Serial1.print(text);
            break;
    }
}

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

void loop() {
    stream = 0;
    printit("Hello on stream 0\r\n");
    stream = 1;
    printit("Hello on stream 1\r\n");
}

This is less efficient and limits what you can print unless you write lots of overloaded functions.
2b. Use a macro
This is like 2a but uses a macro instead of a function:
#define printit(T) if (stream == 0) Serial.print(T) else Serial1.print(T)

This keeps the standard overloading of the print function but has lots of IF statements littered through your code. A fraction more efficient than 2a since it's all inline. Harder for a human to understand though.
3. Create a wrapper class
This is the rolls-royce method. Everything becomes encapsulated in your own object. Pointers are used to keep it efficient.
class Printer : public Print {
    private:
        Print *stream;
        Print *stream0;
        Print *stream1;
    public:
        Printer(Print &s0, Print &s1) : stream0(&s0), stream1(&s1) {
            stream = &s0;
        }
        size_t write(uint8_t c) {
            return stream->write(c);
        }
        void setStream(uint8_t sno) {
            switch (sno) {
                case 0: stream = stream0; break;
                case 1: stream = stream1; break;
            }
        }
};

Printer printer(Serial, Serial1);

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

void loop() {
    printer.setStream(0);
    printer.println(millis());
    delay(100);
    printer.setStream(1);
    printer.prinln(millis());
    delay(100);
}

With this method the new class could be put into a library and used across your projects.
You also get all the functions you'd normally get with the Serial object when printing (for reading change Print to Stream and implement all the pure virtual functions you need for that class).
And a footnote for all those that say "Why use pointers? Why not references?" I say: I hate references. Pointers are far more obvious what they are. References you can't tell apart from distinct variables. With a pointer you know it's a pointer. References are the spawn of the devil.


Importance of resistor I'm new to Arduino and also new to electronics. I'm following the tutorial here. I'm not understanding the importance of the resistor in this schematic diagram. Can someone please help me on this?

That resistor, where positioned, is called a pull-down resistor, and if replaced by a straight wire, that circuit would short out when the switch was closed.

The purpose of this is that when a digital input pin is not connected, it floats, and if the switch were open that pin could see upwards of 2v floating value from external and internal noise. With Digital circuitry, any value in this float range can be invalid and return invalid results.

A pull down resistor will generally have a very high ohmic value >5kohm, as to allow as little current pass as possible. Here, you are shorting the pin to ground through the resistor so it will not have a LOW value when the switch is open, instead of possibly invalid.

When the switch is closed, you will have 5v passing through switch into the pin, to be read as a HIGH value, also sending 5v across a 10k or so resistor to ground, consuming only .5mA of current.

It you want to see what I mean by a floating value, debug the output of any analog pin with a wire going nowhere, and watch as the value changes. Try touching the wire, now add a pull down to ground, or try pulling it up to 5v and observe the behavior.

Happy Arduinoing!


Do all pins of Arduino Uno output 5V? I am currently working on a project which uses PIR motion sensor and 5V relay.
Since you might be familiar that both the motion sensor and the relay requires a 5V connection.

My problem is, I don't want messy connections (parallel and series) and want to use any other pin for power and ground.

Also, can you suggest which resistor I might require for the motion sensor and relay?

Thanks for any help.

You might get away with powering a PIR sensor from a logic line. Check the specs. If it draws less ≤20mA you'd be fine. If you nee to drive more current than that you can use a CMOS TTL Driver or a properly selected N-channel MOSFET. Adafruit sells these, for example.

A relay is another matter. If you this is one of those optically isolated relays and all you're driving is the optioisolator then you might get away with that too if you only need ≤20mA. If you're looking to actually power the relay coils with your Arduino, forget it. it's a bad idea to even have the relay driven from the 5V line on the Arduino. Relays take quite a bit of current, and their load is quite "dirty" and likely to cause problems.

As to "which resistor I might require for the motion sensor & relay", I'm not sure what you mean. You shouldn't need any resistors. If the relay draws more current than the Arduino can supply, a current limiting resistor might protect the Arduino from damage but the relay won't work correctly.

What resistors are you referring to?


Set and extract individual bytes of a number (lowByte() and highByte()) You can extract

  the low-order (rightmost) byte of a variable

or

  the high-order (leftmost) byte of a word

with the functions lowByte() and highByte() respectively (the quotes are from the Arduino Reference).

Does Arduino provide a way to extract any byte from a number with a similar function?

And does it provide a way to set any individual bytes of a number (which would be the counterparts to these functions, if they exist)?

Any more sophisticated byte exchange can be done with binary operators.

Extracting information

You'll need some constants like

MASK         SHIFT
0xFF000000   24       (first byte, most significant)
0x00FF0000   16       (second byte)
0x0000FF00    8       (third byte)
0x000000FF    0       (last byte, least significant)

You would binary AND the original value with MASK

     0x12345678
AND  0x00FF0000
 =   0x00340000

and then bit shift it left, e.g.

   0x00340000
>> 16
 = 0x00000034

So from the original value 0x12345678 you have gotten 0x34.

Setting information

The opposite direction is also possible with the same constants but opposite operators and in opposite order:

   0x00000034
<< 16
 = 0x00340000

and then

   0x12005678
OR 0x00340000
 = 0x12345678

Note that the OR operation only works reliably if the corresponding positions are 0x00. That's fine with a starting value of 0x00000000.

If you don't know that or you want to process an arbitrary number, you can introduce a step in between

    0x12??5678   (?? could be anything)
AND 0xFF00FFFF   (which is the inverse of 0x00FF0000 and can be expressed as ~0x00FF0000)
 =  0x12005678   (whatever ?? was, it'll be cleared out)

Actual Code

Tested on Arduino Uno. The long data type is 32 bits or 4 bytes.

The code here may not be the most efficient. Advanced developers would likely not use MASK and SHIFT as arrays like this. This answer focuses more on the educational point.

long MASK[]  = {0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF};
byte SHIFT[] = {24        , 16        , 8         , 0};

// Extracts a byte from a larger data type
// value: larger data type to extract a byte from
// position: 0 based number, 0 = MSB, 3 = LSB
byte getByteAt(long value, byte position)
{
  long result = value & MASK[position];  // binary AND
  result = result >> SHIFT[position];    // Shift right, moving all bits
  byte resultAsByte = (byte) result;     // Convert to an actual byte
  return resultAsByte;
}

// Sets a byte in a larger data type
// value: larger data type where to set the byte
// position: 0 based number, 0 = MSB, 3 = LSB
// newPartialValue: the byte to be inserted
long setByteAt(long value, byte position, byte newPartialValue)
{
  long result = value & ~MASK[position];                       // clear the affected byte so that it is 0x00
  long valueToSet = (long) newPartialValue << SHIFT[position]; // Shift left, moving all bits
  result = result | valueToSet;                                // binary OR
  return result;
}

void setup() {
  Serial.begin(9600);
  Serial.println(getByteAt(0x12345678, 1));       // Prints 52, which is 0x34
  Serial.println(setByteAt(0x87654321, 1, 0xBB)); // Prints -2017770719 which is 0x87BB4321
}

void loop() {

}


Sending colours to vga monitor I'm looking for a simple way to send a signal from my arduino to a vga monitor.

What would be the easiest method, and what components would be needed?

I don't need to display an image, just a solid colour.

My page about Arduino Uno output to VGA monitor has a lot of theory on it, including a sketch that produces colour bars like this:

Code

To produce a single colour is slightly simpler, this sketch did it for me:

/*
 VGA colour video generation

 Author:   Nick Gammon
 Date:     22nd April 2012
 Version:  1.0

 Connections:

 D3 : Horizontal Sync (68 ohms in series) --> Pin 13 on DB15 socket
 D4 : Red pixel output (470 ohms in series) --> Pin 1 on DB15 socket
 D5 : Green pixel output (470 ohms in series) --> Pin 2 on DB15 socket
 D6 : Blue pixel output (470 ohms in series) --> Pin 3 on DB15 socket
 D10 : Vertical Sync (68 ohms in series) --> Pin 14 on DB15 socket

 Gnd : --> Pins 5, 6, 7, 8, 10 on DB15 socket

*/

#include <TimerHelpers.h>
#include <avr/pgmspace.h>
#include <avr/sleep.h>

const byte hSyncPin = 3;     // <------- HSYNC

const byte redPin = 4;       // <------- Red pixel data
const byte greenPin = 5;     // <------- Green pixel data
const byte bluePin = 6;      // <------- Blue pixel data

const byte vSyncPin = 10;    // <------- VSYNC

const int horizontalBytes = 60;  // 480 pixels wide
const int verticalPixels = 480;  // 480 pixels high

// Timer 1 - Vertical sync

// output    OC1B   pin 16  (D10) <------- VSYNC

//   Period: 16.64 ms (60 Hz)
//      1/60 * 1e6 = 16666.66 µs
//   Pulse for 64 µs  (2 x HSync width of 32 µs)
//    Sync pulse: 2 lines
//    Back porch: 33 lines
//    Active video: 480 lines
//    Front porch: 10 lines
//       Total: 525 lines

// Timer 2 - Horizontal sync

// output    OC2B   pin 5  (D3)   <------- HSYNC

//   Period: 32 µs (31.25 kHz)
//      (1/60) / 525 * 1e6 = 31.74 µs
//   Pulse for 4 µs (96 times 39.68 ns)
//    Sync pulse: 96 pixels
//    Back porch: 48 pixels
//    Active video: 640 pixels
//    Front porch: 16 pixels
//       Total: 800 pixels

// Pixel time =  ((1/60) / 525 * 1e9) / 800 = 39.68  ns
//  frequency =  1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

// However in practice, it we can only pump out pixels at 375 ns each because it
//  takes 6 clock cycles to read one in from RAM and send it out the port.

const byte verticalBackPorchLines = 35;  // includes sync pulse?
const int verticalFrontPorchLines = 525 - verticalBackPorchLines;

volatile int vLine;
volatile byte backPorchLinesToGo;

#define nop asm volatile ("nop\n\t")

// ISR: Vsync pulse
ISR (TIMER1_OVF_vect)
  {
  vLine = 0;
  backPorchLinesToGo = verticalBackPorchLines;
  } // end of TIMER1_OVF_vect

// ISR: Hsync pulse ... this interrupt merely wakes us up
EMPTY_INTERRUPT  (TIMER2_OVF_vect)

void setup()
  {

  // disable Timer 0
  TIMSK0 = 0;  // no interrupts on Timer 0
  OCR0A = 0;   // and turn it off
  OCR0B = 0;

  // Timer 1 - vertical sync pulses
  pinMode (vSyncPin, OUTPUT);
  Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
  OCR1A = 259;  // 16666 / 64 µs = 260 (less one)
  OCR1B = 0;    // 64 / 64 µs = 1 (less one)
  TIFR1 = bit (TOV1);   // clear overflow flag
  TIMSK1 = bit (TOIE1);  // interrupt on overflow on timer 1

  // Timer 2 - horizontal sync pulses
  pinMode (hSyncPin, OUTPUT);
  Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
  OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
  OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)
  TIFR2 = bit (TOV2);   // clear overflow flag
  TIMSK2 = bit (TOIE2);  // interrupt on overflow on timer 2

  // prepare to sleep between horizontal sync pulses
  set_sleep_mode (SLEEP_MODE_IDLE);

  // pins for outputting the colour information
  pinMode (redPin, OUTPUT);
  pinMode (greenPin, OUTPUT);
  pinMode (bluePin, OUTPUT);

}  // end of setup

// draw a single scan line
void doOneScanLine ()
  {

  // after vsync we do the back porch
  if (backPorchLinesToGo)
    {
    backPorchLinesToGo--;
    return;
    }  // end still doing back porch

  // if all lines done, do the front porch
  if (vLine >= verticalPixels)
    return;

  PORTD = bit (5) | bit (6);  // cyan (green + blue)
  delayMicroseconds (27);     // one scan line

  PORTD = 0;  // back to black
  // finished this line
  vLine++;

  }  // end of doOneScanLine

void loop()
  {
  // sleep to ensure we start up in a predictable way
  sleep_mode ();
  doOneScanLine ();
 }  // end of loop

As @ChrisStratton suggested, the hardware timers are a big help.

Wiring

I wired it up like this:

TimerHelpers library

The TimerHelpers.h library is described on my timers page, a copy is below:

/*
 Timer Helpers library.

Devised and written by Nick Gammon.
Date: 21 March 2012
Version: 1.0

Licence: Released for public use.

See: http://www.gammon.com.au/forum/?id=11504

 Example:

 // set up Timer 1
 TCNT1 = 0;         // reset counter
 OCR1A =  999;       // compare A register value (1000 * clock speed)

 // Mode 4: CTC, top = OCR1A
 Timer1::setMode (4, Timer1::PRESCALE_1, Timer1::CLEAR_A_ON_COMPARE);

 TIFR1 |= bit (OCF1A);    // clear interrupt flag
 TIMSK1 = bit (OCIE1A);   // interrupt on Compare A Match

*/

#ifndef _TimerHelpers_h
#define _TimerHelpers_h

#include <Arduino.h>

/* ---------------------------------------------------------------
 Timer 0 setup
 --------------------------------------------------------------- */

namespace Timer0
{
  // TCCR0A, TCCR0B
  const byte Modes [8] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFF
  { bit (WGM00),               0 },            // 1: PWM, Phase-correct, top = 0xFF
  {               bit (WGM01), 0 },            // 2: CTC, top = OCR0A
  { bit (WGM00) | bit (WGM01), 0 },            // 3: Fast PWM, top = 0xFF
  { 0,                         bit (WGM02) },  // 4: Reserved
  { bit (WGM00),               bit (WGM02) },  // 5: PWM, Phase-correct, top = OCR0A
  {               bit (WGM01), bit (WGM02) },  // 6: Reserved
  { bit (WGM00) | bit (WGM01), bit (WGM02) },  // 7: Fast PWM, top = OCR0A

  };  // end of Timer0::Modes

  // Activation
  // Note: T0 is pin 6, Arduino port: D4
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T0_FALLING, T0_RISING };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 12, Arduino port: D6
    TOGGLE_A_ON_COMPARE  = bit (COM0A0),
    CLEAR_A_ON_COMPARE   = bit (COM0A1),
    SET_A_ON_COMPARE     = bit (COM0A0) | bit (COM0A1),

    // pin 11, Arduino port: D5
    TOGGLE_B_ON_COMPARE  = bit (COM0B0),
    CLEAR_B_ON_COMPARE   = bit (COM0B1),
    SET_B_ON_COMPARE     = bit (COM0B0) | bit (COM0B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 7)  // sanity check
    return;

  // reset existing flags
  TCCR0A = 0;
  TCCR0B = 0;

  TCCR0A |= (Modes [mode] [0]) | port;
  TCCR0B |= (Modes [mode] [1]) | clock;
  }  // end of Timer0::setMode

}  // end of namespace Timer0

/* ---------------------------------------------------------------
 Timer 1 setup
 --------------------------------------------------------------- */

namespace Timer1
{
  // TCCR1A, TCCR1B
  const byte Modes [16] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFFFF
  { bit (WGM10),               0 },            // 1: PWM, Phase-correct, 8 bit, top = 0xFF
  {               bit (WGM11), 0 },            // 2: PWM, Phase-correct, 9 bit, top = 0x1FF
  { bit (WGM10) | bit (WGM11), 0 },            // 3: PWM, Phase-correct, 10 bit, top = 0x3FF
  { 0,                         bit (WGM12) },  // 4: CTC, top = OCR1A
  { bit (WGM10),               bit (WGM12) },  // 5: Fast PWM, 8 bit, top = 0xFF
  {               bit (WGM11), bit (WGM12) },  // 6: Fast PWM, 9 bit, top = 0x1FF
  { bit (WGM10) | bit (WGM11), bit (WGM12) },  // 7: Fast PWM, 10 bit, top = 0x3FF
  { 0,                                       bit (WGM13) },  // 8: PWM, phase and frequency correct, top = ICR1
  { bit (WGM10),                             bit (WGM13) },  // 9: PWM, phase and frequency correct, top = OCR1A
  {               bit (WGM11),               bit (WGM13) },  // 10: PWM, phase correct, top = ICR1A
  { bit (WGM10) | bit (WGM11),               bit (WGM13) },  // 11: PWM, phase correct, top = OCR1A
  { 0,                         bit (WGM12) | bit (WGM13) },  // 12: CTC, top = ICR1
  { bit (WGM10),               bit (WGM12) | bit (WGM13) },  // 13: reserved
  {               bit (WGM11), bit (WGM12) | bit (WGM13) },  // 14: Fast PWM, TOP = ICR1
  { bit (WGM10) | bit (WGM11), bit (WGM12) | bit (WGM13) },  // 15: Fast PWM, TOP = OCR1A

  };  // end of Timer1::Modes

  // Activation
  // Note: T1 is pin 11, Arduino port: D5
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T1_FALLING, T1_RISING };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 15, Arduino port: D9
    TOGGLE_A_ON_COMPARE  = bit (COM1A0),
    CLEAR_A_ON_COMPARE   = bit (COM1A1),
    SET_A_ON_COMPARE     = bit (COM1A0) | bit (COM1A1),

    // pin 16, Arduino port: D10
    TOGGLE_B_ON_COMPARE  = bit (COM1B0),
    CLEAR_B_ON_COMPARE   = bit (COM1B1),
    SET_B_ON_COMPARE     = bit (COM1B0) | bit (COM1B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 15)  // sanity check
    return;

  // reset existing flags
  TCCR1A = 0;
  TCCR1B = 0;

  TCCR1A |= (Modes [mode] [0]) | port;
  TCCR1B |= (Modes [mode] [1]) | clock;
  }  // end of Timer1::setMode

}  // end of namespace Timer1

/* ---------------------------------------------------------------
 Timer 2 setup
 --------------------------------------------------------------- */

namespace Timer2
{
  // TCCR2A, TCCR2B
  const byte Modes [8] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFF
  { bit (WGM20),               0 },            // 1: PWM, Phase-correct, top = 0xFF
  {               bit (WGM21), 0 },            // 2: CTC, top = OCR2A
  { bit (WGM20) | bit (WGM21), 0 },            // 3: Fast PWM, top = 0xFF
  { 0,                         bit (WGM22) },  // 4: Reserved
  { bit (WGM20),               bit (WGM22) },  // 5: PWM, Phase-correct, top = OCR2A
  {               bit (WGM21), bit (WGM22) },  // 6: Reserved
  { bit (WGM20) | bit (WGM21), bit (WGM22) },  // 7: Fast PWM, top = OCR2A

  };  // end of Timer2::Modes

  // Activation
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_32, PRESCALE_64, PRESCALE_128, PRESCALE_256, PRESCALE_1024 };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 17, Arduino port: D11
    TOGGLE_A_ON_COMPARE  = bit (COM2A0),
    CLEAR_A_ON_COMPARE   = bit (COM2A1),
    SET_A_ON_COMPARE     = bit (COM2A0) | bit (COM2A1),

    // pin 5, Arduino port: D3
    TOGGLE_B_ON_COMPARE  = bit (COM2B0),
    CLEAR_B_ON_COMPARE   = bit (COM2B1),
    SET_B_ON_COMPARE     = bit (COM2B0) | bit (COM2B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 7)  // sanity check
    return;

  // reset existing flags
  TCCR2A = 0;
  TCCR2B = 0;
  TimerHelpers.h
  TCCR2A |= (Modes [mode] [0]) | port;
  TCCR2B |= (Modes [mode] [1]) | clock;
  }  // end of Timer2::setMode

}  // end of namespace Timer2

#endif

References

Timers
Interrupts
Arduino Uno output to VGA monitor


How to copy files from local computer to Yun with scp? I need to transfer files from my local machine to my Arduino Yun.

I have tried:

scp /Users/SSCirrus/Documents/index.html root@arduino.local:/root
scp ~/Users/SSCirrus/Documents/index.html root@arduino.local:/root
# No such file or directory (referring to my desktop)

I have confirmed that the filepath is accurate. What's wrong here?

Try ~/Documents/index.html

The ~ represents the current user's home directory, so ~/Documents is the Documents folder for the current user.  It means you don't have to make sure you have spelled the user's home directory exactly right.

Other options are:

$HOME/Documents/index.html
Documents/index.html (if you are in your home directory)
cd ~/Documents then just use index.html

... the list goes on ...


Two arduinos one power source I was surprised that this question had no answer on Stack Exchange and I can't find much about it elsewhere so, in the hopes that it will be useful to people other than myself, I'd like to ask:
How can one power two arduinos using the same power source? Such that the first is connected by barrel jack to a 12v transformer.
I saw this youtube video which very briefly mentions doing this by make the connections:

Ardu1 --> Ardu2
5V --> 5V
GND --> GND

This surprised me as I was not aware the 5V could operate as a power input. I was expecting the use of the VIN pin somewhere along the line.
Am I correct in thinking that the second arduino would take power on it's VIN pin from 5V on arduino one?
If so, where should the second arduino ground to?

You could put the 12v from the barrel jack on both Arduninos Vin pins by jumpering the Vin pins together instead of the Vin->+5 or +5->+5.  Then they'd have independent protection and regulation of 1A, 5V through their NCP1117ST50T3G chips.


How to change this function in to a non-blocking function? How do I modify the getTheNumber() function to satisfy the statement below??
"
This function blocks until the user is done typing the number. Try to rewrite it in a non-blocking fashion. For example, it could return -1 on every call as long as the user is not done typing the number. On the first call after the user is done it would return the valid value. If you manage to write everything non-blocking, then you loop() will restart very often, and the program will work with no significant latency."

Here is the code:

int getTheNumber()
{
    char buffer[4];
    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
            int value = atoi(buffer);
            break;
        }
    }
    return atoi(buffer);
    }

make buffer[] and i static.
get rid of the while() loop.

Like this:

int getTheNumber()
{
    static char buffer[4];
    static int i=0;
    // Input up to 3 numbers until we find a * or #
    char key = keypad.getKey();

    // If it's a number AND we have space left, add to our string
    if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
            return(-1)
        }
        // If it's a * or #, end
    else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
            int value = atoi(buffer);
            i=0;
            return atoi(buffer);
        }
}


How to subtract the current analog value from previous one I pretty new to the Arduino. I am working on project that find the power by reading your

I think you need something like the following :

int lastTime;

void loop(){
  int thisTime = analogRead(A1);
  int diff = thisTime - lastTime;
  lastTime = thisTime;
  Serial.println(diff);
}


Arduino not recognizing when a timer reaches 0 Alright, so I'm attempting to make a timer that will turn on a light after an hour. Currently I have it set to 5 seconds for testing. What is happening is whenever I start the program it won't recognize when the timer reaches 0.
Here is my code

/*
Hour Alarm
An hour long alarm that allows breaks
Created by: Jaxon Reid
Last Edited: 19/5/2017

Pins:
Pin 13 = Led
Pin 2 = Button
*/
int secLeft=5;
const int led=13;
const int button=2;
const int buttonIn=4;
int buttonValue=0;
// Declares the button to reset as 2 and the lightbulb on pin 13
//the secLeft means the seconds until the light turns on and button value is for wether or not the button is pushed

void setup() {
  Serial.begin(2400);
  Serial.print("On  ");
  pinMode(13,OUTPUT);
  pinMode(button,OUTPUT);
  pinMode(buttonIn,INPUT);
}
// makes the led pin an input and opens the channel for the debugger
void loop() {
  int buttonValue=digitalRead(button);
  Serial.println("Checking time");
  if (secLeft<=0) {
    Serial.println("No time remaining");
    digitalWrite(13,HIGH);
    Serial.println("Light On");
    // If the time remaining is 0 then turn on the light
  }
  if (secLeft>0) {
    Serial.println("Time Remaining");
    digitalWrite(led,LOW);
    secLeft=(secLeft--);
    Serial.println(secLeft);
  }
  if (buttonValue==1) {
    int secLeft=5;
    Serial.println("Reset Timer");
    Serial.println(secLeft);
  }
  delay(1000);
}

Whenever I start it up it just starts reading

On 5
Checking time
Time remaining
5
Checking time
Time remaining
4
Checking time
Time remaining
3
Checking time
Time remaining
2
Checking time
Time remaining
1
Checking time
Time remaining
0
Checking time
Time remaining
-1
Checking time
Time remaining
-2

etc...
So where did I go wrong is what I'm asking.
Thanks!

As per comment and Majenko's answer you are current creating local variables called secLeft and secLeft2 inside the 'if block.  These take precedence over the ones you have defined globally.  Removing the in declarations from inside the if block will stop doing that and point you at the globally defined variables.

As to the rest of the code. If you have

secLeft=(secLeft2--);
secLeft2=(secLeft);

Then that translates to this sequence of instructions

Assign secLeft with the value of secLeft2
Decrement secLeft2
Assign secLeft2 with the value of secLeft

And in the end you do not change anything.

This is because you are using post-decrement on secLeft2  EG secLeft2--.  This is a feature of C style languages.

I am not sure what you are even trying to do at this point.


Arduino "Maximum Power point tracker" (MPPT) Problem I need an IV curve for a solar panel. As far I know, solar-panel and Diode IV curve pretty much the same. Here, I am using diodes(6A10-1) as a solar-panel. Where each Diode voltage drops 0.6volt. I provide 4.8v across the diodes from a power supply and limited the current at 1amp of the power supply for acting like a solar panel.
The number of diodes is 8 for a 4.8V drop. A 1-ohm resistor for measuring the current. I am using Arduino to measure the value of current and voltage by varies the MOSFET(IRF540) gate voltage. A low pass filter is connected between D2 and Mosfet Gate. A0 for measuring the solar voltage and Current, Id=A0-A1.
But Arduino gives incorrect values of A1 and current, Id, and sometimes negative values with respect to a multimeter.
[
const int V1 = A0;
const int V2 = A1;
float SolarVolt = 0.0;
float V1_VOLT = 0.0;
float V2_VOLT = 0.0;
float Id  = 0.0;
int V1_value = 0;
int V2_value = 0;
double gateVoltage=150; //For Gate volt
double mstep=5.1;
int GatePin=2;

void setup() {
  pinMode(GatePin,OUTPUT);
  Serial.begin(9600);
  pinMode(V1,INPUT);
  pinMode(V2,INPUT);
}

void loop() {
  analogWrite(GatePin,gateVoltage);
  gateVoltage=gateVoltage+mstep;
  Serial.print("GateVolt = ");
  Serial.print(gateVoltage);
  Serial.print("    ");
  if (gateVoltage <= 0) {
    mstep = 1;
  } else if (gateVoltage>=255){
    gateVoltage = 255;
    mstep = -1;
    delay(50);
  }

  V1_value = analogRead(V1);
  V1_VOLT = (V1_value * 5.0) / 1024.0;

  Serial.print("V1_VOLT= ");
  Serial.print(V1_VOLT);
  Serial.print("    ");

  V2_value = analogRead(V2); // for Id1
  V2_VOLT= (V2_value * 5.0) / 1024.0;

  Serial.print("V2_VOLT= ");
  Serial.print(V2_VOLT);
  Serial.print("    ");

  Id=V1_VOLT-V2_VOLT;

  Serial.print("ID= ");
  Serial.print(Id);
  Serial.println();

  delay(1000);
}

Your current signal will also show PWM, so you will need to filter that before measuring.  It would be much simpler if you could rearrange your circuit to put the sense resistor on the ground side of the MOSFET, since then you can use a simple RC filter and a single A0 measurement.   Also, you wouldn't have to worry about the no-load voltage from the solar panel (when the MOSFET is off) going above the 5V limit of the A0 pin.


Why does the standard Arduino IDE not include the CH341G USB Drivers? Can anyone explain why the standard Arduino IDE 1.6 distribution does not include support for the popular CH341G USB/serial drivers?

I am using these USB/serial chips in several teaching projects for CoderDojo and it is somewhat difficult to have each student download the drivers and reboot their PCs for each class. It seems like both Mac and PC users would benefit from having these drivers loaded directly into the standard Arduino IDE.

Is there possibly some security concern? I know that the latest Mac requires that the drivers are digitally signed. In fact for many modern Macs to use the drivers we have to disable the digital signature checks.

Here is the link to the official drivers.

Here is a good article on how to download the drivers.

BTW, the command to disable the digital signature check on the mac we need to do the following:

In the Mac "Terminal" application enter:

sudo nvram boot-args="kext-dev-mode=1"

Then we must reboot the mac. Then when we want to re-enable the checks change the 1 to 0:

sudo nvram boot-args="kext-dev-mode=0"

If we don't do this command, the Arduino App will not show the serial ports. Do to this go to Tools -> Port Menu within the Arduino application.

/dev/tty.SerialPort
/dev/cu.SerialPort

I should mention that the CH340G are also used in many "Arduino Nano" clones from China. Perhaps that is why the drivers are not included?

Tags: Driver CH340 Setup Installation

This is simply because the CH340G is not supported officially. The Arduino IDE is meant primarily for genuine Arduinos.

What you could do is repackage the Arduino zip file with the required library and create a basic script file to install the drivers with just a couple of clicks.

Or you could shift to another board that uses the ATMEGA32u4 as this might not require anything special. Have a look here. I don't have tested this board so you will need to check the quality and whether it works with your projects.


Disable Reset when Com Port Connected/Disconnected I've noticed that when I open and close the com port my Arduino is connected to, the device resets. This makes the program run the setup profile again and it loses the previous variable states. Is there any way to prevent this?

If you review the Uno schematic, you can see the circuitry that enables an automatic reset when serial communication starts.  The circuitry is intended to allow easy program downloading.

There are two or three ways to prevent that reset:  add a 10 μF capacitor from ground to reset;  use a much-lower resistance for the pullup on reset; cut a trace from the serial-interface pin (eg CTS) that pulls reset.

The first method is relatively easy to implement, and easy to remove whenever you want to install a new program.

References:  Disabling AutoReset On SerialConnection and ArduinoISP on Uno requires 10uF cap -- WHY?, both at Arduino.cc.


OTA update - sodaq board (arduino M0 compatible) I am trying to perform a firmware update from an SD card, on a Sodaq Sara AFF board. If i use the SDU.h library in my sketch, it fails the board check. See this link please.
I have edited the SDU.cpp myself to force the selection of ARDUINO_SAM_ZERO. It is now :
__attribute__ ((section(".sketch_boot")))
unsigned char sduBoot[0x6000] = {
  #include "boot/mzero.h"
};

I have increased the size to 6000 otherwise it was complaining too many initializers.
I also have changed the SD_SS_PIN to match my pin on the SDUboot.ino, under extras. Afterwards, i recompiled it with build.sh in the same folder.
But I am unable to perform the firmware update. After power cycling the board (original code: the blink example, target update: blink with a faster rate) - the original firmware remains.
I exported the firmware using arduino IDE -> export compiled bynary, and tested both versions with and without bootloader.
Any help would be appreciated.

SOLVED!
I have compiled my own SDUBoot.ino with fixed SDU_START 0x2000 and for SODAQ Sara (boot/sodaq_sara.h). My sketch with #include "SDU.h" compiles successfully. The board package is also installed in Arduino (http://downloads.sodaq.net/package_sodaq_samd_index.json). Here my code with changes (base is SodaqCore-samd-1.8.6-sodaq from Github):
File libraries/SDU/extras/SDUBoot/SDUBoot.ino:
#include <SD.h>
#include <FlashStorage.h>

#define SDU_START    0x2000
#define SDU_SIZE     0x4000

#define SKETCH_START (uint32_t*)(SDU_START + SDU_SIZE)

#ifndef SDCARD_SS_PIN
#define SDCARD_SS_PIN 10
#endif

#define UPDATE_FILE "UPDATE.BIN"

FlashClass flash;

// Initialize C library
extern "C" void __libc_init_array(void);

int main() {
  init();

  __libc_init_array();

  delay(1);

  if (SD.begin(SDCARD_SS_PIN) && SD.exists(UPDATE_FILE)) {
    File updateFile = SD.open(UPDATE_FILE);
    uint32_t updateSize = updateFile.size();
    bool updateFlashed = false;

    if (updateSize > SDU_SIZE) {
      // skip the SDU section
      updateFile.seek(SDU_SIZE);
      updateSize -= SDU_SIZE;

      uint32_t flashAddress = (uint32_t)SKETCH_START;

      // erase the pages
      flash.erase((void*)flashAddress, updateSize);

      uint8_t buffer[512];

      // write the pages
      for (uint32_t i = 0; i < updateSize; i += sizeof(buffer)) {
        updateFile.read(buffer, sizeof(buffer));

        flash.write((void*)flashAddress, buffer, sizeof(buffer));

        flashAddress += sizeof(buffer);
      }

      updateFlashed = true;
    }

    updateFile.close();

    if (updateFlashed) {
      SD.remove(UPDATE_FILE);
    }
  }

  // jump to the sketch
  __set_MSP(*SKETCH_START);

  //Reset vector table address
  SCB->VTOR = ((uint32_t)(SKETCH_START) & SCB_VTOR_TBLOFF_Msk);

  // address of Reset_Handler is written by the linker at the beginning of the .text section (see linker script)
  uint32_t resetHandlerAddress = (uint32_t) * (SKETCH_START + 1);
  // jump to reset handler
  asm("bx %0"::"r"(resetHandlerAddress));
}

File libraries/SDU/extras/SDUBoot/build.sh:
#!/bin/sh -x

ARDUINO=arduino
SKETCH_NAME="SDUBoot.ino"
SKETCH="$PWD/$SKETCH_NAME"
BUILD_PATH="$PWD/build"
OUTPUT_PATH="../../src/boot"

if [[ "$OSTYPE" == "darwin"* ]]; then
    ARDUINO="/Applications/Arduino.app/Contents/MacOS/Arduino"
fi

buildSDUBootSketch() {
    BOARD=$1
    DESTINATION=$2

    $ARDUINO --verify --board $BOARD --preserve-temp-files --pref build.path="$BUILD_PATH" $SKETCH
    cat "$BUILD_PATH/$SKETCH_NAME.bin" | xxd -i > $DESTINATION
    rm -rf "$BUILD_PATH"
}

mkdir -p "$OUTPUT_PATH"

buildSDUBootSketch "SODAQ:samd:sodaq_sara" "$OUTPUT_PATH/sodaq_sara.h"

File libraries/SDU/src/SDU.cpp:
#include <Arduino.h>

#include "SDU.h"

__attribute__ ((section(".sketch_boot")))
unsigned char sduBoot[0x4000] = {
  #include "boot/sodaq_sara.h"
};

Sketch file sdu_test.ino:
#include <Arduino.h>
#include "SDU.h"

#if defined(ARDUINO_SODAQ_SARA)
#define DEBUG_STREAM SerialUSB
#else
#error "Please select the SODAQ SARA as your board"
#endif

#define DEBUG_STREAM_BAUD 115200

String message;

void setup() {
  // Start communication.
  DEBUG_STREAM.begin(DEBUG_STREAM_BAUD);

  while (!DEBUG_STREAM) {
    // Wait for Serial Monitor to be opened.
  }

  message += "Sketch compile date and time: ";
  message += __DATE__;
  message += " ";
  message += __TIME__;

  // print out the sketch compile date and time on the serial port
  DEBUG_STREAM.println(message);
}

void loop() {
  // add you own code here
}

File arduino/50/.arduino15/packages/SODAQ/hardware/samd/1.8.6/variants/sodaq_sara/linker_scripts/gcc/flash_with_bootloader.ld add these lines:
KEEP(*(.sketch_boot))

. = ALIGN(0x2000);

here:
...
SECTIONS
{
    PROVIDE(__sodaq_firmware_state = ORIGIN(FLASH) - 0x100);

    .text :
    {
        __text_start__ = .;

        KEEP(*(.sketch_boot))

        . = ALIGN(0x2000);
        KEEP(*(.isr_vector))
        ...

On SD card (formatted as FAT32) I have stored the renamed file UPDATE.bin without bootloader of the compiled sketch file. Pin D10 is connected and used as chip select CS.
Build boot hex files:
$ cd libraries/SDU/extras/SDUBoot
$ ./build.sh

Version 1.8.6-sodaq has these missing lines on arduino_zero variant but not on sodaq_sara variant.


Are there any online data analysis websites for arduino IoT projects? I am planning on making a system where multiple arduinos monitor the conditions of certain type of plant. (Each arduino monitors its own plant, but the plants are of the same species). Each plant would have a different placement in the yard(varies the light). The plants are watered as normal, without an exact amount of water. The arduinos would measure light, temperature, and soil water content. Each would send it to the cloud. My question is: Is their a cloud service that can analyze and "find" the best conditions(amount of water,light,temperature,etc) for type a plant, based on how healthy the plants are?(The health of the plants would be entered in manually by the person using the system). (Sorry if my question doesn't make sense, please ask me any questions you have ,Thanks.)

To send data to cloud you will need an internet shield and given that the individual plants are far apart, you will need a wifi shield for each plant that you want to monitor most likely the yun shield.
Now for online services, there are a few like Temboo, Pushingbox, Initial State, Cayenne, Xively.
Each of them works differently and you will need to choose which best suit you.


Hardware damage from executing tight polling loop over extended periods of time? I want my project to be standing by at the ready for months and years at a time, so I started writing my code to throttle back from polling at delayMicroseconds  to just delay. Like, after 15 minutes with no user input, switch from 10 microsecond delay intervals to 10 millisecond (or even 10 second intervals). I wonder if spinning its wheels at warp speed for months on end will wear a path in the circuit pathways? This has got to be a stupid question (or at least make someone chuckle), but I'm really 50/50 at this point: worth the effort for the extra code or won't make a lick of difference? (I know there's my implementation and then there's the right one, but this is where I am right now. FYI, I went with 17 GPIO's in parallel to link my Pi to my teensyduino. add 17 optocouplers, hot glue, hinges, scavenged enclosures etc and this thing looks ridiculous.  But I LOVE IT! (It's a mouse that I control over the web)

EDIT
Although I didn't mention any concerns about using batteries, their mention didn't really detract from anything. Rather, I welcomed their inclusion because I realized that I had overlooked things more fundamental. I'm always telling others how important ventilation can be and the impact heat can have, but it went right by me this time!

I do value and appreciate the feedback I have gotten. I don't think I will be writing any code to vary polling speed after timing out. But I would still like if someone wanted to directly answer the specific concern I had when posting this question: "At certain times, my program waits for a GPIO pin to change states. I am using the polling method to determine the status of the pin, and I am using this bit of code to do so:

do
{

} while (digitalRead(pin#) == 0); //wait for pin to go high

So, my question is, "Does it make any difference at all, in terms of wear & tear or stress placed on the CPU, how many loops I choose to make in one second? I'm considering something in the range 0.1Hz -> 100kHz  Assuming that I keep heat under control and other vital parameters within their nominal operating levels, is it true that the frequency I choose won't make a bit of difference, one way or another?"

Thanks in advance for any interest given to this question.

There's nothing to save except battery charge (if your system even uses a battery). It will take just as much energy to delay() as it would to keep polling. The only way to save energy is to put the processor to sleep instead of delaying. And polling will be so brief that you might as well keep the sleep time short, too.

You probably don't need 10 uSec poll intervals; I should think your mouse would be plenty responsive with 1 mSec intervals. If polling takes, say, 100 uSec (and that's a total guess) and you sleep the processor for the other 900 uSec, you'll cut the energy use by 90%. If you don't need to save energy, it won't matter whether, or how long, you delay.

Update:

  "Does it make any difference at all, in terms of wear & tear or stress
  placed on the CPU, how many loops I choose to make in one second? I'm
  considering something in the range 0.1Hz -> 100kHz Assuming that I
  keep heat under control and other vital parameters within their
  nominal operating levels, is it true that the frequency I choose won't
  make a bit of difference, one way or another?"

Yes, it is true. Your CPU can run full speed continuously, safely. It won't overheat from continuous running. Only if some part of your project is trying to draw too much current through the CPU; then that will cause heating, but the CPU polling a bunch of inputs is well within its specs.


Can I use The mpu6050 with this? I am making a project with 3 arduinos (2 slave, 1 master) and I want to know can I use the mpu6050 since it uses the I2c communication.

You can but keep the I2C wires less then about 30cm. If they are going to be further apart consider something like RS485 or CAN. Are you sure you need three?


Printing vairable with U8GLib I have this code that takes temperature and humidity values from a DHT11 sensor and number of faces from an external python code and prints them on an OLED screen but instead of values of variables it keeps printing 0, how can I solve it? (Sorry some parts are not in English but just consider them as random variable names.)
//dht11 kodu için ayarlamalar
#include <dht.h>
dht DHT;
#define DHT11_PIN 7

//ekran için ayarlamalar
#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE | U8G_I2C_OPT_DEV_0);
char bufferX [20];
char bufferY [20];
char bufferZ [20];

//fan kodu için ayarlamalar
int mot1 = 8;
int mot2 = 9;
int en1 = 10;
int dir = 6;
bool state = true;
int nob = A0;
int val = 0;
int fan_hizi = 0;
String faces_str;
int faces;
float sicaklik;
float nem;

void draw(void)
{
  u8g.setFont(u8g_font_unifont);
  u8g.drawStr( 0, 15, bufferX);
  u8g.drawStr( 0, 30, bufferX);
  u8g.drawStr( 0, 45, bufferY);
  u8g.drawStr( 0, 60, bufferZ);
}

void setup() {
  Serial.begin(9600); //iletişim ve dht11 verisi

  // pin ayarları
  pinMode(mot1,OUTPUT);
  pinMode(mot2,OUTPUT);
  pinMode(en1,OUTPUT);
  pinMode(dir,INPUT_PULLUP);
}

void loop() {
  //dht11 kodu
  sicaklik = DHT.temperature;
  nem = DHT.humidity;
  delay(1000);

  //iletişim kodu
  if(Serial.available() > 0) {
    faces_str = Serial.readString();
    faces = faces_str.toInt();
  }

  Serial.print(faces);

  //sınırlar
  if(faces == 0 && sicaklik < 25 && nem < 65) {
    fan_hizi = 50;
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
  }
  if(faces >= 1 || sicaklik >= 25 || nem >= 65) {
    fan_hizi = 250;
    digitalWrite(13, LOW);
    digitalWrite(12, HIGH);
  }

  //ekran
  sprintf(bufferX, "Yuzler: %d", faces);
  sprintf(bufferY, "Sicaklik: %d", sicaklik);
  sprintf(bufferZ, "Nem: %d", nem);
   u8g.firstPage();
  do {
  draw();
    }
  while ( u8g.nextPage() );
  delay(10);

  //fan kodu
  analogWrite(en1, fan_hizi);
  digitalWrite(mot1, HIGH);
  digitalWrite(mot2, LOW);
  delay(1000);
  digitalWrite(mot1, LOW);
  }

I do not understand, how you initialize the DHT sensor object.
(I wonder why this compiles at all.)
Your way:
//dht11 kodu için ayarlamalar
#include <dht.h>
dht DHT;
#define DHT11_PIN 7

I would use:
//dht11 kodu için ayarlamalar
#include <DHT.h>
#define DHT11_PIN 7

DHT dht( DHT11_PIN, DHT11 );

Don't forget to start the DHT object with:
void setup() {
  // ... code removed for brevity
  dht.begin();
}

Now use the dht object instad of the DHT class.
sicaklik = dht.readTemperature();
nem = dht.readHumidity();

You did not specify what libraries you have used. But I tried all DHT libs I could find and none of them compiled with your code without errors.
The following code compiles on my IDE for an arduino UNO having olivers ug8lib and adafruits DHT sensor library installed. BTW: You even did not mention the Arduino/ESP you used. So I guess it is an UNO.
//dht11 kodu için ayarlamalar
#include "DHT.h"
#define DHT11_PIN 7
DHT dht( DHT11_PIN, DHT11 );

//ekran için ayarlamalar
#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE | U8G_I2C_OPT_DEV_0);
char bufferX [20];
char bufferY [20];
char bufferZ [20];

//fan kodu için ayarlamalar
int mot1 = 8;
int m ot2 = 9;
int en1 = 10;
int dir = 6;
bool state = true;
int nob = A0;
int val = 0;
int fan_hizi = 0;
String faces_str;
int faces;
float sicaklik;
float nem;

void draw(void)
{
  u8g.setFont(u8g_font_unifont);
  u8g.drawStr( 0, 15, bufferX);
  u8g.drawStr( 0, 30, bufferX);
  u8g.drawStr( 0, 45, bufferY);
  u8g.drawStr( 0, 60, bufferZ);
}

void setup()
{
  Serial.begin(9600); //iletişim ve dht11 verisi

  // pin ayarları
  pinMode(mot1,OUTPUT);
  pinMode(mot2,OUTPUT);
  pinMode(en1,OUTPUT);
  pinMode(dir,INPUT_PULLUP);
}

void loop()
{
  //dht11 kodu
  sicaklik = dht.readTemperature();
  nem = dht.readHumidity();
  delay(1000);

  //iletişim kodu
  if(Serial.available() > 0)
  {
    faces_str = Serial.readString();
    faces = faces_str.toInt();
  }

  Serial.print(faces);

  //sınırlar
  if(faces == 0 && sicaklik < 25 && nem < 65)
  {
    fan_hizi = 50;
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
  }

  if(faces >= 1 || sicaklik >= 25 || nem >= 65)
  {
    fan_hizi = 250;
    digitalWrite(13, LOW);
    digitalWrite(12, HIGH);
  }

  //ekran
  sprintf(bufferX, "Yuzler: %d", faces);
  sprintf(bufferY, "Sicaklik: %d", sicaklik);
  sprintf(bufferZ, "Nem: %d", nem);
  u8g.firstPage();

  do
  {
    draw();
  }  while ( u8g.nextPage() );

  delay(10);

  //fan kodu
  analogWrite(en1, fan_hizi);
  digitalWrite(mot1, HIGH);
  digitalWrite(mot2, LOW);
  delay(1000);
  digitalWrite(mot1, LOW);
}

I do not have the time to assemble the hardware to try it.
So I can say it compiles, but I can not say it works.
EDIT:
Now I found adidax "DHT11 lib". your code compiles with this library. But you forgott to read the values from the sensor, before you read them from the variables.
The following line is missing:
void loop() {
  //dht11 kodu
  DHT.read( DHT11_PIN ); // <-- this line is missing
  sicaklik = DHT.temperature;
  nem = DHT.humidity;
...


ESP8266 on WiFi without password, possible? Is it possible to connect to an SSID that does not require a password?
My project using ESP8266-01 modules will sometimes be used in non-password protected guest networks.

Yes it works! You can use:

WiFi.begin(ssid, NULL)

or even leave the passphrase empty, because it's optional:

Wifi.begin(ssid)

Reference: https://www.arduino.cc/en/Reference/WiFiBegin


Is it possible to simulate PWM using delay() function? I was thinking about if it is possible to simulate PWM (AKA pulse width modulation).
Is it possible to reach the speed of the PWM using the delay() function ?.
Note : I am talking about the pins which does not support PWM, Arduino uno Pin 13 for example.

It is possible to create a PWM signal from a non-PWM digital pin although you would not want to use delay, but timer interrupts for accuracy and finite timing. PWM intervals are typically measured in (μs[microseconds] vs ms[milliseconds]).

The standard Arduino servo library  does this: Servo.


Speed control of BLDC with an integrated controller (Hall out, PWM in) I am aiming at precise speed control of this BLDC motor: it has an integrated controller, outputting digital Hall signal (period 20.8ms on oscilloscope, w/o load) and taking PWM as input for speed regulation.
As far as my knowledge goes, this is a task for PID: measure Hall pulses at input, adjust duty cycle of the PWM based on target period/frequency of the Hall output.
The speed should be controlled with <1% error (even less is better).

Is this goal realistic with this particular motor?
How should I measure pulse duration?
Is pulseIn (with interrupts disabled) going to be sufficiently precise? Should I measure lows or highs?
Should I measure several pulses instead (and how)? Or should I accept imprecision in the pulse period and compensate (smooth) it using integral/derivative terms?
Do I need more than 8-bit PWM resolution for this task? (I will use Nano at first, but might switch to Nano Every, which has 10-bit PWM).

Any other comments/suggestions are welcome.

This is only a partial answer, about measuring pulse period or duration.
For best accuracy, I would recommend using the “input capture” feature
of a 16-bit timer. This is not as easy as using pulseIn() or timing
the signal with micros(): you will have to carefully study the MCU's
datasheet and manually configure the bits of some I/O registers. You
will be rewarded with high accuracy (single-cycle if the timer runs at
the MCU clock speed) and without the jitter inherent to any
software-based approach.
Beware that the Nano and Nano Every use different MCUs, with very
different timers. Both have input capture capability, but if you switch
from one to the other you will have to redo most of the work. Note that
the Nano is capable of 10-bit PWM if you program it low-level.
A software-based approach (pulseIn() or attachInterrupt() +
micros()) has the advantage of portability.


NodeMCU ESP8266 on Arduino IDE doesn't detect Wifi I am using a NodeMCU 1.0 v3 and I am trying the example sketch (wifiscan) but it just doesn't pick up any AP in the house. My phone and laptops etc are able to pick up the APs though.

Other sketches upload and work fine but the wifi aspect of it doesn't work. I even got an LCD sketch to work properly but it isn't able to find any access points or even join any access points. I have been trying to get it to work for hours now.

I first tried using the latest Arduino IDE (1.6.12), then I uninstalled and tried using 1.6.1 but no luck. My upload settings are NodeMCU 1.0 (ESP-12E module), 80Mhz, 115200, 4M (3M SPIFFS).

Your router might be using 5GHz Wifi which the ESP8266 doesn't support but your other devices likely do. Try setting your wifi network to 2.4GHz.


Is it possible to accept multiple web requests at once? I have an Arduino with ethernet shield and there are 8 different URLs that can be called to perform different actions.

The program loads and runs as expected for the most part, but, if it is busy doing an action, it won't accept the next one until the current action has finished.

Basically, the code's main loop listens for a client connection, then has a bunch of ifs that look in the URL that was called (for a query string) and then process the command.

I have looked at a few answers on here, but none deal with listening to HTTP requests. One recommended a library, but, I couldn't quickly get it to compile, and the other answer recommended a state machine - I do like this approach, however, I haven't had time to implement and it doesn't "feel" right as the listening for a HTTP request works on a if(client) basis.

I was wondering if anyone has done this before and/or has any advice?

It can be done. The Arduino is a single tasking environment so you have to make sure your code is non-blocking.

BlinkWithoutDelay is a good starting point (thanks @Majenko) but you should also look at the Timer1 library.

Basically your programs needs to do all the steps it can right away and whenever it does something that could block, it must do it asynchronously and during a later loop() run check if it's finished and continue with the next task. The alternative (if you know how long your task will take) is to use the timer interrupt with the library mentioned above.


Arduino scrolling text program freeze after some time I use a 16x2 character lcd to display some text. What I want is first line will stay, but the second line should scroll text.

I wrote a program which works fine but the problem is after some time arduino does not respond. I suspect there might be a bug or memory leak in the code.

The relevant code is like this.

void scrollTextFromRight(int line, char text[])
{
    const char space[16] = "                ";
    char screen[16];
    char * longText;

    longText = malloc(sizeof(char) * (sizeof(text) + 17));

    memset(longText, '\0', sizeof(char) * (sizeof(text) + 17));
    memset(screen, '\0', sizeof(screen));

    for (int i = 0; i < 16; ++i)
    {
        longText[i] = space[i];
    }

    for (int j = 0; j < sizeof(text) + 17; ++j)
    {
        longText[16+j] = text[j];
    }

    for (int i = 0; i < sizeof(text) + 17; ++i)
    {

        lcd.setCursor(0, line);
        strncpy(screen, longText + i, 17 );
        lcd.print(screen);
        delay(350);
    }
}

I call this function from main program like this:

scrollTextFromRight(1, "Scrolling text");

You malloc but don't free. Of course it's going to leak. Also sizeof(text) doesn't work like that. Instead you can do strlen to get the number of characters in a null-terminated char array.

You can do this without the longText buffer by doing partial copies into screen.

const char space[16] = "                ";
char screen[16];

for (int i = 0; i < sizeof(text) + 17; ++i)
{
    lcd.setCursor(0, line);
    strncpy(screen, space, i); // copy i spaces
    strncpy(screen+i, text, min(17-i, strlen(text))); // copy the rest of the string up to the end whichever is shorter.
    screen[17] = '\0'; // force null termination
    lcd.print(screen);
    delay(350);
}


Proxying streaming i2c data(int values) to serial The following code works correctly in reading single int values. It also works correctly for 3-4 seconds if I 'stream' the values in constantly (Mouse move coordinates) before I get an IO error and the i2C bus connection is dropped. I assume this is some sort of buffer overrun...or? Can anyone get me on the right track here? What changes do I need to make so that I can constantly stream in serial data?

    #include <Wire.h>

#define SLAVE_ADDRESS 0x04
int zeroByte;
int state = 0;
int receivedValue = 0;

int numBytes = 0;

bool newData = false;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);         // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);

    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);

    Serial.println("Ready!");
}

void loop() {
    delay(100);
    if(newData){

      Serial.println(receivedValue);
      newData=false;
    }
}

// callback for received data
void receiveData(int byteCount){

    while(Wire.available()) {
        newData = true;
        zeroByte = Wire.read();

         if(Wire.available() == 2)
  {
    receivedValue = Wire.read() | Wire.read() << 8;

  }

     }
}

// callback for sending data
void sendData(){

    Wire.write(receivedValue);
}

Your I2C bus is operating at 100 kHz. Your serial connection is set to 9600 baud. In case you are sending coordinates at a pace faster than the serial interface can keep up, the buffer will fill up. I assume you are using hardware serial (uno, mega, etc). Once the buffer is filled up Serial.write (which is called by Serial.println) will block until the buffer has free space. But the serial transmission depends on interrupts, and you are calling Serial.write inside an interrupt routine. By defult interrupt routines block other interrupts from happening. So your program gets stuck there and locks up both the serial transmission and the I2C interface.

It would be a good idea to put the serial write outside the interrupt routine, in the loop. Make a global variable bool newData = false; and set it true in the receiveData function. In your loop check the flag and transmit the data. Then set the flag to false.

You will still experience data loss if the serial interface can't keep up, but your application wont lock up. To solve the data loss simply use a higher baud rate, eg. 115200.


Arduino crashing and rebooting I have recently written a program which is supposed to change the duty-cycle to keep the feedback voltage measured on A0, A1 constant. The problem is that the Arduino will start crashing at pretty constant intervals if it approaches it's target current. Once it crashes I have confirmed that it restarts the program (but crashes again in a moment).

Here's a sample of the serial output during the crash:

Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 236.00
Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 235.96
Current A: 65   Current B: 67   PWM A: 174.98   PWM B: 235.92
Current A: 64   Current B: 67   PWM A: 175.00   PWM B: 235.88
Current A: 64   Current B: 66   PWM A: 250.00   PWM B: 285114740000000000000000000.00
Current A: 0    Current B: 0    PWM A: 1.30     PWM B: 0.00
Current A: 0    Current B: 0    PWM A: 2.60     PWM B: 1.30
Current A: 0    Current B: 0    PWM A: 3.90     PWM B: 2.60
Current A: 0    Current B: 0    PWM A: 5.20     PWM B: 3.90

And here is all of my code:

#include <MemoryFree.h>

//Program to run on the Vegetarium
//Written by Leon Teichroeb on 12/6/2016

//Hardware description:
//-Oscillator 2A and 2B for the two onboard driver circuits
//-Pin 13 is attached to the "heartbeat" LED
//-Channel A (3) and B (11) current measurements on A0 and A1

//Functionality:
//-Drive Channels at set current

float PWMA = 0;
float PWMB = 0;

int TARGETA = 65;
int TARGETB = 65;

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

  pinMode(3, OUTPUT);
  pinMode(11, OUTPUT);
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(CS20);
  OCR2A = (int)PWMA;
  OCR2B = (int)PWMB;
  digitalWrite(3, LOW);
  digitalWrite(11, LOW);

  delay(5000);
}

void loop() {
  int CURRENTA = analogRead(A0) / 4;

  if(CURRENTA < TARGETA) {
    PWMA += (TARGETA - CURRENTA) * 0.020f;
    if(PWMA > 250) {
      PWMA = 250;
    }
  }
  if(CURRENTA > TARGETA) {
    PWMA += (TARGETA - CURRENTA) * 0.020f;
    if(PWMA < 5) {
      PWMA = 5;
    }
  }

  int CURRENTB = analogRead(A1) / 4;

  Serial.println("Current A: " + (String)CURRENTA + "\t" + "Current B: " + (String)CURRENTB + "\t" + "PWM A: " + (String)PWMA + "\t" + "PWM B: " + (String)PWMB);
  //Serial.println("PWM A: " + (String)PWMA + "\t" + "PWM B: " + (String)PWMB);
  //Serial.print("freeMemory()=");
  //Serial.println(freeMemory());

  if(CURRENTB < TARGETB) {
    PWMB += (TARGETB - CURRENTB) * 0.020f;
    if(PWMB > 250) {
      PWMB = 250;
    }
  }
  if(CURRENTB > TARGETB) {
    PWMB += (TARGETB - CURRENTB) * 0.020f;
    if(PWMB < 5) {
      PWMB = 5;
    }
  }

  if(PWMA < 10) {
    digitalWrite(3, LOW);
  } else {
    analogWrite(3, (int)PWMA);
  }
  if(PWMB < 10) {
    digitalWrite(11, LOW);
  } else {
    analogWrite(11, (int)PWMB);
  }

  delay(40);
}

My circuit also provides power for the Arduino through a simple 7815 voltage regulator. The analog input does not exceed a few volts, and the PWM outputs are driving two logic level MOSFETs. If more information on the circuit is necessary please let me know!

EDIT: I have found out that it isn't a bug in the two feedback loops, because both work on their own. It crashes as soon as I use both feedback loops together. As far as I'm aware, there are no shared variables or data between them

I finally figured it out, the Arduino was entering a current protection mode causing it to reset. The pins driving the MOSFETs were pulling too much current once the regulation started because of the BUZ11's input capacitance.

To fix the problem I just had to add 120 ohm resistors in series with the gate. This made the activation and deactation slower resulting in less current flow.


EthernetUdp2 does not name a type I'm using arduino Ethernet shield 2 form arduino.org and the arduino IDE 1.7.10 also from arduino.org
the code is :

#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet2.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp2.h>
#include <Twitter.h>
#include <util.h>

#include<SPI.h>

EthernetUdp2 udp;
void setup() {
  // put your setup code here, to run once:

}

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

}

and it is giving the following Error :

Arduino: 1.7.10 (Windows 8.1), Board: "Arduino Uno"

UDPMessages002.ino:14:1: error: 'EthernetUdp2' does not name a type

Error compiling.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

after Enabling Show verbose output I got :

Arduino: 1.7.10 (Windows 8.1), Board: "Arduino Uno"

Build options changed, rebuilding all

Using library Ethernet2 in folder: C:\Program Files\ArduinoOrg\libraries\Ethernet2

Using library SPI in folder: C:\Program Files\ArduinoOrg\hardware\arduino\avr\libraries\SPI

C:\Program Files\ArduinoOrg/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\cores\arduino -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\variants\standard -IC:\Program Files\ArduinoOrg\libraries\Ethernet2\src -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\libraries\SPI C:\Users\friend\AppData\Local\Temp\build8617491196975133384.tmp\UDPMessages002.cpp -o C:\Users\friend\AppData\Local\Temp\build8617491196975133384.tmp\UDPMessages002.cpp.o

UDPMessages002.ino:14:1: error: 'EthernetUdp2' does not name a type

Error compiling.

any Help please

These libraries came with the IDE and were not added by me and all the includes
were added automatically after using Sketch --> Import Library --> Ethernet2

The error you see, 'EthernetUdp2' does not name a type, means exactly that - there is no type EthernetUdp2 defined.

If you look at the source of EthernetUdp2.h, you'll see that the class declaration is EthernetUDP. See:

class EthernetUDP : public UDP {
    private:
        // Private members...
    public:
        EthernetUDP();  // Constructor

      // Public members...

};

class EthernetUDP : public UDP defines a class called EthernetUDP that inherets from the base class UDP. The constructor is what gets called when you instantiate a new object of type EthernetUDP.

Replace the line EthernetUdp2 udp; in your code with EthernetUDP udp; and it should work because the types will match. For reference:

#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet2.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp2.h>
#include <Twitter.h>
#include <util.h>

#include<SPI.h>

EthernetUDP udp; // <---- This works

void setup() {
  // put your setup code here, to run once:

}

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

}


How to rebuild Arduino core for ESP8266 I'm experimenting adding DHCP option 160 to dhcpserver.c in the Arduino core for ESP8266 and therefor need to rebuild the relevant parts.

I made an initial guess that I might be able to make the change by installing using git according to the instructions in the readme and just restarting the IDE. I wasn't surprised to learn that this didn't help. The modifications to dhcpserver.c did not make it to the device following restart of the IDE and a new upload.

From another forum I saw a suggestion that the following commands could be used to rebuild from source:

$ cd esp8266/tools/sdk/lwip/src
$ make install

Again the changes didn't make it to the device after restarting and uploading the sketch again.

Does anyone have any clearer instructions for how to build a new Arduino core for esp8266?

There are four variants of LwIP bundled with the ESP8266 core:

V1.4 (Compile from source)
V1.4 (Precompiled)
V2 Lower Memory
V2 Higher Bandwidth

By default (for most boards) one of the V2 variants is selected. You need to change that to the V1.4 (Compile from source) for it to use the version that you have modified.


ESP01 and Arduino - Serial port confusion I'm trying to understand how to think about ESP01 devices and arduino connectivity

I purchased one of the USB programmers from Ebay to program the ESP01 - this works nicely, I can see the ESP doing things (I have it pinging a server sending data back and forth)

Obviously, the ESP01 has very few GPIO pins, so I'm interested in connecting to an arduino so I can combine the Arduino's IO with the Wifi on the ESP, and this is where I'm getting a little stuck. I'm assuming I have to connect the RX pin on the Uno to the TX on the ESP and the TX on the Uno to the ESP RX to set up the connection, but I'm confused as to which serial port to use on the Uno.

Specifically:

are the TX/RX pins on the arduino actually the same serial port as the USB connector - i.e if my intent is to plug the arduino into a computer to talk to it over USB, should I not then re-use the TX/RX pins to talk to the ESP
if so, should I look to software serial or something similar and use other IO pins on the arduino to connect to the ESP01

... Also, as an aside, if I get this all working, do I still need the USB programmer, or can I then program directly from the arduino?

The Arduino UNO only has one serial port. That is pins 0/1 (RX and TX), which is mapped to the Serial object.

Those pins and that object are also used for communication with the PC through the USB connection. That means you can't easily use them for both PC communication and ESP8266 communication. It's possible, but it gets messy.

That is why many people use SoftwareSerial because that can work on any combination of pins on the Arduino that you like.

  ... Also, as an aside, if I get this all working, do I still need the USB programmer, or can I then program directly from the arduino?

Again, that is possible, but very messy. You could possibly get things to pass through from Serial to a SoftwareSerial instance, but it's not reliable (SoftwareSerial in general is not reliable for sustained transfers of data), and using the Arduino as a dumb UART interface would entail changing the wiring to pins 0/1 when you wanted to program.

So it's far simple to just use your USB interface for programming. Either that or set up OTA programming for the ESP8266 so you don't even have to use wires.


PROGMEM : pgm_read_float_near() equivalent for double? (Arduino Due) I'm using an Arduino Due where double have a size of 8 bytes. In my software, I use double table const stored in prog memory, I was using an UNO before and used pgm_read_float_near() to retreive these values. What function should I use ?

Arduino Due (ARM Cortex-M3) doesn't need anything like PROGMEM as it has access into the flash memory in the same way as into the RAM. The const qualifier is enough to keep it in program memory only.

The AVR based boards like UNO needs PROGMEM because there are different instructions for fetching data from program memory and g++ is not very advanced in this way (some other compilers supports it directly - but usually expensive ones)


Reading PushButton status with pyserial I'm trying to read the status of a PushButton with python via pyserial.

In the loop function of Arduino Uno I have this:

void loop() {

if(digitalRead(BUTTON) == HIGH){
Serial.print("E\n");
while(1){}
}

So, if my pushbutton is pressed, it will send this message "E" via serial and then it will enter in an infinite loop so that nothing else happens.

But I want to detect this message in the python code. So this is my python code:

import serial
import time

try:
   arduino = serial.Serial('/dev/ttyACM0', 9600)
except:
   print "Failed to connect on /dev/ttyACM0"

try:
   print arduino.readline()

   while True:
      if arduino.readline() == 'E':
        print("Detected!\n")

except:
   print ("Failed to read!")

The first print before the infinite While is working: it is printing in the ubuntu terminal "Program Initiated", which is a message that I'm sending in the void Setup function of Arduino.

Then, it gets stucked in the line:

 if arduino.readline() == 'E':

I mean, I press several times my pushbutton, and nothing is happening.

Any help?
Thanks!

The string you are sending ("E\n") is not the same one you are checking for: 'E'.

You could, for example, strip newlines from the string:

if arduino.readline().strip() == 'E':


Error "avr-g++: error: CreateProcess: No such file or directory" When Compiling Script Whenever I try to compile a script, the Arduino IDE throws the error avr-g++: error: CreateProcess: No such file or directory. I've already tried reinstalling the IDE, changing the board version in the board manager to 1.6.21, and deleting the Arduino15 folder under AppData/Local/Arduino15.
This problem appeared suddenly - one compilation worked, and two minutes later, nothing would compile - and occurs across all scripts that I've tried.

I'm working from Windows 10 and compiling for an Arduino Uno.

Turns out that McAfee's Host Intrusion Prevention had decided to start blocking avr-g++.exe. Not sure why it did so all of a sudden, but it's an easy fix once you know where to look. Anyone finding this in the future should be sure to check their antivirus logs to see if the compiler's executable is being blocked.


Change Digispark clock speed, run at low voltage? I have a low voltage (3.2v) application. I was hoping to use the Digispark. I have a solution using a separate Tiny85, but want to use the Digispark USB programming.

To run at lower voltage I think you need the lower clock rate. I have done this using the standalone Tiny85. I could hook up the Digispark to the programmer direct and change the frequency fuses, however...

I assume reducing the clock rate by programming the fuses would break the Digispark boot loader as it would have the wrong timing. Correct?

Can I dynamically switch the clock frequency in my code after the bootloader or is it fuse controlled only?

Is the bootloader available and could I change it to a lower frequency? Would there be a lot of work changing the code to a different freq? Would it be powerful enough to run the USB bootloader?

You can set the clock prescaler at run time. For example:

#include <avr/power.h>

void setup()
{
    clock_prescale_set(clock_div_8);
    // etc...
}

More details in the documentation from
avr-libc.

Note that with this method your Digispark will still be overclocked when
booting, so it might not be 100% reliable. But it will be overclocked
only for a very short time.


How can I power an Arduino Nano with a LiPo battery, preferably 3.7v I am a newbie to Arduino, so please bear with me. I am trying to figure out how to power an Arduino Nano with a LiPo battery. I want to use a 3.7v if possible, as my project needs to be lightweight. There are two possibilities I know could work:

-Taking a USB to Mini-B USB, cutting off the normal USB end, and soldering a connector (based on the battery I use) to that end. I would then plug the Mini-B USB into the Nano, giving it power.

-Using the 5v and Ground pins.

I would prefer to use the USB cable solution, however the 5v/Ground or any other solution is perfectly usable.

Also, would 3.7v be enough to power the Nano, two Infrared LEDS (Launch and Receiver), and a 7-segment LED display. I also have a button.
                                                             Thanks, saddlepiggy!

In short: not reliably.  The Arduino Nano expects either a 5V regulated supply or a 6-20V unregulated supply (https://www.arduino.cc/en/Main/ArduinoBoardNano).  Even if you plugged it in and it worked initially, the battery voltage will decrease gradually as it discharges (LiPo cells can drop as low as ~3.2V), making it more and more unreliable.  You'd technically be overclocking the processor, since the Nano runs at 16 MHz and the datasheet for the microcontroller requires at least a 4.5V supply to run above 10 MHz.

A safer solution would be to use a 2S LiPo battery (~7.4V), which would be plenty to supply the regulated input pin (VIN).  On the other hand, if you're set on using a 3.7V LiPo, other Arduino boards (like certain versions of the Pro Mini) run at 3.3V.

As for your second question, 3.7V is plenty to power a few LEDs so long as they are connected in parallel (or to separate pins).  The only thing you need to be aware of is current draw--more current means shorter battery life.  For example, if your circuit draws 100 mA total from the battery, and your battery is specified at 500 mAh, you will get approximately (500 / 100) = 5 hours of battery life.


ULN2803 and common-anode RGB strip; how am I doing it wrong? I'm not super-good with my electrical foo. But I've managed to get a ULN2803 wired up to give the +12v that my RGB LED strip needs. The strip has four connectors, RGB and common +12v.

My concern is that (I think) the Arduino is shorting out- while the Arduino processes my loop, the USB connection dies and the RX/TX LEDs light up.

Here's how I am wiring things. I'm currently powering the Arduino through USB, so when I say "power supply" I'm referring to the +12v supply I'm using.

power supply ground to Arduino ground, ULN2803 pin 9.
power supply +12v to 2803 pin 10, common +12v on LED strip.
arduino output pin 11 to 2803 pin 1
2803 pin 18 to green LED strip

So, that's my circuit. It works- the strip lights up. But again, I think it's wrong. How do I correct it?

The COM pin on the ULN2803 is for protection when driving inductive loads, which means motors, solenoid.  For an LED, nothing needs connect to COM.

The chip you are using is a low side driver.  That means it connects between the low side of the load (your LED) and ground.  When you drive +5 to the input pin, the transistors will conduct, connecting the output pin to ground.

So for your LED strip make the following connections:

Arduino output pin -> driver input, 1B = pin 1
driver output, 1C = pin 18 -> LED strip R G or B
+12 -> LED strip common power
ground -> GND = pin 9

Without the ground connection on the driver chip, no surprise that odd things happened.  There are diodes designed to protect the input and output pins (see chip data sheet).  Without the ground connection to the driver chip, the input protection diode might have been conducting back to the microcontroller output pin.


DigiSpark AT Tiny85 compile problem? Friend asked me to find problem with compilation for his DigiSpark AT Tiny85 board.
We are trying to compile sketch from here:
https://forum.arduino.cc/index.php?topic=314773.0

But with no luck - there is something mixed in headers or configuration and I do not know what exactly.

This ISR does not compile:

ISR(TIMER1_OVF_vect) {       //timer1 overflow

First there were some errors like TCCR1 = 0; not defined in this sketch, then after playing with #define __ AVR_ATtiny85__, #undef _AVR_IOXXX_H_ and replacing avr/io.h with iotn85.h errors like multiple definition of __vector_x(?) came. Commenting out this line:
//attachInterrupt(0,zeroCrossingInterrupt, FALLING)
helped, but now even this one works, but ISR not.

I know there is a lot of caches and you do not see what is going on behind curtains, but I am quite lost yet...

Maybe there is also problem I have multiple installs in different dirs, but do not know how to clean old ones (1.6.5-r2) and at the end both work same way now, my latest fresh installed is 1.8.9.

Does anyone have any experiences with or some working demo sketch using both compare match and overflow ISRs ?

Edit
Setup info
This board selected (...\AppData\Roaming\Arduino15\packages\digistump\hardware\avr\1.6.7\boards.txt):

digispark-tiny.name=Digispark (Default - 16.5mhz)
digispark-tiny.upload.using=micronucleusprog
digispark-tiny.upload.protocol=usb
digispark-tiny.upload.tool=micronucleus
digispark-tiny.upload.maximum_size=6012
digispark-tiny.build.mcu=attiny85
digispark-tiny.build.f_cpu=16500000L
digispark-tiny.build.board=AVR_DIGISPARK
digispark-tiny.build.core=tiny
digispark-tiny.build.variant=digispark
digispark-tiny.upload.wait_for_upload_port = false
digispark-tiny.upload.use_1200bps_touch = false
digispark-tiny.upload.disable_flushing = false

And these are available:

(...\AppData\Roaming\Arduino15\package_digistump_index.json)
...
"boards": [
  {
    "name": "Digispark (Default - 16.5mhz)"
  },
  {
    "name": "Digispark Pro (Default 16 Mhz)"
  },
  {
    "name": "Digispark Pro (16 Mhz) (32 byte buffer)"
  },
  {
    "name": "Digispark Pro (16 Mhz) (64 byte buffer)"
  },
  {
    "name": "Digispark (16mhz - No USB)"
  },
  {
    "name": "Digispark (8mhz - No USB)"
  },
  {
    "name": "Digispark (1mhz - No USB)"
  }
],
...

Edit 2
Fresh install attempt on W10
Few more links - 2nd manual here:
https://www.electronicshub.org/getting-started-with-attiny85/

http://digistump.com/package_digistump_index.json
have to be translated to
https://raw.githubusercontent.com/digistump/arduino-boards-index/master/package_digistump_index.json

https://downloads.arduino.cc/arduino-1.8.9-windows.zip
W10
When installing shows error downloading (timeout?):
http://downloads.arduino.cc/tools/avr-gcc-4.8.1-arduino5-i686-mingw32.zip

Downloaded by hand to (there was empty file of this name):
...\AppData\Local\Arduino15\staging\packages\
avr-gcc-4.8.1-arduino5-i686-mingw32.zip

...\AppData\Local\Temp\arduino_build_139604\core\core.a(wiring.c.o): In function `__vector_4':

...\AppData\Local\Arduino15\packages\digistump\hardware\avr\1.6.7\cores\tiny/wiring.c:93: multiple definition of `__vector_4'

...\AppData\Local\Temp\arduino_build_139604\sketch\sketch_jun28a.ino.cpp.o:...\arduino-1.8.9\SketchBook\sketch_jun28a/sketch_jun28a.ino:60: first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Digispark (Default - 16.5mhz).

...\AppData\Local\Arduino15\packages\digistump\hardware\avr\1.6.7\cores\tiny\core_build_options.h (not found that file in arduino dir):

/*=============================================================================
  Build options for the ATtiny85 processor
=============================================================================*/

#if defined( __AVR_ATtiny25__ ) || defined( __AVR_ATtiny45__ ) || defined( __AVR_ATtiny85__ )
#define __AVR_ATtinyX5__
#endif

#if defined( __AVR_ATtinyX5__ )

/*
  For various reasons, Timer 1 is a better choice for the millis timer on the
  '85 processor.
*/
#define TIMER_TO_USE_FOR_MILLIS                   1

The problem is the following:

The digispark core already implements the TIMER1_OVF_vect ISR (Timer1 Overflow Interrupt). Since you have a 1 for the #define TIMER_TO_USE_FOR_MILLIS, Timer1 will be used for counting the millis() value in the background. For this the Timer 1 Overflow interrupt is needed.

The code, that you copied from that site, does not anticipate, that you might use a core, that already implements the interrupts. It is written for a generic ATtiny85, not specifically for the Digispark version.

What you can do to solve the problem:

You can use Timer0 for your code, keeping the Digispark core untouched. You can change all registers from Timer1 to Timer0 (by replacing the 1 with a 0). Additionally you need to replace TCCR1 with TCCR0B, because for Timer0 that's the register, that set's the prescaler (and turns the timer off if zero is written to it). Also you need to consider, that Timer0 has other prescaler settings. So the line TCCR1 = B00001011; in zeroCrossingInterrupt()  must be changed to TCCR0B = B00000101;. That will set the prescaler to 1024 as mentioned in the comment. The resulting code compiles fine for me with the digispark core (though I have not tested it's functionality).
You can set the Digispark core to use Timer0 for millis(), by changing the definition of TIMER_TO_USE_FOR_MILLIS in the Attiny85 section of the file arduino_folder/packages/digistump/hardware/avr/1.6.7/cores/tiny/core_build_options.h to the value 0 instead of 1. If you do this, the original sketch compiles fine. Though the comment before that build options states, that Timer1 is better for millis() "for various reasons", which is not very specific. You can try, if it works good for you.
You can use another Attiny core. Though you might have to change it too, to accomodate for the unusual clock frequency fo 16.5MHz (most cores I have seen have 16, 8 and 1MHz). That might be as easy as changing the value of the defined clock speed in the cores files, but I'm not sure about that.


SPISettings was not declared in this scope I'm trying to compile a simple I2C example to read data from an MPU-6050 accel/gyro sensor, but I'm getting the compilation error:

/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:27:8: error: 'SPISettings' does not name a type
 static SPISettings settings;
        ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectHigh()':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:167:9: error: 'class SPIClass' has no member named 'endTransaction'
     SPI.endTransaction();
         ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectLow()':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:9: error: 'class SPIClass' has no member named 'beginTransaction'
     SPI.beginTransaction(settings);
         ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:26: error: 'settings' was not declared in this scope
     SPI.beginTransaction(settings);
                          ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::init(uint8_t, uint8_t)':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:3: error: 'settings' was not declared in this scope
   settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
   ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:53: error: 'SPISettings' was not declared in this scope
   settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
                                                     ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:275:7: error: 'class SPIClass' has no member named 'beginTransaction'
   SPI.beginTransaction(settings);
       ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:279:7: error: 'class SPIClass' has no member named 'endTransaction'
   SPI.endTransaction();
       ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::setSckRate(uint8_t)':
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:14: error: 'settings' was not declared in this scope
     case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
              ^
/usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:66: error: 'SPISettings' was not declared in this scope
     case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
                                                                  ^
make: *** [.build_ano/uno/SD/src/utility/Sd2Card.o] Error 1
Make failed with code 2

I've commented-out all code until it compiled without error, and I found that the error is caused by the line:

#include <Wire.h>

So my minimal code to reproduce the error is:

#include <Wire.h>

void setup(){
}

void loop(){
}

Why is this include throwing this error? Why is it trying to compile code for accessing an SD card when I have no code that uses that?

I'm using Arduino 1.6.1 and targeting the Uno. I found I can fix this error by copying version 1.0 of the Wire library into my local sketch folder.

If fixed this by deleting this built-in library

/usr/share/arduino/libraries/SD

but then I received the error:

/usr/share/arduino/libraries/Robot_Control/ArduinoRobot.cpp:25:2: error: 'Serial1' was not declared in this scope
  Serial1.begin(9600);

so I deleted these libraries as well:

/usr/share/arduino/libraries/Robot_Control
/usr/share/arduino/libraries/Robot_Motor

which appear to be buggy in the 1.6 Arduino release. It's still unclear why any of these libraries were being used, since I wasn't including any of their files.