text:
Get pixel data with OV7670 (w/o FIFO) and Arduino Uno
I have read a great deal today about interfacing the OV7670 with the Arduino Uno. I decided to jump in and start tinkering with this thing. I wired it up according to this schematic:

And I copied and pasted the sketch I found here (http://www.instructables.com/id/OV7670-Without-FIFO-Very-Simple-Framecapture-With-/step3/Upload-sketch-to-Arduino/):
// Source code for application to transmit image from ov7670 to PC via USB
// By Siarhei Charkes in 2015
// http://privateblog.info
//

#include <stdint.h>
#include <avr/io.h>
#include <util/twi.h>
#include <util/delay.h>
#include <avr/pgmspace.h>

#define F_CPU 16000000UL
#define vga   0
#define qvga  1
#define qqvga   2
#define yuv422  0
#define rgb565  1
#define bayerRGB  2
#define camAddr_WR  0x42
#define camAddr_RD  0x43

/* Registers */
#define REG_GAIN    0x00  /* Gain lower 8 bits (rest in vref) */
#define REG_BLUE    0x01  /* blue gain */
#define REG_RED       0x02  /* red gain */
#define REG_VREF    0x03  /* Pieces of GAIN, VSTART, VSTOP */
#define REG_COM1    0x04  /* Control 1 */
#define COM1_CCIR656  0x40    /* CCIR656 enable */

#define REG_BAVE    0x05  /* U/B Average level */
#define REG_GbAVE   0x06  /* Y/Gb Average level */
#define REG_AECHH   0x07  /* AEC MS 5 bits */
#define REG_RAVE    0x08  /* V/R Average level */
#define REG_COM2    0x09  /* Control 2 */
#define COM2_SSLEEP         0x10  /* Soft sleep mode */
#define REG_PID           0x0a  /* Product ID MSB */
#define REG_VER           0x0b  /* Product ID LSB */
#define REG_COM3    0x0c  /* Control 3 */
#define COM3_SWAP         0x40  /* Byte swap */
#define COM3_SCALEEN          0x08  /* Enable scaling */
#define COM3_DCWEN          0x04  /* Enable downsamp/crop/window */
#define REG_COM4    0x0d  /* Control 4 */
#define REG_COM5    0x0e  /* All "reserved" */
#define REG_COM6    0x0f  /* Control 6 */
#define REG_AECH    0x10  /* More bits of AEC value */
#define REG_CLKRC   0x11  /* Clocl control */
#define CLK_EXT           0x40  /* Use external clock directly */
#define CLK_SCALE   0x3f  /* Mask for internal clock scale */
#define REG_COM7    0x12  /* Control 7 */ //REG mean address.
#define COM7_RESET          0x80  /* Register reset */
#define COM7_FMT_MASK         0x38
#define COM7_FMT_VGA          0x00
#define COM7_FMT_CIF          0x20  /* CIF format */
#define COM7_FMT_QVGA         0x10  /* QVGA format */
#define COM7_FMT_QCIF         0x08  /* QCIF format */
#define COM7_RGB          0x04  /* bits 0 and 2 - RGB format */
#define COM7_YUV          0x00  /* YUV */
#define COM7_BAYER          0x01  /* Bayer format */
#define COM7_PBAYER         0x05  /* "Processed bayer" */
#define REG_COM8    0x13  /* Control 8 */
#define COM8_FASTAEC          0x80  /* Enable fast AGC/AEC */
#define COM8_AECSTEP          0x40  /* Unlimited AEC step size */
#define COM8_BFILT    0x20  /* Band filter enable */
#define COM8_AGC    0x04  /* Auto gain enable */
#define COM8_AWB    0x02  /* White balance enable */
#define COM8_AEC    0x01  /* Auto exposure enable */
#define REG_COM9    0x14  /* Control 9- gain ceiling */
#define REG_COM10   0x15  /* Control 10 */
#define COM10_HSYNC         0x40  /* HSYNC instead of HREF */
#define COM10_PCLK_HB         0x20  /* Suppress PCLK on horiz blank */
#define COM10_HREF_REV          0x08  /* Reverse HREF */
#define COM10_VS_LEAD         0x04  /* VSYNC on clock leading edge */
#define COM10_VS_NEG          0x02  /* VSYNC negative */
#define COM10_HS_NEG          0x01  /* HSYNC negative */
#define REG_HSTART    0x17  /* Horiz start high bits */
#define REG_HSTOP   0x18  /* Horiz stop high bits */
#define REG_VSTART    0x19  /* Vert start high bits */
#define REG_VSTOP   0x1a  /* Vert stop high bits */
#define REG_PSHFT   0x1b  /* Pixel delay after HREF */
#define REG_MIDH    0x1c  /* Manuf. ID high */
#define REG_MIDL    0x1d  /* Manuf. ID low */
#define REG_MVFP    0x1e  /* Mirror / vflip */
#define MVFP_MIRROR         0x20  /* Mirror image */
#define MVFP_FLIP   0x10  /* Vertical flip */

#define REG_AEW           0x24  /* AGC upper limit */
#define REG_AEB           0x25    /* AGC lower limit */
#define REG_VPT           0x26  /* AGC/AEC fast mode op region */
#define REG_HSYST   0x30  /* HSYNC rising edge delay */
#define REG_HSYEN   0x31  /* HSYNC falling edge delay */
#define REG_HREF    0x32  /* HREF pieces */
#define REG_TSLB    0x3a  /* lots of stuff */
#define TSLB_YLAST    0x04  /* UYVY or VYUY - see com13 */
#define REG_COM11   0x3b  /* Control 11 */
#define COM11_NIGHT         0x80  /* NIght mode enable */
#define COM11_NMFR          0x60  /* Two bit NM frame rate */
#define COM11_HZAUTO          0x10  /* Auto detect 50/60 Hz */
#define COM11_50HZ          0x08  /* Manual 50Hz select */
#define COM11_EXP   0x02
#define REG_COM12   0x3c  /* Control 12 */
#define COM12_HREF          0x80  /* HREF always */
#define REG_COM13   0x3d  /* Control 13 */
#define COM13_GAMMA         0x80  /* Gamma enable */
#define COM13_UVSAT         0x40  /* UV saturation auto adjustment */
#define COM13_UVSWAP          0x01  /* V before U - w/TSLB */
#define REG_COM14   0x3e  /* Control 14 */
#define COM14_DCWEN         0x10  /* DCW/PCLK-scale enable */
#define REG_EDGE    0x3f  /* Edge enhancement factor */
#define REG_COM15   0x40  /* Control 15 */
#define COM15_R10F0         0x00  /* Data range 10 to F0 */
#define COM15_R01FE         0x80  /*      01 to FE */
#define COM15_R00FF         0xc0  /*      00 to FF */
#define COM15_RGB565          0x10  /* RGB565 output */
#define COM15_RGB555          0x30  /* RGB555 output */
#define REG_COM16   0x41  /* Control 16 */
#define COM16_AWBGAIN         0x08  /* AWB gain enable */
#define REG_COM17   0x42  /* Control 17 */
#define COM17_AECWIN          0xc0  /* AEC window - must match COM4 */
#define COM17_CBAR          0x08  /* DSP Color bar */
/*
* This matrix defines how the colors are generated, must be
* tweaked to adjust hue and saturation.
*
* Order: v-red, v-green, v-blue, u-red, u-green, u-blue
* They are nine-bit signed quantities, with the sign bit
* stored in0x58.Sign for v-red is bit 0, and up from there.
*/
#define REG_CMATRIX_BASE  0x4f
#define CMATRIX_LEN           6
#define REG_CMATRIX_SIGN  0x58
#define REG_BRIGHT    0x55  /* Brightness */
#define REG_CONTRAS         0x56  /* Contrast control */
#define REG_GFIX    0x69  /* Fix gain control */
#define REG_REG76   0x76  /* OV's name */
#define R76_BLKPCOR         0x80  /* Black pixel correction enable */
#define R76_WHTPCOR         0x40  /* White pixel correction enable */
#define REG_RGB444          0x8c  /* RGB 444 control */
#define R444_ENABLE         0x02  /* Turn on RGB444, overrides 5x5 */
#define R444_RGBX   0x01  /* Empty nibble at end */
#define REG_HAECC1    0x9f  /* Hist AEC/AGC control 1 */
#define REG_HAECC2    0xa0  /* Hist AEC/AGC control 2 */
#define REG_BD50MAX         0xa5  /* 50hz banding step limit */
#define REG_HAECC3    0xa6  /* Hist AEC/AGC control 3 */
#define REG_HAECC4    0xa7  /* Hist AEC/AGC control 4 */
#define REG_HAECC5    0xa8  /* Hist AEC/AGC control 5 */
#define REG_HAECC6    0xa9  /* Hist AEC/AGC control 6 */
#define REG_HAECC7    0xaa  /* Hist AEC/AGC control 7 */
#define REG_BD60MAX         0xab  /* 60hz banding step limit */
#define REG_GAIN    0x00  /* Gain lower 8 bits (rest in vref) */
#define REG_BLUE    0x01  /* blue gain */
#define REG_RED           0x02  /* red gain */
#define REG_VREF    0x03  /* Pieces of GAIN, VSTART, VSTOP */
#define REG_COM1    0x04  /* Control 1 */
#define COM1_CCIR656          0x40  /* CCIR656 enable */
#define REG_BAVE    0x05  /* U/B Average level */
#define REG_GbAVE   0x06  /* Y/Gb Average level */
#define REG_AECHH   0x07  /* AEC MS 5 bits */
#define REG_RAVE    0x08  /* V/R Average level */
#define REG_COM2    0x09  /* Control 2 */
#define COM2_SSLEEP         0x10  /* Soft sleep mode */
#define REG_PID           0x0a  /* Product ID MSB */
#define REG_VER           0x0b  /* Product ID LSB */
#define REG_COM3    0x0c  /* Control 3 */
#define COM3_SWAP         0x40  /* Byte swap */
#define COM3_SCALEEN          0x08  /* Enable scaling */
#define COM3_DCWEN          0x04  /* Enable downsamp/crop/window */
#define REG_COM4    0x0d  /* Control 4 */
#define REG_COM5    0x0e  /* All "reserved" */
#define REG_COM6    0x0f  /* Control 6 */
#define REG_AECH    0x10  /* More bits of AEC value */
#define REG_CLKRC   0x11  /* Clocl control */
#define CLK_EXT           0x40  /* Use external clock directly */
#define CLK_SCALE   0x3f  /* Mask for internal clock scale */
#define REG_COM7    0x12  /* Control 7 */
#define COM7_RESET          0x80  /* Register reset */
#define COM7_FMT_MASK         0x38
#define COM7_FMT_VGA          0x00
#define COM7_FMT_CIF          0x20  /* CIF format */
#define COM7_FMT_QVGA         0x10  /* QVGA format */
#define COM7_FMT_QCIF         0x08  /* QCIF format */
#define COM7_RGB    0x04  /* bits 0 and 2 - RGB format */
#define COM7_YUV    0x00  /* YUV */
#define COM7_BAYER          0x01  /* Bayer format */
#define COM7_PBAYER         0x05  /* "Processed bayer" */
#define REG_COM8    0x13  /* Control 8 */
#define COM8_FASTAEC          0x80  /* Enable fast AGC/AEC */
#define COM8_AECSTEP          0x40  /* Unlimited AEC step size */
#define COM8_BFILT    0x20  /* Band filter enable */
#define COM8_AGC    0x04  /* Auto gain enable */
#define COM8_AWB    0x02  /* White balance enable */
#define COM8_AEC    0x01  /* Auto exposure enable */
#define REG_COM9    0x14  /* Control 9- gain ceiling */
#define REG_COM10   0x15  /* Control 10 */
#define COM10_HSYNC         0x40  /* HSYNC instead of HREF */
#define COM10_PCLK_HB         0x20  /* Suppress PCLK on horiz blank */
#define COM10_HREF_REV          0x08  /* Reverse HREF */
#define COM10_VS_LEAD           0x04  /* VSYNC on clock leading edge */
#define COM10_VS_NEG          0x02  /* VSYNC negative */
#define COM10_HS_NEG          0x01  /* HSYNC negative */
#define REG_HSTART    0x17  /* Horiz start high bits */
#define REG_HSTOP   0x18  /* Horiz stop high bits */
#define REG_VSTART    0x19  /* Vert start high bits */
#define REG_VSTOP   0x1a  /* Vert stop high bits */
#define REG_PSHFT   0x1b  /* Pixel delay after HREF */
#define REG_MIDH    0x1c  /* Manuf. ID high */
#define REG_MIDL    0x1d  /* Manuf. ID low */
#define REG_MVFP    0x1e  /* Mirror / vflip */
#define MVFP_MIRROR         0x20  /* Mirror image */
#define MVFP_FLIP   0x10  /* Vertical flip */
#define REG_AEW           0x24  /* AGC upper limit */
#define REG_AEB           0x25  /* AGC lower limit */
#define REG_VPT           0x26  /* AGC/AEC fast mode op region */
#define REG_HSYST   0x30  /* HSYNC rising edge delay */
#define REG_HSYEN   0x31  /* HSYNC falling edge delay */
#define REG_HREF    0x32  /* HREF pieces */
#define REG_TSLB    0x3a  /* lots of stuff */
#define TSLB_YLAST    0x04  /* UYVY or VYUY - see com13 */
#define REG_COM11   0x3b  /* Control 11 */
#define COM11_NIGHT         0x80  /* NIght mode enable */
#define COM11_NMFR          0x60  /* Two bit NM frame rate */
#define COM11_HZAUTO          0x10  /* Auto detect 50/60 Hz */
#define COM11_50HZ          0x08  /* Manual 50Hz select */
#define COM11_EXP   0x02
#define REG_COM12   0x3c  /* Control 12 */
#define COM12_HREF          0x80  /* HREF always */
#define REG_COM13   0x3d  /* Control 13 */
#define COM13_GAMMA         0x80  /* Gamma enable */
#define COM13_UVSAT         0x40  /* UV saturation auto adjustment */
#define COM13_UVSWAP          0x01  /* V before U - w/TSLB */
#define REG_COM14   0x3e  /* Control 14 */
#define COM14_DCWEN         0x10  /* DCW/PCLK-scale enable */
#define REG_EDGE    0x3f  /* Edge enhancement factor */
#define REG_COM15   0x40  /* Control 15 */
#define COM15_R10F0         0x00  /* Data range 10 to F0 */
#define COM15_R01FE         0x80  /*      01 to FE */
#define COM15_R00FF         0xc0  /*      00 to FF */
#define COM15_RGB565          0x10  /* RGB565 output */
#define COM15_RGB555          0x30  /* RGB555 output */
#define REG_COM16   0x41  /* Control 16 */
#define COM16_AWBGAIN         0x08  /* AWB gain enable */
#define REG_COM17   0x42  /* Control 17 */
#define COM17_AECWIN          0xc0  /* AEC window - must match COM4 */
#define COM17_CBAR          0x08  /* DSP Color bar */

#define CMATRIX_LEN             6
#define REG_BRIGHT    0x55  /* Brightness */
#define REG_REG76   0x76  /* OV's name */
#define R76_BLKPCOR         0x80  /* Black pixel correction enable */
#define R76_WHTPCOR         0x40  /* White pixel correction enable */
#define REG_RGB444          0x8c  /* RGB 444 control */
#define R444_ENABLE         0x02  /* Turn on RGB444, overrides 5x5 */
#define R444_RGBX   0x01  /* Empty nibble at end */
#define REG_HAECC1    0x9f  /* Hist AEC/AGC control 1 */
#define REG_HAECC2    0xa0  /* Hist AEC/AGC control 2 */
#define REG_BD50MAX         0xa5  /* 50hz banding step limit */
#define REG_HAECC3    0xa6  /* Hist AEC/AGC control 3 */
#define REG_HAECC4    0xa7  /* Hist AEC/AGC control 4 */
#define REG_HAECC5    0xa8  /* Hist AEC/AGC control 5 */
#define REG_HAECC6    0xa9  /* Hist AEC/AGC control 6 */
#define REG_HAECC7    0xaa  /* Hist AEC/AGC control 7 */
#define REG_BD60MAX         0xab  /* 60hz banding step limit */
#define MTX1            0x4f  /* Matrix Coefficient 1 */
#define MTX2            0x50  /* Matrix Coefficient 2 */
#define MTX3            0x51  /* Matrix Coefficient 3 */
#define MTX4            0x52  /* Matrix Coefficient 4 */
#define MTX5            0x53  /* Matrix Coefficient 5 */
#define MTX6            0x54  /* Matrix Coefficient 6 */
#define REG_CONTRAS         0x56  /* Contrast control */
#define MTXS            0x58  /* Matrix Coefficient Sign */
#define AWBC7           0x59  /* AWB Control 7 */
#define AWBC8           0x5a  /* AWB Control 8 */
#define AWBC9           0x5b  /* AWB Control 9 */
#define AWBC10            0x5c  /* AWB Control 10 */
#define AWBC11            0x5d  /* AWB Control 11 */
#define AWBC12            0x5e  /* AWB Control 12 */
#define REG_GFI           0x69  /* Fix gain control */
#define GGAIN           0x6a  /* G Channel AWB Gain */
#define DBLV            0x6b
#define AWBCTR3           0x6c  /* AWB Control 3 */
#define AWBCTR2           0x6d  /* AWB Control 2 */
#define AWBCTR1           0x6e  /* AWB Control 1 */
#define AWBCTR0           0x6f  /* AWB Control 0 */

struct regval_list{
  uint8_t reg_num;
  uint16_t value;
};

const struct regval_list qvga_ov7670[] PROGMEM = {
  { REG_COM14, 0x19 },
  { 0x72, 0x11 },
  { 0x73, 0xf1 },

  { REG_HSTART, 0x16 },
  { REG_HSTOP, 0x04 },
  { REG_HREF, 0xa4 },
  { REG_VSTART, 0x02 },
  { REG_VSTOP, 0x7a },
  { REG_VREF, 0x0a },

/*  { REG_HSTART, 0x16 },
  { REG_HSTOP, 0x04 },
  { REG_HREF, 0x24 },
  { REG_VSTART, 0x02 },
  { REG_VSTOP, 0x7a },
  { REG_VREF, 0x0a },*/
  { 0xff, 0xff }, /* END MARKER */
};

const struct regval_list yuv422_ov7670[] PROGMEM = {
  { REG_COM7, 0x0 },  /* Selects YUV mode */
  { REG_RGB444, 0 },  /* No RGB444 please */
  { REG_COM1, 0 },
  { REG_COM15, COM15_R00FF },
  { REG_COM9, 0x6A }, /* 128x gain ceiling; 0x8 is reserved bit */
  { 0x4f, 0x80 },   /* "matrix coefficient 1" */
  { 0x50, 0x80 },   /* "matrix coefficient 2" */
  { 0x51, 0 },    /* vb */
  { 0x52, 0x22 },   /* "matrix coefficient 4" */
  { 0x53, 0x5e },   /* "matrix coefficient 5" */
  { 0x54, 0x80 },   /* "matrix coefficient 6" */
  { REG_COM13, COM13_UVSAT },
  { 0xff, 0xff },   /* END MARKER */
};

const struct regval_list ov7670_default_regs[] PROGMEM = {//from the linux driver
  { REG_COM7, COM7_RESET },
  { REG_TSLB, 0x04 }, /* OV */
  { REG_COM7, 0 },  /* VGA */
  /*
  * Set the hardware window.  These values from OV don't entirely
  * make sense - hstop is less than hstart.  But they work...
  */
  { REG_HSTART, 0x13 }, { REG_HSTOP, 0x01 },
  { REG_HREF, 0xb6 }, { REG_VSTART, 0x02 },
  { REG_VSTOP, 0x7a }, { REG_VREF, 0x0a },

  { REG_COM3, 0 }, { REG_COM14, 0 },
  /* Mystery scaling numbers */
  { 0x70, 0x3a }, { 0x71, 0x35 },
  { 0x72, 0x11 }, { 0x73, 0xf0 },
  { 0xa2,/* 0x02 changed to 1*/1 }, { REG_COM10, 0x0 },
  /* Gamma curve values */
  { 0x7a, 0x20 }, { 0x7b, 0x10 },
  { 0x7c, 0x1e }, { 0x7d, 0x35 },
  { 0x7e, 0x5a }, { 0x7f, 0x69 },
  { 0x80, 0x76 }, { 0x81, 0x80 },
  { 0x82, 0x88 }, { 0x83, 0x8f },
  { 0x84, 0x96 }, { 0x85, 0xa3 },
  { 0x86, 0xaf }, { 0x87, 0xc4 },
  { 0x88, 0xd7 }, { 0x89, 0xe8 },
  /* AGC and AEC parameters.  Note we start by disabling those features,
  then turn them only after tweaking the values. */
  { REG_COM8, COM8_FASTAEC | COM8_AECSTEP },
  { REG_GAIN, 0 }, { REG_AECH, 0 },
  { REG_COM4, 0x40 }, /* magic reserved bit */
  { REG_COM9, 0x18 }, /* 4x gain + magic rsvd bit */
  { REG_BD50MAX, 0x05 }, { REG_BD60MAX, 0x07 },
  { REG_AEW, 0x95 }, { REG_AEB, 0x33 },
  { REG_VPT, 0xe3 }, { REG_HAECC1, 0x78 },
  { REG_HAECC2, 0x68 }, { 0xa1, 0x03 }, /* magic */
  { REG_HAECC3, 0xd8 }, { REG_HAECC4, 0xd8 },
  { REG_HAECC5, 0xf0 }, { REG_HAECC6, 0x90 },
  { REG_HAECC7, 0x94 },
  { REG_COM8, COM8_FASTAEC | COM8_AECSTEP | COM8_AGC | COM8_AEC },
  { 0x30, 0 }, { 0x31, 0 },//disable some delays
  /* Almost all of these are magic "reserved" values.  */
  { REG_COM5, 0x61 }, { REG_COM6, 0x4b },
  { 0x16, 0x02 }, { REG_MVFP, 0x07 },
  { 0x21, 0x02 }, { 0x22, 0x91 },
  { 0x29, 0x07 }, { 0x33, 0x0b },
  { 0x35, 0x0b }, { 0x37, 0x1d },
  { 0x38, 0x71 }, { 0x39, 0x2a },
  { REG_COM12, 0x78 }, { 0x4d, 0x40 },
  { 0x4e, 0x20 }, { REG_GFIX, 0 },
  /*{0x6b, 0x4a},*/{ 0x74, 0x10 },
  { 0x8d, 0x4f }, { 0x8e, 0 },
  { 0x8f, 0 }, { 0x90, 0 },
  { 0x91, 0 }, { 0x96, 0 },
  { 0x9a, 0 }, { 0xb0, 0x84 },
  { 0xb1, 0x0c }, { 0xb2, 0x0e },
  { 0xb3, 0x82 }, { 0xb8, 0x0a },

  /* More reserved magic, some of which tweaks white balance */
  { 0x43, 0x0a }, { 0x44, 0xf0 },
  { 0x45, 0x34 }, { 0x46, 0x58 },
  { 0x47, 0x28 }, { 0x48, 0x3a },
  { 0x59, 0x88 }, { 0x5a, 0x88 },
  { 0x5b, 0x44 }, { 0x5c, 0x67 },
  { 0x5d, 0x49 }, { 0x5e, 0x0e },
  { 0x6c, 0x0a }, { 0x6d, 0x55 },
  { 0x6e, 0x11 }, { 0x6f, 0x9e }, /* it was 0x9F "9e for advance AWB" */
  { 0x6a, 0x40 }, { REG_BLUE, 0x40 },
  { REG_RED, 0x60 },
  { REG_COM8, COM8_FASTAEC | COM8_AECSTEP | COM8_AGC | COM8_AEC | COM8_AWB },

  /* Matrix coefficients */
  { 0x4f, 0x80 }, { 0x50, 0x80 },
  { 0x51, 0 },    { 0x52, 0x22 },
  { 0x53, 0x5e }, { 0x54, 0x80 },
  { 0x58, 0x9e },

  { REG_COM16, COM16_AWBGAIN }, { REG_EDGE, 0 },
  { 0x75, 0x05 }, { REG_REG76, 0xe1 },
  { 0x4c, 0 },     { 0x77, 0x01 },
  { REG_COM13, /*0xc3*/0x48 }, { 0x4b, 0x09 },
  { 0xc9, 0x60 },   /*{REG_COM16, 0x38},*/
  { 0x56, 0x40 },

  { 0x34, 0x11 }, { REG_COM11, COM11_EXP | COM11_HZAUTO },
  { 0xa4, 0x82/*Was 0x88*/ }, { 0x96, 0 },
  { 0x97, 0x30 }, { 0x98, 0x20 },
  { 0x99, 0x30 }, { 0x9a, 0x84 },
  { 0x9b, 0x29 }, { 0x9c, 0x03 },
  { 0x9d, 0x4c }, { 0x9e, 0x3f },
  { 0x78, 0x04 },

  /* Extra-weird stuff.  Some sort of multiplexor register */
  { 0x79, 0x01 }, { 0xc8, 0xf0 },
  { 0x79, 0x0f }, { 0xc8, 0x00 },
  { 0x79, 0x10 }, { 0xc8, 0x7e },
  { 0x79, 0x0a }, { 0xc8, 0x80 },
  { 0x79, 0x0b }, { 0xc8, 0x01 },
  { 0x79, 0x0c }, { 0xc8, 0x0f },
  { 0x79, 0x0d }, { 0xc8, 0x20 },
  { 0x79, 0x09 }, { 0xc8, 0x80 },
  { 0x79, 0x02 }, { 0xc8, 0xc0 },
  { 0x79, 0x03 }, { 0xc8, 0x40 },
  { 0x79, 0x05 }, { 0xc8, 0x30 },
  { 0x79, 0x26 },
  { 0xff, 0xff }, /* END MARKER */
};

void error_led(void){
  DDRB |= 32;//make sure led is output
  while (1){//wait for reset
    PORTB ^= 32;// toggle led
    _delay_ms(100);
  }
}

void twiStart(void){
  TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN);//send start
  while (!(TWCR & (1 << TWINT)));//wait for start to be transmitted
  if ((TWSR & 0xF8) != TW_START)
    error_led();
}

void twiWriteByte(uint8_t DATA, uint8_t type){
  TWDR = DATA;
  TWCR = _BV(TWINT) | _BV(TWEN);
  while (!(TWCR & (1 << TWINT))) {}
  if ((TWSR & 0xF8) != type)
    error_led();
}

void twiAddr(uint8_t addr, uint8_t typeTWI){
  TWDR = addr;//send address
  TWCR = _BV(TWINT) | _BV(TWEN);    /* clear interrupt to start transmission */
  while ((TWCR & _BV(TWINT)) == 0); /* wait for transmission */
  if ((TWSR & 0xF8) != typeTWI)
    error_led();
}

void wrReg(uint8_t reg, uint8_t dat){
  //send start condition
  twiStart();
  twiAddr(camAddr_WR, TW_MT_SLA_ACK);
  twiWriteByte(reg, TW_MT_DATA_ACK);
  twiWriteByte(dat, TW_MT_DATA_ACK);
  TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);//send stop
  _delay_ms(1);
}

static uint8_t twiRd(uint8_t nack){
  if (nack){
    TWCR = _BV(TWINT) | _BV(TWEN);
    while ((TWCR & _BV(TWINT)) == 0); /* wait for transmission */
    if ((TWSR & 0xF8) != TW_MR_DATA_NACK)
      error_led();
    return TWDR;
  }
  else{
    TWCR = _BV(TWINT) | _BV(TWEN) | _BV(TWEA);
    while ((TWCR & _BV(TWINT)) == 0); /* wait for transmission */
    if ((TWSR & 0xF8) != TW_MR_DATA_ACK)
      error_led();
    return TWDR;
  }
}

uint8_t rdReg(uint8_t reg){
  uint8_t dat;
  twiStart();
  twiAddr(camAddr_WR, TW_MT_SLA_ACK);
  twiWriteByte(reg, TW_MT_DATA_ACK);
  TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);//send stop
  _delay_ms(1);
  twiStart();
  twiAddr(camAddr_RD, TW_MR_SLA_ACK);
  dat = twiRd(1);
  TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);//send stop
  _delay_ms(1);
  return dat;
}

void wrSensorRegs8_8(const struct regval_list reglist[]){
  uint8_t reg_addr, reg_val;
  const struct regval_list *next = reglist;
  while ((reg_addr != 0xff) | (reg_val != 0xff)){
    reg_addr = pgm_read_byte(&next->reg_num);
    reg_val = pgm_read_byte(&next->value);
    wrReg(reg_addr, reg_val);
    next++;
  }
}

void setColor(void){
  wrSensorRegs8_8(yuv422_ov7670);
}

void setRes(void){
  wrReg(REG_COM3, 4); // REG_COM3 enable scaling
  wrSensorRegs8_8(qvga_ov7670);
}

void camInit(void){
  wrReg(0x12, 0x80);
  _delay_ms(100);
  wrSensorRegs8_8(ov7670_default_regs);
  wrReg(REG_COM10, 32);//PCLK does not toggle on HBLANK.
}

void arduinoUnoInut(void) {
  cli();//disable interrupts

    /* Setup the 8mhz PWM clock
  * This will be on pin 11*/
  DDRB |= (1 << 3);//pin 11
  ASSR &= ~(_BV(EXCLK) | _BV(AS2));
  TCCR2A = (1 << COM2A0) | (1 << WGM21) | (1 << WGM20);
  TCCR2B = (1 << WGM22) | (1 << CS20);
  OCR2A = 0;//(F_CPU)/(2*(X+1))
  DDRC &= ~15;//low d0-d3 camera
  DDRD &= ~252;//d7-d4 and interrupt pins
  _delay_ms(3000);

    //set up twi for 100khz
  TWSR &= ~3;//disable prescaler for TWI
  TWBR = 72;//set to 100khz

    //enable serial
  UBRR0H = 0;
  UBRR0L = 1;//0 = 2M baud rate. 1 = 1M baud. 3 = 0.5M. 7 = 250k 207 is 9600 baud rate.
  UCSR0A |= 2;//double speed aysnc
  UCSR0B = (1 << RXEN0) | (1 << TXEN0);//Enable receiver and transmitter
  UCSR0C = 6;//async 1 stop bit 8bit char no parity bits
}

void StringPgm(const char * str){
  do{
      while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit
      UDR0 = pgm_read_byte_near(str);
      while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit
  } while (pgm_read_byte_near(++str));
}

static void captureImg(uint16_t wg, uint16_t hg){
  uint16_t y, x;

  StringPgm(PSTR("*RDY*"));

  while (!(PIND & 8));//wait for high
  while ((PIND & 8));//wait for low

    y = hg;
  while (y--){
        x = wg;
      //while (!(PIND & 256));//wait for high
    while (x--){
      while ((PIND & 4));//wait for low
            UDR0 = (PINC & 15) | (PIND & 240);
          while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit
      while (!(PIND & 4));//wait for high
      while ((PIND & 4));//wait for low
      while (!(PIND & 4));//wait for high
    }
    //  while ((PIND & 256));//wait for low
  }
    _delay_ms(100);
}

void setup(){
  arduinoUnoInut();
  camInit();
  setRes();
  setColor();
  wrReg(0x11, 11); //Earlier it had the value: wrReg(0x11, 12); New version works better for me :) !!!!
}

void loop(){
  captureImg(320, 240);
}

The sketch has way too many #defines, and isn't exactly straightforward, but at least it loads, although there is one warning:
/Users/charles/Documents/Arduino/cameraTest2/cameraTest2.ino:13:0: warning: "F_CPU" redefined
 #define F_CPU 16000000UL
 ^
<command-line>:0:0: note: this is the location of the previous definition

To validate that this does anything, I tried playing around with ComputerNerd's SimpleFrameGrabber, but I'm on a mac and I ran into problems when trying to ./build:
main.c:26:10: fatal error: 'SDL/SDL.h' file not found
#include <SDL/SDL.h>

I then tried opening up the Arduino IDE Serial Monitor, and am not seeing anything. Should I be seeing anything? I was expecting I would at least see gibberish..
Ideally, I would like to find some simple example code that would setup the camera (the defaults might even be just fine), and allow me to get RGB pixel data for a 320x240 or 640x480 image. If I could just print that to the Serial Output, I could then write a simple python script to save it as a jpg or a png or something.
I just need to get to a sanity state with this thing. Or find another inexpensive camera module that's easier to work with.

The warning you received in the compilation of SimpleFrameGrabber is caused by the lack of SDL library. Refer to the docs or any tutorial, like http://lazyfoo.net/tutorials/SDL/01_hello_SDL/mac/index.php

It is nice that you refer to copy of an original article from http://privateblog.info. Orinal example for Uno was compiled using AtmelStudio. I would recommend use two articles:
Uno version is for AtmelStudio: http://privateblog.info/arduino-uno-i-kamera-ov7670-primer-ispolzovaniya/
Due version is for Arduino IDE: http://privateblog.info/arduino-due-i-kamera-ov7670-primer-ispolzovaniya/
Using them, you can compile program which will work.

//enable serial
UBRR0H = 0;
UBRR0L = 1;//0 = 2M baud rate. 1 = 1M baud. 3 = 0.5M. 7 = 250k 207 is 9600 baud rate.
UCSR0A |= 2;//double speed aysnc
UCSR0B = (1 << RXEN0) | (1 << TXEN0);//Enable receiver and transmitter
UCSR0C = 6;//async 1 stop bit 8bit char no parity bits

This bit enables Serial (Rx=0, Tx=1) at 1M baud. Is the Serial Monitor set to the right baud rate?

I tried changing the baud rate on the serial monitor and still don't see anything.


text:
Are these components connected correctly?
I intend to use two ultrasonic sensors as input and a vibration motor as its output, is this connected correctly?

As part of my project, I intend to use an ultrasonic sensor to feed in distance data and react through vibration motor. I have to confirm this arrangement will work but I don't own an Arduino.

That diagram is a case in point for why Fritzing should never be used for anything, ever. It really doesn't help people to learn how to do a proper schematic, and when people do use it the results are so meaningless as to be laughable.

in short: Definitely Not.
1 : you do really need to connect the trigger pins of the ultrassonic sensors, or else you will not be able to "trigger" them.
Read the ultrassound library examples, they may help you.
2 : I am pretty sure an analog (or digital for that matter) pin in arduino nano cannot sink the current needed to make the motor spin. You are going to fry that pin/port or even brick the entire arduino.
Read on power mosfets for the solution of that.
Moreover, i don't think the 5v out of the arduino feeding the motor is a good idea as well, as the current given by its internal regulator may not be enough for the motor as well.

Yep, unless it is a 20 mA motor, you need an alternative arrangement. Also, driving the whole thing from a 9V battery is a doubtful proposition. You may also want a snubber diode over the motor pins.

@ Marcus Thanks for replying. The trig pins are definitely connected to the board, just that when using this software(fritzing), I won't be able drag the wire to trig pin (it will relocated to the centre), I don't know whether it is a bug or not.

Regarding the vibration motor, I took reference from link, I just wonder why it will work for that. Here is the schematics for my reference link

source: Stack Exchange

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

sort: votes


text:
Win10 PCs won't see ATtiny boards
I bought some ATtiny boards on ebay but I can't get my computers to see them.  When I plug them in I get the USB connected sound then a couple of seconds later it gives the USB unplugged sound.
The power light stays on and the LED blinks, I assume it has the blink sketch already loaded.
I have added the drivers to the IDE but I reckon the problem is before that, something to do with the Win10 PC even seeing it.  I have two versions of the board, one with a USB socket and one with a USB plug, neither work.  [UPDATE] Should have mentioned that the board doesn't show up as being connected to a port
I've looked around for solutions with no joy, I have tried everything I can think of.
Does anyone have a suggestion on where to start troubleshooting this?

Did you try reloading Micronucleus onto them?

Isn't that normal? The board pretends to have a USB interface for a couple of seconds, and then runs the sketch.

@NickGammon  seriously????   I had no idea, I thought it was an error...let me test...

@NickGammon ahhh...but the board doesn't show up as a port...forgot to mention that.  Other boards show up as COM3

YOU GUYS!!!  Between Ignazio and Nick I have solved it.
I wasn't using Micronucleus, I started to.  I thought that no port meant the IDE wouldn't see it but after compiling, and then plugging in the board when prompted it works.  I'll update this as an answer when I can

There were a couple of comments that both led to the solution.
For me the most important was Nick's that the board pretends to have a USB interface for a couple of seconds, and then runs the sketch.  It stopped me tearing my hair out over why the board didn't show up as a port.
Ignacio suggested using Micronucleus.  I did this having installed the Digistump drivers and selecting them.
After compiling I was prompted to plug in the board, voila, it uploaded.
Thanks Stack Exchange!

It's amazing that such a small chip can even simulate USB. There have to be some restrictions on the way it works. Anyway, glad we were able to help.

@NickGammon: The ATtiny85 actually does better than the ATmega328P with V-USB due to the fact that its internal oscillator can be tuned all the way up to 16.5MHz, which opens up almost all Low-Speed USB capabilities.

@IgnacioVazquez-Abrams - yes I suppose, but the Atmega328P can run at 20 MHz. Anyway I was really thinking of squeezing it all into quite a small amount of program memory and RAM.

And THAT @IgnacioVazquez-Abrams is going to be my next question.  512 bytes too big, how to squeeze space.  But I will make it a real question :o)

I have no such luck. The Micronuleous just sits there waiting. After inserting the device. Still nothing. These boards do run the blinky program so it must have got on there somehow.

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


text:
How to save a hex file into Arduino Flash to send it via Serial?
I have a text file with hex values formatted in the following style:
A0 3F 55 01 00 C7 55 01 00 C7 AA 29 71 11 00 0B
00 C7 AA 29 71 1F AA 29 71 11 55 01 A0 3F 55 DC
...

How can I save this data into my Arduino's Flash (to save RAM)? What libraries are needed? Is there any tool that can automatically create code for this purpose?
After I save this data into the Arduino's Flash, I want to send the data via Serial. I have to send it as binary.
A solution without saving it into the Flash would be also OK.
I am using an Arduino Due.

Flash program memory or flash EEPROM?

Flash program memory.

Use objcopy to turn it into a .o file, fabricate an appropriate .h file containing the symbols in the .o file, and then compile against the .h and link against the .o.

Replace the spaces with ,, prepend 0x to the start of each pair, so you get 0xA0, 0x3F, 0x55, ..., then wrap it in const byte myData[] PROGMEM = { ... your data ... }; - Personally I would write a small script to do it in Perl or PHP (I loathe Python with a passion).

If I understand your question correctly, you need to integrate this data into a .ino script.  Probably as a byte array. Then the script can read the array and Serial.write its content.
You could write a small tool in Python or else on your computer, that takes the text file and converts it into a .h header. Include that into your .ino script. Or use your favorite text editor to format the data into C++ code, and copy/paste that into your script.


text:
Wait for serial input otherwise start with preconfigured options
I need to input config parameters from serial input. After a period (1 min) with no input I would like the program to start with preconfigured parameters.
Currently in the loop() section I use Serial.available, which stops until it receives new data.
How can I implement that?
void loop() {
  // read serial input
  if (Serial.available() > 0) {
    inChar = (char)Serial.read();
    inputString += inChar;

The Serial.available function does NOT block execution. If you want to try, upload this
unsigned long lastTime;
#define LED1 5
#define LED2 13

void setup() {
  Serial.begin(9600);
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
}

void loop() {
  if (Serial.available() > 0)
  {
    Serial.read();
    digitalWrite(LED1, !digitalRead(LED1));
  }
  if ((millis() - lastTime) > 500)
  {
    lastTime = millis();
    digitalWrite(LED2, !digitalRead(LED2));
  }
}

You will see led on pin 13 to turn on and off even if the serial port buffer is empty.
Maybe your problem is somewhere else. Anyway what you want can be solved this way:
void setup()
{
    Serial.begin(9600);

    // Wait for one minute - millis is started at 0, so there's no
    // need to store the initial value of the waiting time
    boolean receivedConfiguration = false;
    while ((!receivedConfiguration) && (millis() < 60000))
    {
        if (Serial.available() > 0)
        {
            // There's some data; parse it

            if (__receivedDataIsComplete)
            {
                __myConfiguration = __configurationFromSerial;

                receivedConfiguration = true;
            }
        }
    }
    if (!receivedConfiguration)
    {
        __myConfiguration = __defaultConfiguration;
    }
}

In this setup function, the microcontroller waits for one minute. If it receives the data it ends the waiting time and uses that configuration, otherwise restores the default one and goes on. In your loop you can then use the configuration.
Please note that the variables starting with a double underscore (__) are false variables, you will have to fill with the proper code and/or variables


text:
Using Arduino libraries for adding more functionalities to a bootloader
I have a short question to ask before putting time for research.
I have an Arduino Leonardo with the LUFA mass storage bootloader flashed. Now what I need to do is to add more functionalities to the bootloader. Because in the final product, the Leonardo board will be connected to a fitness machine (permanently connected) and the machine has Windows OS. Then the Leonardo should be able to read an RFID card (I need to add an RFID reader to the board, each user has his own RFID card) and then mount a remote server directory to the local USB Host based on the selected user.
I will have to use a wifi shield too. My question is this: is it theoretically possible to add all these functionalities to the LUFA mass storage bootloader? Because it's not possible to use the Arduino IDE for this purpose, since I'm not uploading any sketch on top of the bootloader, rather than editing the existing mass storage bootloader with the required functionalities and re-flash the chip. Am I correct? (This is what I understood after some research. And I'm a noob :D).
Could you please elaborate what would be the first step for solving this issue?

I couldn't understand WHY you can't create a sketch running after the bootloader that runs the code. Anyway just write a program (like a sketch in arduino, or use directly the avr tools) and then upload it. I suggest you to upload it in the usual way, but if you don't want the bootloader anymore just use an external programmer: you will overwrite it.

just an addendum: a bootloader is just a simple program wich executes at boot and loads the main program after some operations (e.g. check if a newer program should be downloaded and flash it). If you want to use as the normal program, it's not a bootloader anymore (since it is not used to load), but simply a program

mount remote server directory to local USB Host -- Do you have any concept about how those two things operate, and the disparity between them? And how what you propose can never work?

I'm not getting why you want to put all your code in the bootloader. That just doesn't make sense.

@frarugi87 I think my question was not that clearly explained. LUFA mass storage bootloader was used to replace the existing Leonardo bootloader. Now when I plug it to the PC, it doesnt recognised as uc but as a mass storage. So I can't use Arduino to program the application memory

Ok, now I got it. Sorry, since I never played with leonardo I was not used to how the programming or bootloader replacement was done. Anyway, but I may be wrong, since I just did a 5-minutes research, you just have to grab the LUFA source code, install the AVR tools to compile, try to compile the example and see if it works. If it does, you have everything set up correctly. Then modify the LUFA source code to do what you have to, thus creating the program (aka firmware) you need and... You are done. And it won't be a bootloader anymore, but just a firmware ;)

@frarugi87 Thanks for the reply. I kinda got this part. And the mass storage example works fine. But my problem is including arduino libraries to LUFA examples. Because each of these examples have one main makefile and several other makefiles. For a beginner like me it's quite hard to figure out where to add these relevant libraries. For ex: I want to use a SD card shield, and I have to add the libraries in a make file and call the setup function in LUFA  massstorage.c main class :o

Ok, I'm kind of slow these days, so sorry for taking so much to understand ;) Well, arduino compilation is somewhat "simpler" than regular one, so a lot of details are hidden. Now you are moving towards a more "standard" way of coding. For the SD card example, go into the arduino source files folder (don't remember where they are) and grab the files SdCard.h and SdCard.cpp. You'll also need Fat16Config.h and SdInfo.h probably, but compilation errors will tell you what are the missing files. Create a copy of MassStorage (will be your program) and inside of it create the folder MyLibs ...

... and put the sd card library files inside. Now open the makefile and search the variable SRC. These are all the source files you are compiling, so add the source files you have added (in this case, only SdCard.cpp, since the other are header files). And then you (should) have included the SdCard library to this program. Use it like you would in an arduino sketch (so include the header and then use the class). Just one remark: I think you'll need to rename BootloaderMassStorage.c to BootloaderMassStorage.cpp, since you need classes inside (and then there will be problems with plain C, so ...

... maybe you'll need to rename all the files to cpp - and of course change the c extension to cpp also in the makefile). Once done, recompile and flash. There will be a lot of errors, but usually I deal with them one by one, since I'm not much expert and so I usually make a lot of mistakes

@frarugi87 Thanks for the detailed explanation. I will try what you said and will post you about the progress :)

@Isuru sorry, but I read the answers and a question arose: why do you need this? Isn't it simpler to have Windows mount the folder? Through the leonardo you detect the ID, pass it to the PC and then it automatically mounts the correct folder. Do you want more security? Use encryption: store the keys on the leonardo, then show only the enabled one. This way it will be simpler for the PC, and you will get bonus features like network on the PC (and so even remote access or database upload)

Let us continue this discussion in chat.

@Majenko: I think, that the task IS possible, but it is really hard (and Leonardo may need more memory for that eventually and some shields too and so ...) but if I understand the problem, than the Leonardo should pretends to be mass storage device for that application, and pretend it have some folders and files on it, depending which RFID is used to activate it.
The application probabelly is NOT going to format the MSD because it would lose all the user data on it.
So Leonardo can do following:

pretend it is already formatted and have some known filesystem on it (vfat is easy enought and probabelly usable as many USB flash sticks came with it)
when the machine detects inserted USB, it ask for type - so it get MSD
then it will read partition table - Leonardo can emulate it easily, having "just one partition of given size and type" the partition can even be stored as a file on that fileserver to save Leonardo's memory.
next goes reading FAT table and root directory

knowing  the user from RFID it is possible to select the right directory on file server,
then enumerate lengths of all files inside (and directories)
make table with the names and "offset"
send back the FAT as if those files were ordered on the "disk" so each entry points to the following sector, until the last marks EOF
root directory begins after FAT and contains names of the files, their lenghts, dates and starting sectors (and some very basic right like read-only, system and such)
then follows files and directories

each time the machine asks for a "sector", it is possible to compute, in which file the sector is placed, read the portion of a file (potentially fill it with zeroes to "sector lenght" and return it as requested "sector"
if the sector is in directory instead, return the part of directory (that means filenames and such)
if the sector is outside it all (should not happen), return just zeroes.

On the other direction:

if you get something outside structure, put it to temp. file along with address of such stray "sector"
if you get something in a file, just replace the file content on given offset
if you get something in directory, you need to compare it with previous version and "rename file", "create file" or "delete file" acordingly.
it would probabely need two directories on the server for each user - one for actual files, other for "lost sectors" and "deleted files" which could be "reconected", "undeleted" or "attached later" to the files/directories. The second directory can be emptied after "removing USB MSD" when user with given RFID logouts.

It is lot of work, but basically it could be done. It also needs a lot of accounting on the Leonardo and lot of communication with the fileserver, but it is possible to do.
It suppose, that the files on fileserver would not be modified by somebody else while "mounted" and that the Windows machine would not "format" the USB to some kind of filesystem, the Leonardo does not understand (how to translate to the real files on server).
But for the supposed use I think those two conditions could be reasonable. The MSD probabelly just holds the "user profile" so the machine can put in records of hir/her activiti, some stats and so on, probabely it would be just a few growing files maybe even just in root directory.
Anyway I would not like to write such system, as it is terrifying lot of work and a lot of things could go wrong, if there is a bug (or bad connection).
Also the size of required memory for Leonardo is large - probabelly larger, than the Leonardo actually have, but it could be offloaded to the filesystem too (in "hidden directory" not shown to the machine) - which would be slow and hard to manage - or expanded by HW RAM, which would be a lot faster, but needs nontrivial settings.
(Remebers me, how I wrote resident program for DOS, which had just 130 bytes, which swaped in two 16KB widows of EMS where the rest of program (actually interpret of some pseudocode) was placed (it was like 4 or 6 such 16KB pages, but was able to swap itself acordingly) while the remaining two EMS pages was reserverd for data (like 300-400KB total of pseudocode and data) which was also swapped as needed to access everything. From DOS point of view it was just the 130B resident API, from the view of program, which was using it, it was 400KB engine running FORTH-like program and containing database. The result was like 3x faster processing of 2.000+ employes wages.)
Here are the memory restrictions even more tight, but I thing, that it is possible to do such thing, only it is extremely hard to make it work reliably.

Thanks for your detailed answer. I got the general idea about what you explained. Regarding the files that will be written to Leonardo: There will be around 23 small files(no folders) with format "ini", "apt" and "dat". And the Leonardo mass storage has FAT12 file system. And I will extend the storage with a SD card. Yet I have less knowledge in file systems. So I will be spending the next few days on researching about the topics you mentioned. Life is hard xD

From your brief description of what you want to do I think you want to:

Mount a Windows share on your Leonardo
Make said share available through USB MSD

Well, sorry to break it to you, but that is not possible. No, it's not because the Leonardo isn't up to the task, but you are trying to mix two completely different concepts.
A Windows share (CIFS) is a file-centric system. That is, you access files within the share and request bytes at offsets within the files. The client has no concept of the underlying filesystem, it just works on files.
A USB MSD device, in contrast, has no concept of files, directories, etc. Instead all it knows about is blocks. Raw fixed size blocks of data. The computer that it is attached to is what knows what a filesystem is. It requests blocks of data from the MSD and interprets them as a filesystem, allowing you to access the files within it.
You can see the problem you would now face? MSD responding to requests for raw blocks of data from a computer which then wants to get the contents of files from a server - how do they fit together? Simply: they don't.
So you are going to have to re-think your basic idea.
One possible idea would be to use some client-server block based system, such as iSCSI, which gives you block devices on a network (a single file which is an image of a virtual disk), though only the device which is attached to that block device through the network can see the content of it.


text:
bridge messes up serial.print
EDIT
I am using an Genuino Uno & Yun Shield
I am a complete arduino noob
I am creating something where I need a process to execute a command on my yun shield but when I use Bridge.begin(); It scrambles all text to something like this

.ÿš2%š%šr%š%š%šr%š2%š2%º%š%š%š2%º2%º2%ºr%š2%º2%šr%šr%š%š2%šþøøþøøþúøøýýøþþþýþþøøøøúýøþÿøøþþøúýþúøøøþøýøþýúøþþøüþþøýþþøýøúø

and it just keeps adding characters. if I don't use Bridge.begin(); then it correctly prints.
I wrote this short program to replicate the bug:
#include <Process.h>

void setup() {
// put your setup code here, to run once:
// Start the bridge and serial port.
Bridge.begin();
Serial.begin(9600);

 while(!Serial){

 }
}

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

So this will give the scrambled text and when you remove the Bridge.begin(); it will show the text but I really need to use a Process in my other program so as I understand I need Bridge.

Did you really follow the "Arduino - Process - Tutorial" ?

If I use that code I get a SerialUSB not declared in this scope on the last line but if change all of them to Serial then it still gives the scrambled output

This may well not be workable with an Uno as the host, unless you do some serious revision to the behind-the-scenes code, as it probably assumes that there is UART for communication with the Linux module that is distinct from the USB channel to the serial monitor.  That would be true on the Leonardo type system this originated with, but not on an Uno.  Hence your probably probably comes from the Bridge code setting the single serial port to a different rate than you intended to use.

So @ChrisStratton do you maybe have an idea how I could make it work

You need to use the Console class instead of Serial. Official example here.

How can I then view my console because I constantly get "Connection closed by foreign host" on my serial monitor when I connect to the yun shield port in the ide (because it said to do that in the example)

Have you shorted the two pins on Arduino Board? If you don't know what I'm talking about I will give more information.

No I have not I was really hoping I wouldn't need to do that where can I find something to sort them?

And maybe also what pins do I exactly need to sort?

Well, I realized that wouldn't probably be the problem (I had to do it, but I have the old Dragino Yun Shield, so it doesn't matter in your case, probably). But make sure you are not connected to the Arduino by USB cable, but via WiFi.

Well that's a little bit of a problem considering that is my power source

Ok, but make sure in your Arduino IDE you have the Network Port (with IP address) selected, NOT the COM ports.

Yes I am connected through the network

I found this: https://www.arduino.cc/en/Guide/ArduinoYunShield#toc10. So if you are using Arduino UNO or MEGA, you need to short the pins indeed.

How can I sort these then? they say with a jumper but when I google them I only find jumper wires?

In my case the shunt jumpers were included with the shield, but here are some places where you can get one: https://www.sparkfun.com/products/9044, https://www.pololu.com/product/968, http://www.digikey.com/product-detail/en/sullins-connector-solutions/STC02SYAN/S9000-ND/76372. I hope they are the right dimension.

But if I read that text it says I would still be able to work without the jumper. But my problem is that it says Connection closed by foreign host

I found a jumper in an old pc thanks for the help

Great, does it work correctly now?

Bridge and Serial both use the same pins. You cannot use them both.
Bridge runs at a much higher baud rate (230400 IIRC) than Serial, which is why it all messes up.

Do you maybe have an idea why my console says Connection closed by foreign host when I try to view it.


text:
Keypad number input and store
i'm stuck with a little problem. I need to create a program that can store a number via keypad (this number will be chosen by the user) and then do something with it. To be more specific i will create a temperature control in which the user will be able to input a value of temperature they need and then with this value control a heater, but that's another story, the main point here is that the program needs to be able to store a value via keypad.
i use the keypad library and some of its commands like getKey() and waitForKey() and so on.
thanks for your answers!

It doesn't sound like you've asked a question. Can you show us what you have tried?

“Store a number via keypad” is too vague to be an adequate problem description or program specification.  Please edit your post and add question details, keypad model and which pins you attach it to, and some code that shows keypad library #include and calls.  (To mark code as code, highlight it and press ctrl-k)

There are many issue when interfacing a processor to a physical switch.  So many that this one question can and has been broken down into several separate questions here on this web site:

How to de-bounce a switch has been asked many times including here.
How to use pull up resistors with a switch has been asked many times including here.
How to scan a switch matrix has been asked many times including here.

Add to that, you need to decide how to parse your data.

Will you always expect 2 digits?
If so, What will you do if the user enters 3 digits?
Will you support a back-space feature?
Hows about a clear-entry feature?
What about a enter-key feature?

Fortunately many of these questions are addressed in this tutorial.

http://playground.arduino.cc/Code/Keypad#Example here is the setup for you, you should see, what you are pressing.
then try something like this:
int temp=0;
bool in_press=false;
void loop() {
  char key = keypad.getKey();
  if (in_press &&  key == NO_KEY){ in_press=false; return;} // key released
  if ( ! in_press ){
    if (key != NO_KEY){ // if key is just pressed - proceed it
      in_press=true;
      if (key == '*') {temp=0; return;} //cancel input
      if (key == "#') { do_something_with(temp); temp=0;return;} //accept input
      // key is '0'..'9' - add it to result
      temp= temp*10 + (key-'0'); // maybe check it temp is not too high ...
      return;
    }
  }
  // this pass of loop no new key was pressed, do anything else to do
  // if we want, we can test in_press to see, if key is holded or not
  // or ignore it at all
  do_other_stuff_like_blinking_leds_or_what();
} // end of loop()

The return at third line of loop() is unnecessary and is problematic -- it locks out do_other_stuff_like_blinking_leds_or_what() during the whole time a button is  held down.

@jwpat7 No, just one, as it sets in_press to false and so the next time the in_press && ... is false, thereturn is skipped and so no more locking occures. On the other hand those returns may be avoided, but the structure would be more complicated. And if the process is reading human input (really slow) and manages room temperature (slow as hell), then one or two more cycles thru loop() does not mean real problem. I did choose more simple and straithforward approche (and slightly less efficient), as it looked to me, that the autor is not much skilled, so clarity is better than speed.

Ok, you are correct that do_other_stuff...() gets skipped only once.

well there are other returns too, so theoretically you can press/release keys so fast, that the other_stuff is avoided at all - but you cannot do it by hand, you would need some other comp to emulate it. But it is not important here I think.


text:
Flash String Helper object as variable
So I have a Bunch of commonly used char arrays to build commands in my library.
So to preserve memory, I have them put into flash, via PROGMEM ext,
typedef const char PROGMEM ProgChar;
ProgChar AT[] = "AT";
ProgChar AT_RST[] = "RST";

Then in my program I have it all go out to A port via:
*hws << AT << PLUS << CWMODE << EQUAL; //hws can be any Print type,

This is handled by overloading the << operator;
static Print &operator <<(Print &obj, ProgChar* arg) {
  char pbuffbuffer[12]; //create a buffer,
  obj.print(loadProgmemVal(arg,pbuffbuffer)); //Load it, and then pass to obj print method.
  return obj;
}

But this also overloads the << operator for all const char* Which makes me have to do a workaround:
hws->print(1); //HACK

At first, I thought I would overload the operator to handle both a char* and a Prog Char Object, But unfortunately, they are both treated as the same thing at run-time which makes that idea useless.
So after snooping I find the __FlashStringHelper type and macro. Which would allow me to have a sepperate type for these variables, and allow me to overload.
But the problem is, I cant find a good way to Create these:
const __FlashStringHelper MYVAR = F("Some text to be progchared");

Does not compile =/
Now I could probably make some helper method to load them all in, but that is just patching a hack with another hack... Is there any Clean way to do this? So I can use << for all types,
*hws << AT << PLUS << CWMODE << EQUAL << 1 << "\r\n"; //1 and Return break...

Idea: Is the objects in Flash at a lower PTR value then Objects in Ram, and ifso, what is then cutoff?
EG: 0-04f00 = Flash 04f01-fffff = Ram, ext.

Seems like the recommended style is to use the macro FPSTR(). https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html static const char xyz[] PROGMEM = "This is a string stored in flash"; Serial.println(FPSTR(xyz));

Is this legal?
typedef const char ProgChar;
ProgChar AT[] = "AT";

I would think that the PROGMEM can't be in the typedef, i.e.:
typedef const char ProgChar;
ProgChar AT[] PROGMEM = "AT";

If you meant "Is typedef const char PROGMEM ProgChar; ProgChar AT[] = "AT";", legal then apparently it is. typedef const char PROGMEM ProgChar; ProgChar AT[] = "AT"; void setup() { Serial.begin(115200); Serial.println((const __FlashStringHelper *)&AT[0]); } void loop() { ; } compiles, runs, and produces the expected output.


text:
Arduino Mega web server always returning JSON data even if JSON is not passed in URL
I am trying to return JSON data if JSON is found in the HTTP header, and if not I am trying to display a normal page. But instead it always displays the JSON text, even if I do not pass the JSON in the URL! Full code is here.
if (client) {
  // an http request ends with a blank line
  boolean currentLineIsBlank = true;
  boolean sentHeader = false;
  while (client.connected()) {
    if (client.available()) {
      // client data available to read
      char c = client.read(); // read 1 byte (character) from client
      // buffer first part of HTTP request in HTTP_req array (string)
      // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
      if (req_index < (REQ_BUF_SZ - 1)) {
        HTTP_req[req_index] = c; // save HTTP request character
        req_index++;
      }
      // last line of client request is blank and ends with \n
      // respond to client only after last line received
      if (c == '\n' && currentLineIsBlank) {
        if (!sentHeader) {
          // send a standard http response header
          client.println(F("HTTP/1.1 200 OK"));
        }
        // Ajax request - send JSON output
        if (util::StrContains(HTTP_req, "json")) {
          // Spit out JSON data
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: ArduinoMega");
          client.println("Connnection: close");
          client.println();
          client.print("{\"arduino\":[{\"location\":\"outdoor\",\"celsius\":\"");
          client.print(tempInC);
          client.print("\"}]}");
          client.println();
          break;
        } else {
          client.println(F("Content-Type: text/html"));
          client.println(F("Connection: close")); // the connection will be closed after completion of the response
          client.println(F("Refresh: 1000")); // refresh the page automatically every 60 sec
          client.println();
          sentHeader = true;
          client.println(F("<!DOCTYPE HTML>"));
          client.println(F("<title>"));
          client.println(F("Welcome to Arduino WebServer</title>"));
          util::printProgStr(client, htmlStyleMultiline );
          client.println(F(""));
          client.println(c);
          client.print(F("
 LIVE:
"));

Please help.

You should output the contents of HTTP_req to see where/if json is in it.

If I run URL in browser without json text in it then how from where json will come on HTTP_req

@Musa even if I do not pass json it returns json
HTTP_req GET /json HTTP/1.1 Host: 192.168.1.177:8090 U

I see a json in there, you just check the whole thing you should be only checking the url parameters

even if I do not pass json in the url parameters i still get json in HTTP_req

okay, so if you go to http://192.168.1.177:8090/ you still see json in HTTP_req?

Let us continue this discussion in chat.

So figured out the problem, the issue was  I was closing the connection instead when it was json fetched, I had to keep alive the connection.
so replaced client.println("Connnection: close"); with  client.println("Connection: keep-alive");
which fixed the problem.


text:
How can I send/write two doubles via Bluetooth (nRF8001 Bluefruit LE) in Arduino?
I recently purchased an nRF8001 Bluefruit LE and I am now trying to read/send data with an app. But I am not sure how I can write/send a double value. I want to send two double values at once and to successfully send this, do I have to convert these doubles to a byte array? If so I would very much appreciate how that would look!
This is documentation on how my module works:
https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/nrf-uart-in-detail
Under the headline Writing data they give examples on how to send data but as far as I can see (I am a bit new to Arduino code) in their example they only send an int and a string.
I know how to read and set up the module, so it is only the writing/sending doubles that I am struggling with.
These are the two doubles that I wish to send and I control it with:
double valueOne;
double valueTwo;

The Bluetooth control:
Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

So if I for example do this:
BTLEserial.write(valueOne, valueTwo);

I get this message: no matching function for call to 'Adafruit_BLE_UART::write(double&, double&)'
So do I need to convert these two double values to a byte array and if so how would that look?
Appreciate every help, tips, code! :)

After the first successful message received, did you see the location refreshed on the serial monitor by the Serial.println(gps.location.lat(),6); ?

I see that once yes and also the Serial.println(gps.location.lng(),6); once

Also the Serial.println(F("* Connected!")); once

Seeing once Serial.println(F("* Connected!")); is normal, because the message is sent only when the status change. But are you sure that your gps.location.isUpdated() is true ?

I removed gps.location.isUpdated() in the if-statement but it still stops right when I connect my app to the bluetooth. I also added a Serial.println("test"); right at the top of the while loop and that stops once i connect the app with the bluetooth as well so there must be something else.

And what is strange is: If i remove the write/print function. It works and Serial.println(gps.location.lng(),6); keeps getting written out in the log. So it is that last line when I write the data the while loop decides to stop

When reading the "nRF UART In Detail", only 20 bytes could be sent at a time... So, try send a small string in place of sBuffer... Then reduce the size of sBuffer by sending less decimal for your location.

I kinda need the lat/long decimals to be as exact as possible when i send them. I tried with this code: String slat = (String)latvalue;     BTLEserial.print (slat); but that gave me the same result unfortantly

I recieve this amount of decimals right now from my lat value 15.728758 which is 8 numbers and the same amount of numbers from my lng value. Should this be a problem?

Try to send for instance just "lat,lon" that very small message... Is it sent periodically ?

So just BTLEserial.print("lat,lon");?

Same thing :(
When I connect i get this in the monitor:

Connected!
0.000000
0.000000

0.000000  is the lat, lng that is currently empty and I dont send that, i just write them out in the while loop each time it runs to see if it keeps running after i sent "lat,lon"

Ok I figured out the codeline that makes it work but I am not sure how to solve it without it because I do not want to read current data, i want to send new data. I need this line in order to make it work String vOut = Serial.readString();

Check it out here: https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/nrf-uart-in-detail on the first code example you can find it and how the code works when they write it. If i copy that it works. But if i create my own string and replace that one line i mentioned above String vOut = Serial.readString(); it does not work.

I made a new post covering that exact issue

As the link "Adafruit - nRF UART In Detail" describes, the function write(sendbuffer, sendbuffersize); is waiting for a buffer of uint8_t followed by the size of the message.
Here are the step--by-step solution to send the 2 doubles by using that function.
Step1 - convert the floating-point values into a char string.

In the Arduino environment, the standard format-specifier %f or %lf
  is not well-managed and the function dtostrf() is recommended.

The format is char *   dtostrf (double __val, signed char __width, unsigned char __prec, char *__s) where:

__val is the floating-point value to be converted,
__s is the array of char to store the result,
__width is the number of characters to store the result,
__prec is the number of digit

The conversion is:
char sValueOne[16], sValueTwo[16];
char sBuffer[33];

strcpy(sBuffer,dtostrf(valueOne, 15, 8, sValueOne));
strcat(sBuffer,",");
strcat(sBuffer,dtostrf(valueTwo, 15, 8, sValueTwo));

Step2 - write the buffer over the BTLEserial object.
BTLEserial.write((uint8_t *)sBuffer, strlen(sBuffer));

Alternate output solution using BTLEserial.print() function.

BTLEserial.print(sBuffer);

so should I use a strcpyon the sValueOne and a strcaton sValueTwo? What does these strcpy and strcpy mean? What type of function is it? Btw, thanks a lot for the answer!! I learned a lot with your example

Both functions strcpy() and strcat() are used to copy char strings. The first is used to initialize the buffer char sBuffer[33] and the second is used to concatenate the extra string to the existing. If valueOne= 8.89 and valueTwo=9.88, the first string is sValueOne =  "8.89000000" and the second string is sValueTwo =  "9.98000000" and the output buffer is sBuffer = "8.89000000,9.98000000".

How often can I write code? Is it possible to do it each 0.5 second?

Ok. Thanks a lot for explaining that! my both doubles cointains 6 numbers after. I send coordinates looking like this:  `double latvalue;
double lngvalue;
latvalue = (gps.location.lat(),6);
lngvalue = (gps.location.lng(),6);`

The period is highly depending of the real baudrate of your BTLEserial device. The conversion is enough fast for two samples per second.

Alright! Thanks a lot for your help! Appreciate it a lot

After I write/print with the bluetooth, the void loop()stops and it does not keep working/running. Any idea why this is?

I add a delay (500); after the write/print but still the while loop stops after the first "run"

Could you edit your question and add your source code ?

Sure one second

Updated now with source code

When i connect my phone to the bluetooth device it works once, atleast I think) so becuase I recieve the latvalue + lngvalue when I print out in my serial monitor and also i get  "Connected". But I only recieve this once.

I didn't try this, but since Adafruit_BLE_UART inherits from Stream,
which in turn inherits from Print, you should be able to
BTLEserial.print(valueOne);
BTLEserial.print(",");
BTLEserial.println(valueTwo);

Codes uploads without any trouble! However the while-loop stops with my current code when I use your code as well. It works once (when I connect to the bluetooth with my phone) I edited the post with my source code if you want to check it out.

If i completely remove write or print and connect to the bluetooth with my app the while loop keeps going but if i add your code or j.piquards code the while loop stops right away when i connect the app with the bluetooth


text:
WiFiManager autoconnect after timeout
I like to configure my ESP8266 with WiFiManager. After each power cycle, the config portal should open and wait for a new configuration. If there is no new configuration entered, WiFiManager should autoconnect with the last/old configuration.
For this I modified AutoConnectWithFSParametersAndCustomIP.ino slightly as you can see here:

#include <FS.h>                   //this needs to be first, or it all crashes and burns...

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

//define your default values here, if there are different values in config.json, they are overwritten.
//length should be max size + 1
char mqtt_server[40];
char mqtt_port[6] = "8080";
char blynk_token[33] = "YOUR_BLYNK_TOKEN";
//default custom static IP
char static_ip[16] = "10.0.1.56";
char static_gw[16] = "10.0.1.1";
char static_sn[16] = "255.255.255.0";

//flag for saving data
bool shouldSaveConfig = false;

//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println();

  //clean FS, for testing
  //SPIFFS.format();

  //read configuration from FS json
  Serial.println("mounting FS...");

  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("opened config file");
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        json.printTo(Serial);
        if (json.success()) {
          Serial.println("\nparsed json");

          strcpy(mqtt_server, json["mqtt_server"]);
          strcpy(mqtt_port, json["mqtt_port"]);
          strcpy(blynk_token, json["blynk_token"]);

          if(json["ip"]) {
            Serial.println("setting custom ip from config");
            //static_ip = json["ip"];
            strcpy(static_ip, json["ip"]);
            strcpy(static_gw, json["gateway"]);
            strcpy(static_sn, json["subnet"]);
            //strcat(static_ip, json["ip"]);
            //static_gw = json["gateway"];
            //static_sn = json["subnet"];
            Serial.println(static_ip);
/*            Serial.println("converting ip");
            IPAddress ip = ipFromCharArray(static_ip);
            Serial.println(ip);*/
          } else {
            Serial.println("no custom ip in config");
          }
        } else {
          Serial.println("failed to load json config");
        }
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }
  //end read
  Serial.println(static_ip);
  Serial.println(blynk_token);
  Serial.println(mqtt_server);

  // The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length
  WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
  WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5);
  WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 34);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;

  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);

  //set static ip
  IPAddress _ip,_gw,_sn;
  _ip.fromString(static_ip);
  _gw.fromString(static_gw);
  _sn.fromString(static_sn);

  wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);

  //add all your parameters here
  wifiManager.addParameter(&custom_mqtt_server);
  wifiManager.addParameter(&custom_mqtt_port);
  wifiManager.addParameter(&custom_blynk_token);

  //reset settings - for testing
  //wifiManager.resetSettings();

  //set minimu quality of signal so it ignores AP's under that quality
  //defaults to 8%
  wifiManager.setMinimumSignalQuality();

  //sets timeout until configuration portal gets turned off
  //useful to make it all retry or go to sleep
  //in seconds
  wifiManager.setTimeout(120);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if (!wifiManager.startConfigPortal("AutoConnectAP", "password")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(5000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");

  //read updated parameters
  strcpy(mqtt_server, custom_mqtt_server.getValue());
  strcpy(mqtt_port, custom_mqtt_port.getValue());
  strcpy(blynk_token, custom_blynk_token.getValue());

  //save the custom parameters to FS
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["mqtt_server"] = mqtt_server;
    json["mqtt_port"] = mqtt_port;
    json["blynk_token"] = blynk_token;

    json["ip"] = WiFi.localIP().toString();
    json["gateway"] = WiFi.gatewayIP().toString();
    json["subnet"] = WiFi.subnetMask().toString();

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }

    json.prettyPrintTo(Serial);
    json.printTo(configFile);
    configFile.close();
    //end save
  }

  Serial.println("local ip");
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.gatewayIP());
  Serial.println(WiFi.subnetMask());
}

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

}

My Problem is, that it does not connect after timeout. Only the config portal is closed.
What do I need to change, so that it automatically connects after timeout?

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


text:
Digital Reading from a array without using the exact element
Is it possible to read a digital input from an array without using the exact element? Such as
   while(digitalRead(myButtonArray[i]))
     digitalWrite(myLEDArray[i], HIGH);

Reading the myButtonArray one by one and turning on the led one by one doesnt make for clean written code. The following is just an example code. When button on pin 2 which is element 0 is pressed turn on led on pin 7 and turn off when released. When button on pin 3 is pressede turn on led on pin 8 and turn off when released and continue on in the same fashion with the rest of the buttons and leds as well.
 int myButtonArray[] = {2,3,4,5,6};
 int myLEDArray[] = {7,8,9,10,11};

 void setup() {
   for(int i = 0;i<5;i++){
     pinMode(myButtonArray[i], INPUT);
     pinMode(myLEDArray[i], OUTPUT);
   }

 }

 void loop() {
 while(digitalRead(myButtonArray[0]))
      digitalWrite(myLEDArray[0], HIGH);

 while(digitalRead(myButtonArray[1]))
      digitalWrite(myLEDArray[1], HIGH);

 while(digitalRead(myButtonArray[2]))
      digitalWrite(myLEDArray[2], HIGH);

 while(digitalRead(myButtonArray[3]))
      digitalWrite(myLEDArray[3], HIGH);

 while(digitalRead(myButtonArray[4]))
      digitalWrite(myLEDArray[4], HIGH);
 }

You want a for loop.

The AVR chip has operations that affect multiple pins at once, however this is guided/limited by their organization into ports at hardware level; the Arduino framework slaps numbers on these that bridge the divisions between the several distinct ports, and then gives you "one pin at a time" functions that hide all that detail.  I don't believe there are any Arduino-type bulk methods short of using the individual methods in a loop, and targeting the actual AVR port registers is usually only recommended where speed, rather than cleanliness, is the goal.

Is this what you want?
 #define NUM_ITEMS 5
 int myButtonArray[NUM_ITEMS] = {2,3,4,5,6};
 int myLEDArray[NUM_ITEMS] = {7,8,9,10,11};

 void setup() {
   for(int i = 0;i<NUM_ITEMS;i++){
     pinMode(myButtonArray[i], INPUT);
     pinMode(myLEDArray[i], OUTPUT);
   }

 }

 void loop() {
     for (int i=0 ; i<NUM_ITEMS ; ++i) {
         while(digitalRead(myButtonArray[i]))
              digitalWrite(myLEDArray[i], HIGH);
         digitalWrite(myLEDArray[i], LOW);
     }
 }

This code does the job I was looking for exactly. Thanks for your help.

You're welcome. Worth spending some time understanding the other answers as well because there are some interesting points made.

I think, you did not realized, that digitalWrite(i,value) sets the pin i to value AND the pin have the value until set otherwise. So you probabelly want something like this:
void loop() {
  for (int i=0;i<5;i++)
    digitalWrite(myLEDArray[i], digitalRead(myButtonArray[i]));
}

where each LED follows each respective Button both HIGH and LOW.

It isn't clear from the question or the code what you actually want to do.  Perhaps back up a step: edit the question and write a clear-cut problem specification.
For example, a specification for what the code you have actually does, is:

For each of five buttons,

If button k is on, turn on LED k, and stall in a loop until button k is released.  Leave LED k on when the button is released.

I made an edit so hopefully it is easier to understand now.

@1fastk: It is still unclear whether the “stall in a loop” behavior is a desired feature or a bug in your code.

@EdgarBonet: Im not exactly sure what you mean by "stall in a loop" but what I am trying to achieve is to not have to have multiple digitalRead and digitalWrite statement for every element inside of the arrays. I want to just have only one digitalRead statement to read which button is HIGH inside of the array and then to have one digitalWrite statement to write the led HIGH of the same element. If the element 3 goes high on myButtonArray[] to write element 3 in the myLEDArray HIGH as well. I hope this make better since.

I mean that while the first button is HIGH, your program does not check the other buttons, as it is stuck inside a while loop.

In your question you wrote

and turn [the LED] off when [the corresponding button is] released

and yet you never turn the LEDs off in your code. Then, I assume the
code in your question is irrelevant, and you just want the LEDs to show
the states of the buttons at all times. This can be done by writing to
the LEDs the values you read from the buttons. Do this for each
button/LED pair, and loop over the pairs:
void loop() {
    for (int i = 0; i < 5; i++)
        digitalWrite(myLEDArray[i], digitalRead(myButtonArray[i]));
}

Yes the code here is irrelevant, I wrote it just for a quick example to see if it was possible to digitalRead from a array and then to  digitalWrite to an LED in another array of the same element. Thanks for your help


text:
Sense checking Arduino Uno barebones schematic
I have had some difficulties finding a barebones Arduino board and have had the following made. I just wanted to see if anyone could spot any issues? I think it has everything. I'm really trying to get it as minimalistic as possible, but at the same time able to use a power source like a 12v/24 battery. Any help would be greatly appreciated. Many thanks

You shouldn't put a capacitor under the chip like that. In fact I don't much like the layout of the whole crystal circuit at all.
You need capacitors on the 7805 regulator - around 10µF on both the input and output.
The RESET pin needs a pullup resistor otherwise the chip won't function at all.
You need decoupling capacitors on all VCC pins on your main chip.
Instead of meandering ground traces you should use a ground pour.
Running from the kind of voltages you propose the 7805 is going to melt. You will need a BigAss™ heat-sink on it. For those kind of voltages you would be better using a switching (aka buck) regulator. Maybe as an off-board module to keep your board simple.

Many thanks for your help Majenko. Do you think there is any way to get around the issues with the board as it is? I've (foolishly) already sent 10 of those to print. I'm guessing with 1, I could add the capacitors off board. Also doesn't the 1N4007 help at all?

Most things you can work out a way to solder them in afterwards. The biggest issue will be heat from the regulator. By adding a switching regulator on a separate board to feed the 7805 you would solve that problem. Regulate down to about 7v.

The 1N4007 will just drop 0.7V so does very little in the scheme of things. It is really only for reverse power protection.

Ah I see, so putting something like this to feed the 7805 should solve the problem? http://ebay.eu/2hVTZRX

No, exactly oposite of that - step-up converts low voltage to higher (say input 3.2V and output of 7V (to feed your own 7805). You want step-down (like this one http://www.ebay.co.uk/itm/LM2596-DC-DC-Switching-Adjustable-Step-Down-Voltage-Regulator-Converter-3V-40V-/172058668488?var=&hash=item280f7eedc8:m:mDHLwFGVrh49Tb7BA-Y6CWg or any other with Input rang covering yours 12-24V (rather little more) and OUTPUT of 7V for your 7805. Maybe you can even go with some outputting 5V and big capacitor to filter the switching noise, if you want risk and save more money.

The diode there is good, if you have some other sink (like motor, servo or such) powered by the same batery, as it protects the Arduino from short drops of power, when such motor took big current to start moving and so drops the voltage for a moment. See the picture here (http://petr-kubac.blog.cz/1202/kubacova-magicka-dioda-ktera-se-porad-opakuje), also you can translate it from CZECH by google or so.

there are two ways how to drop voltage - one is switching (with or without transformer), which usually have high efficiency and does not burn much energy, the other is to just burn energy on some resistors, diodes and such, which have efficiency lower when the difference is bigger - as you need the same current going thru and just make heat on the regulator, to eat the voltage. Arguino needs 5V, if you have 24V then you need to burn 19V, which is 4x the Arduino itself eats. And that all goes to the heat. So BigAss heat-sink is needed and even so you drain your battery just for nothing.

long story short, use step-down to the voltage you need, then stabilise it. If you plan for some motors, servos or something like that on the same batery, use the diode too and regulate for 7.7V, send it to the diode, then to the regulator with capacitors around. Otherwise your Arduino is at risk of random restarts every time you use that motor/servo/something.

C4 is under the IC, which may (or may not) do problems, regardless which side of PCB you place it actually. The reset is better to connect via resistor to defined level than to leave floating. Usually there is also capacitor there to delay start until power is stabilized. I would put big capacitor near the stabiliser (also I think, it is recomended by manufacturer of the stabiliser for a reason), but maybe if you have good batery and short wires, it could work too. Also small capacitors between GND and VCC as near the IC as possible are common to reduce noise. And reset button is usefull add-on, but not necessary. Anyway I think, it could work as it is (with the reset defined).
If you have some particular application in mind, then you may use also different layout and/or get more connectors for some pins (some of my "arduinos" does not look like Arduino at all, having all periferials on the same PCB instead on some shields.
also http://download.gilhad.cz/arduinobb_12.jpg this is fully working arduino, which I used many times - so you do not miss anything critical (those LEDS are not necessary)

Many thanks for your help Gilhad. With regards to the reset, would connecting it through a resistor to ground solve the problem? Majenko (above) said it probably would not work without this.

No, that is a boost regulator. You want a buck regulator (step-down). They do some that look very similar to that one.

Yes, he was right (in some way) - depending of intended use the resistor can be onboard, or offboard or managed some other way (as output of some othe system, or programmed to be NOT reset, but I/O, for example). But fof simple generic Arduino board you should put there resistor and if you already send it to production, then just solder the resistor over the board - ugly but sure work.

With regards to the reset, would connecting it through a resistor to ground solve the problem? - no, /RESET needs a pull-up resistor. Something like 10k soldered from Reset to Vcc.


text:
Arduino keeps crashing
I've got an Arduino with a WS2812 hooked up to it, powered by the USB on my computer and I am trying to run the following code:
#include <FastLED.h>

#define NUM_LEDS 144
#define DATA_PIN 6
#define LED_TYPE WS2812B
#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
  FastLED.show();
}

void loop() {
  for(int dot = 0; dot < NUM_LEDS; dot++) {
    fill_solid(leds, NUM_LEDS, CRGB::Red);
    leds[dot] = CRGB::Black;
    leds[dot] = CRGB::Blue;
    FastLED.show();
    leds[dot] = CRGB::Red;
    delay(30);
  }
}

void setAll() {

  FastLED.show();
}

What this does is sets all the LEDs to red, then goes through each one turning it off, then to blue and then back to red.
For some reason, it gets X number of LEDs along and then crashes.  By crashes I mean the Arduino disconnects itself from the computer, but the Arduino stays on with the LED strip still powered up.
Any ideas?  This is a genuine Uno and I can run any of the FastLED or NeoPixel examples for hours on end without an issue

Have you checked the memory footprint?

I'm not 100% sure how I go about this, but when I upload the code, it says its taking up X bytes which if I recall was about 25%.  Also, I can throw any of the complex FastLED examples onto it and run them without any problems at all

Have you checked the power requirements? Circuit?

The LEDs require 5v and are powered off the Arduinos 5v pin. It's a fairy simple setup. Grd to grd pin, data to pin 6 and live to 5v

X number of LEDs time 60 mA > USB Amax.

This is a duplicate of Arduino keeps crashing in Stack Overflow. It already has an answer there (and the OP said in chat that the problem was the power: http://chat.stackoverflow.com/transcript/message/34924703#34924703 ). I'm closing this as a duplicate.

Please do not cross-post the same question on different Stack Exchange sites. See Is cross-posting a question on multiple Stack Exchange sites permitted if the question is on-topic for each site?.

I'm voting to close this question as off-topic because it has been cross-posted to Stack Overflow. Also it is a power issue, not an Arduino issue.

I'm going to add to this.  This might be a power issue, but it is also an Arduino resolution.  Within FastLED there is a power setting which can be used to control the power of the LEDs.  A USB3 port gives off a maximum of 900mAh, so setting the following code configures the commands sent to the LEDs to scale as to not use more than the power parameter given FastLED.setMaxPowerInVoltsAndMilliamps(5,900);

It is inferred from your question that the Arduino is getting powered through the USB port.  As you say the Arduino appears "gone" from the computer when you light up too many LEDs.
All USB ports are only obliged to supply 500mA with out the USB Device (the Arduino) negotiating for more power from the USB Host.  If the load goes beyond 500mA, the USB Host (the computer) can limit the power my reducing the voltage.  At some point the Atmel processor on the Arduino will stop working.
There are many tutorial on how to use LED strips on the web.  Most will indicate power from a larger than normal power supply is necessary.  Also, that the LED strip power should be connected directly to an appropriately chosen power supply.
The following image from this web page illustrates this:

(Note: In this picture PIN 6 was chosen to communicate with the LED strip.  Your specific application (program or sketch) may use a different pin. Also, realize that the power supply in the picture is wired to only power the LED strip. The Arduino still needs to be powered.)

You are correct for only fort the example above. I can quite happily make the entire strip white at 100% brightness or run any of the FastLED or Neopixel examples without an issue.

I'm trying this with my 5V PSU now, however I can't even get the LEDs to power on (even with just lighting 1 LED)  The LED 5V goes to my PSU 5V+, GRD & Data to my arduino

What you say sound correct.  If you are using 2 power supplies make sure their grounds are connected.  I will add a link to a LED strip how to web page to my answer to help out.

See Powering NeoPixels.

Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue).

OK, so you have 144 LEDs.
#define NUM_LEDS 144

That means you need to allow for 8.64 amps to power them!
144 * 0.060 = 8.64

(This is a worst-case scenario, but you should probably allow for 2 amps at least).
As st2000 points out, the USB interface will provide 500 mA (0.5 amps). So you are possibly 8 amps short. You need to power the NeoPixels independently, not through the Arduino.
By powering them through the Arduino they are draining the current from the USB port so much that the over-current protection kicks in.

See my comment above. Your answer is theoretically correct, bit given that I can light the entire strip white and 100% brightness and run any FastLED without issue, it would disprove your theory on power consumption

I measured my 24-pixel strip using your sketch and it took 388 mA. Extrapolating to 144 pixels you get 144/24 * 388 which is 2.328 amps. You just can't get that from your USB supply! I note that you acknowledge here that "OK well power was definately the issue" so perhaps you can upvote the replies here that said so, and accept one of them.


text:
Output specific value using port manipulation
How can I output a specific value on a pin using port manipulation?
Example: I want to use this code but without any arduino functions, just with port manipulation:
for (int i = 0; i < 255; i++){
analogWrite(11, i); //write the i value to pin 11
}

I want to replace the analogWrite function with register manipulation. Is that possible?

Of course, how do you think analogWrite does it?

@NickGammon Alright, I made some quick research and I am back from where I started. I must actually generate a PWM on that PIN and change the duty cycle acordingly ( basically what analogWrite does). Am I right?

Have you read the ATmega328 datasheet? This is where you have to start. Taking a look at the implementation of analogWrite() might help too.

The analogWrite function is just an interface to setting up the hardware timers to do PWM (pulse-width modulation). I have a page about timers which you may find helpful.
Depending on which pin you want to output the PWM to, the registers will be slightly different. Here is one example from my page:
const byte OUTPUT_PIN = 3;  // Timer 2 "B" output: OC2B

const byte n = 224;  // for example, 1.111 kHz

void setup()
 {
  pinMode (OUTPUT_PIN, OUTPUT);

  TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1); // fast PWM, clear OC2A on compare
  TCCR2B = bit (WGM22) | bit (CS22);         // fast PWM, prescaler of 64
  OCR2A =  n;                                // from table
  OCR2B = ((n + 1) / 2) - 1;                 // 50% duty cycle
  }  // end of setup

void loop() { }

How can I output a specific value on a pin ?

I should point out that the only values you can output are +5V or 0V. There is no provision for outputting (say) 3.7V. The only way you can sort-of do this is by using PWM and then running the result through an RC filter. There is an example on my page about op amps.
An example circuit could be:

This uses a resistor and capacitor to filter out the "ripple" in the PWM, giving you a reasonably smooth output voltage, proportional to the PWM duty cycle.
For a larger range of output values a rail-to-rail op-amp would be preferable.


text:
Arduino Leonardo model differences
I was thinking of buying another Arduino, and the Leonardo looks appropriate.
However I am confused! The Comparative Tables seems to show 2 different Leonardos. (This table is very difficult to read with tiny black text on a grey background, and no key to the column headings.)
There appear to be different models "R3" and "R4" from different retailers and Element14 seems to have a "U4". Can anyone clarify the differences?
I assume I can use the Uno Prototyping shield on the Leonardo.

Wow! I'll have to talk to them about that. :) I think you can take that as a typo.

I think the pin-outs are the same on both boards (the pin spacings) so the shield should work on the Leonardo. The signals will differ a bit from the Uno to the Leonardo.

Personally I wouldn't buy the Leonardo unless I specifically needed the USB interface stuff (eg. mouse/keyboard emulation). There are more sketches for the Uno than for the Leonardo. However if you want to make something that simulates a keyboard, then the Leonardo is the way to go!

Personally I wouldn't buy either. I'd buy the chipKIT Lenny, but then I made it :P Not such good USB support yet though, so it depends what you want from it...

At the end of the day the Leonardo is just a chip (ATMega32U4) on a board with a voltage regulator, a couple of LEDs and USB socket / shield headers. There's not much else to it.
Different revisions may change some of the support components - maybe a component went EOL and they needed to change it, or a better / cheaper one came along that they switched to - but the basic design of it - a chip on a board with minor support components - can't really change.
The reason it's hard to find the differences between the different revisions is because those differences are so inconsequential to the end user that knowing them is irrelevant. The only real way you'd find the differences would be to compare the schematics of each revision to find the components that have changed. In some cases it may even just be a change to the silk screening in re-branding from Arduino to Genuino, or just a slightly more modern logo, etc.
It's still the same chip, and still connected up in the same way.

In fact I decided to buy a Pro Mini instead, as I don't need USB.