text:
OLED display wrong (using SPI )
I can't figure out where I doing wrong
https://www.youtube.com/watch?v=35NqOANmgUE
This is my question in videos

The both of two connect the same pin
(so the right display result is the correct  OLED)
My connecting table  (using SPI )
GND              gnd
VCC              5V
D0(OLED_CLK)     10
D(OLED_MOSI)     9
RES(OLED_RESET)  13
D/C(OLED_DC)     11
CS（OLED_CS）    12
but the left OLED doesn't have the "RES" pin
(so I didn't connect it)
the left OLED just display the upper part
(and its the position of display picture is also wired ,too)
this is my code
/*********************************************************************
This is an example for our Monochrome OLEDs based on SSD1306 drivers
This example is for a 128x64 size display using SPI to communicate
4 or 5 pins are required to interface

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

Written by Limor Fried/Ladyada  for Adafruit Industries.
BSD license, check license.txt for more information
All text above, and the splash screen must be included in any redistribution
*********************************************************************/

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// If using software SPI (the default case):
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

/* Uncomment this block to use hardware SPI
#define OLED_DC     6
#define OLED_CS     7
#define OLED_RESET  8
Adafruit_SSD1306 display(OLED_DC, OLED_RESET, OLED_CS);
*/

#define NUMFLAKES 10
#define XPOS 0
#define YPOS 1
#define DELTAY 2

#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH  16
static const unsigned char PROGMEM logo16_glcd_bmp[] =
{ B00000000, B11000000,
  B00000001, B11000000,
  B00000001, B11000000,
  B00000011, B11100000,
  B11110011, B11100000,
  B11111110, B11111000,
  B01111110, B11111111,
  B00110011, B10011111,
  B00011111, B11111100,
  B00001101, B01110000,
  B00011011, B10100000,
  B00111111, B11100000,
  B00111111, B11110000,
  B01111100, B11110000,
  B01110000, B01110000,
  B00000000, B00110000 };

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

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

  // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
  display.begin(SSD1306_SWITCHCAPVCC);
  // init done

  // Show image buffer on the display hardware.
  // Since the buffer is intialized with an Adafruit splashscreen
  // internally, this will display the splashscreen.
  display.display();
  delay(2000);

  // Clear the buffer.
  display.clearDisplay();

  // draw a single pixel
  display.drawPixel(10, 10, WHITE);
  // Show the display buffer on the hardware.
  // NOTE: You _must_ call display after making any drawing commands
  // to make them visible on the display hardware!
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw many lines
  testdrawline();
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw rectangles
  testdrawrect();
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw multiple rectangles
  testfillrect();
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw mulitple circles
  testdrawcircle();
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw a white circle, 10 pixel radius
  display.fillCircle(display.width()/2, display.height()/2, 10, WHITE);
  display.display();
  delay(2000);
  display.clearDisplay();

  testdrawroundrect();
  delay(2000);
  display.clearDisplay();

  testfillroundrect();
  delay(2000);
  display.clearDisplay();

  testdrawtriangle();
  delay(2000);
  display.clearDisplay();

  testfilltriangle();
  delay(2000);
  display.clearDisplay();

  // draw the first ~12 characters in the font
  testdrawchar();
  display.display();
  delay(2000);
  display.clearDisplay();

  // draw scrolling text
  testscrolltext();
  delay(2000);
  display.clearDisplay();

  // text display tests
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println("Hello, world!");
  display.setTextColor(BLACK, WHITE); // 'inverted' text
  display.println(3.141592);
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.print("0x"); display.println(0xDEADBEEF, HEX);
  display.display();
  delay(2000);

  // miniature bitmap display
  display.clearDisplay();
  display.drawBitmap(30, 16,  logo16_glcd_bmp, 16, 16, 1);
  display.display();

  // invert the display
  display.invertDisplay(true);
  delay(1000);
  display.invertDisplay(false);
  delay(1000);

  // draw a bitmap icon and 'animate' movement
  testdrawbitmap(logo16_glcd_bmp, LOGO16_GLCD_HEIGHT, LOGO16_GLCD_WIDTH);
}

void loop() {

}

void testdrawbitmap(const uint8_t *bitmap, uint8_t w, uint8_t h) {
  uint8_t icons[NUMFLAKES][3];

  // initialize
  for (uint8_t f=0; f< NUMFLAKES; f++) {
    icons[f][XPOS] = random(display.width());
    icons[f][YPOS] = 0;
    icons[f][DELTAY] = random(5) + 1;

    Serial.print("x: ");
    Serial.print(icons[f][XPOS], DEC);
    Serial.print(" y: ");
    Serial.print(icons[f][YPOS], DEC);
    Serial.print(" dy: ");
    Serial.println(icons[f][DELTAY], DEC);
  }

  while (1) {
    // draw each icon
    for (uint8_t f=0; f< NUMFLAKES; f++) {
      display.drawBitmap(icons[f][XPOS], icons[f][YPOS], logo16_glcd_bmp, w, h, WHITE);
    }
    display.display();
    delay(200);

    // then erase it + move it
    for (uint8_t f=0; f< NUMFLAKES; f++) {
      display.drawBitmap(icons[f][XPOS], icons[f][YPOS],  logo16_glcd_bmp, w, h, BLACK);
      // move it
      icons[f][YPOS] += icons[f][DELTAY];
      // if its gone, reinit
      if (icons[f][YPOS] > display.height()) {
    icons[f][XPOS] = random(display.width());
    icons[f][YPOS] = 0;
    icons[f][DELTAY] = random(5) + 1;
      }
    }
   }
}

void testdrawchar(void) {
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);

  for (uint8_t i=0; i < 168; i++) {
    if (i == '\n') continue;
    display.write(i);
    if ((i > 0) && (i % 21 == 0))
      display.println();
  }
  display.display();
}

void testdrawcircle(void) {
  for (int16_t i=0; i<display.height(); i+=2) {
    display.drawCircle(display.width()/2, display.height()/2, i, WHITE);
    display.display();
  }
}

void testfillrect(void) {
  uint8_t color = 1;
  for (int16_t i=0; i<display.height()/2; i+=3) {
    // alternate colors
    display.fillRect(i, i, display.width()-i*2, display.height()-i*2, color%2);
    display.display();
    color++;
  }
}

void testdrawtriangle(void) {
  for (int16_t i=0; i<min(display.width(),display.height())/2; i+=5) {
    display.drawTriangle(display.width()/2, display.height()/2-i,
                     display.width()/2-i, display.height()/2+i,
                     display.width()/2+i, display.height()/2+i, WHITE);
    display.display();
  }
}

void testfilltriangle(void) {
  uint8_t color = WHITE;
  for (int16_t i=min(display.width(),display.height())/2; i>0; i-=5) {
    display.fillTriangle(display.width()/2, display.height()/2-i,
                     display.width()/2-i, display.height()/2+i,
                     display.width()/2+i, display.height()/2+i, WHITE);
    if (color == WHITE) color = BLACK;
    else color = WHITE;
    display.display();
  }
}

void testdrawroundrect(void) {
  for (int16_t i=0; i<display.height()/2-2; i+=2) {
    display.drawRoundRect(i, i, display.width()-2*i, display.height()-2*i, display.height()/4, WHITE);
    display.display();
  }
}

void testfillroundrect(void) {
  uint8_t color = WHITE;
  for (int16_t i=0; i<display.height()/2-2; i+=2) {
    display.fillRoundRect(i, i, display.width()-2*i, display.height()-2*i, display.height()/4, color);
    if (color == WHITE) color = BLACK;
    else color = WHITE;
    display.display();
  }
}

void testdrawrect(void) {
  for (int16_t i=0; i<display.height()/2; i+=2) {
    display.drawRect(i, i, display.width()-2*i, display.height()-2*i, WHITE);
    display.display();
  }
}

void testdrawline() {
  for (int16_t i=0; i<display.width(); i+=4) {
    display.drawLine(0, 0, i, display.height()-1, WHITE);
    display.display();
  }
  for (int16_t i=0; i<display.height(); i+=4) {
    display.drawLine(0, 0, display.width()-1, i, WHITE);
    display.display();
  }
  delay(250);

  display.clearDisplay();
  for (int16_t i=0; i<display.width(); i+=4) {
    display.drawLine(0, display.height()-1, i, 0, WHITE);
    display.display();
  }
  for (int16_t i=display.height()-1; i>=0; i-=4) {
    display.drawLine(0, display.height()-1, display.width()-1, i, WHITE);
    display.display();
  }
  delay(250);

  display.clearDisplay();
  for (int16_t i=display.width()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, i, 0, WHITE);
    display.display();
  }
  for (int16_t i=display.height()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, 0, i, WHITE);
    display.display();
  }
  delay(250);

  display.clearDisplay();
  for (int16_t i=0; i<display.height(); i+=4) {
    display.drawLine(display.width()-1, 0, 0, i, WHITE);
    display.display();
  }
  for (int16_t i=0; i<display.width(); i+=4) {
    display.drawLine(display.width()-1, 0, i, display.height()-1, WHITE);
    display.display();
  }
  delay(250);
}

void testscrolltext(void) {
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(10,0);
  display.clearDisplay();
  display.println("scroll");
  display.display();

  display.startscrollright(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrollleft(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrolldiagright(0x00, 0x07);
  delay(2000);
  display.startscrolldiagleft(0x00, 0x07);
  delay(2000);
  display.stopscroll();
}

I think I have the same problem like this link
http://www.electroschematics.com/11150/cheap-oled-displays-arduino/
but the case is using I2P
and I didn't understand how it resolve the bug

Nobody wants to watch videos. Clearly type and post exactly what the problem is, as well as, your code so far, if any.

Check the connection. That does not look like SPI.

@WillyLotus -  This question doesn't clearly ask a question.  You have an issue, but its not clear which display has the fault, you say left, but from what perspective.  There is no indication of any make or model numbers of the faulty unit.  You imply that the two displays are not the same or one has a pin missing.  Please can you try and improve the question and keep all the information on this site as external links may not be trust worthy.  Sorry, I'm not trying to be horrible, I'm actually trying to help you get a better answer faster.

Are they both the same model? Both the same resolution? Both the same driver chip?

Check the connections with that required by the software/library. If you intend to use SPI the pins on Arduino Uno are:
SS   10
MOSI 11
MISO 12
SCK  13

You connections above are:
VCC             => 5V
D0(OLED_CLK)    => 10 (SPI SS ??)
D(OLED_MOSI)    => 9
RES(OLED_RESET) => 13 (SPI SCK ??)
D/C(OLED_DC)    => 11 (SPI MOSI ??)
CS（OLED_CS）     => 12 (SPI MISO ??)
GND             => GND (??)

That is not correct for SPI. Post link to library, oled hardware, and snippet of your code for more help.
It is more than the video that is out of focus :)
Cheers!

For the OP, slave select can be whatever pin one defines while writing the library, that means if the library supports it you can use multiple SPI slaves (multiple, different screens at one for example) but it's usually not that easy (depends of the frame of reference) unless someone has done it already and uploaded the code.


text:
Problem using Adafruit nRF8001 (BLE) with Ethernet module on Arduino Nano
I'm working on Arduino Nano and I have to use both the Bluetooth LE module Adafruit nRF8001 and ENC28J60 Ethernet module using Ethercard
The idea of the project is to receive data from smartphone via BLE and send it via Ethernet to check with server if the data is valid then the Arduino will send an ON signal out of digital pin 4
But the problem is when uart.begin() (BLE) command invoked. I can no longer use the Ethernet module anymore.
I tried remove the uart.begin() part and Ethernet works fine.
I tried swap uart.begin() to run before ether.begin(). Ethernet cannot be initialized anymore.
Either way, the BLE module seems to work fine and the Arduino can respond to messages from smartphone. But sometimes it returns error code which I cannot understand. And after I pressed reset button on the Arduino it begins to work again.
ACI Command 40
Evt Cmd respone: Error. Arduino is in an while(1); loop

This version doesn't include the data verification part yet. Only send open from smartphone to trigger the Ethernet request and the server will always return you-are-good
Here is my sketch
//BLUETOOTH
#include <SPI.h>
#include "Adafruit_BLE_UART.h"

#define ADAFRUITBLE_REQ 8
#define ADAFRUITBLE_RDY 2
#define ADAFRUITBLE_RST 9

Adafruit_BLE_UART uart = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);
static bool isBTConnected = false;

//ETHERNET
#include <EtherCard.h>
#define ETH_CS 10
#define FORCE_STATIC_IP true

static const byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 };
byte Ethernet::buffer[140];
const char website[] PROGMEM = "192.168.1.104";
const char website_path[] PROGMEM = "/check";

//TIMER AND OUTPUT
#define OUTPUT_PIN 4
#define OUTPUT_ON  LOW
#define OUTPUT_OFF HIGH

static uint32_t timer;
static const uint16_t interval PROGMEM = 5000; // 5 seconds
static bool isOn = false;

//ETHERNET
static void ethCallback (byte status, word off, word len) {
  Serial.println(F(">>> Response"));

  Ethernet::buffer[len + off] = 0;
  Serial.print((const char*) Ethernet::buffer + off);
  Serial.println(F("..."));
  checkPermission(len + off);
}

// check if the server returns exactly string "you-are-good"
void checkPermission (word len) {
  byte c;
  uint16_t i = 0;
  uint8_t found = 0;

  const byte target[] PROGMEM = "you-are-good";
  const uint8_t targetlen PROGMEM = 12;

  do {
    c = Ethernet::buffer[i];

    if (c == target[found]) {
      if (++found >= targetlen) {
        Serial.println(F("OK"));
        outputON();
        return;
      }
    } else {
      found = 0;
    }
  } while (i++ <= len);

  Serial.println(F("NOT OK"));
  outputOFF();
}

void sendRequest() {
  Serial.println();
  Serial.println("<<< REQ ");

  char params[64];
  String prm = "?p=PARAMS_HERE";
  prm.toCharArray(params, 64);

  ether.browseUrl(website_path, params, website, ethCallback);
}

void initEthernet () {
  Serial.print(F("ETH:"));
  if (ether.begin(sizeof Ethernet::buffer, mymac, ETH_CS) == 0)
    Serial.println(F("Failed"));
  else
    Serial.println(F("OK"));

  Serial.print(F("DHCP:"));
  if (FORCE_STATIC_IP || !ether.dhcpSetup()) {
    Serial.println(F("Failed\r\nStatic: "));

    byte ip[] = {192, 168, 1, 12};
    byte gw[] = {192, 168, 1, 1};
    byte dn[] = {192, 168, 1, 1};
    byte ms[] = {255, 255, 255, 0};
    ether.staticSetup(ip, gw, dn, ms);
  } else {
    Serial.println(F("OK"));
  }

  ether.printIp(F("IP:  "), ether.myip);
  ether.printIp(F("GW:  "), ether.gwip);
  ether.printIp(F("DNS: "), ether.dnsip);

  if (!ether.dnsLookup(website)) {
    Serial.println(F("Lookup failed"));
    while (1) {
      digitalWrite(OUTPUT_PIN, HIGH);
      delay(500);
      digitalWrite(OUTPUT_PIN, LOW);
      delay(500);
    }
  }

  ether.printIp(F("SRV: "), ether.hisip);
}

//BLUETOOTH
void initBluetooth () {
  uart.setRXcallback(rxCallback);
  uart.setACIcallback(aciCallback);
  uart.setDeviceName(PSTR("BLEUART")); /* 7 characters max! */
  Serial.print(F("BT:"));
  if (uart.begin())
    Serial.println(F("OK"));
  else
    Serial.println(F("FAILED"));
}

void aciCallback(aci_evt_opcode_t event) {
  switch (event)
  {
    case ACI_EVT_DEVICE_STARTED:
      Serial.println(F("Advertising started"));
      break;
    case ACI_EVT_CONNECTED:
      isBTConnected = true;
      Serial.println(F("Connected!"));
      break;
    case ACI_EVT_DISCONNECTED:
      isBTConnected = false;
      Serial.println(F("Disconnected or advertising timed out"));
      break;
    default:
      Serial.print(F("ACI OPCODE:"));
      Serial.println(event);
      break;
  }
}

void rxCallback(uint8_t *buffer, uint8_t len) {
  uint8_t target_len = 4;
  const char* target = "open";
  uint8_t counter = 0;

  Serial.print(F("Received "));
  Serial.print(len);
  Serial.print(F(" bytes: "));
  for (int i = 0; i < len; i++) {
    char ch = (char)buffer[i];
    Serial.print(ch);
    if (ch == target[counter]) {
      counter++;
    }

    if (counter == target_len) {
      sendRequest();
    }
  }
}

//OUTPUT
void outputOFF() {
  digitalWrite(OUTPUT_PIN, LOW);
  isOn = false;

  Serial.println(F("Locked"));
}

void outputON() {
  timer = millis() + interval;
  digitalWrite(OUTPUT_PIN, HIGH);
  isOn = true;

  Serial.println(F("Unlocked"));
}

//ARDUINO
void setup () {
  pinMode(4, OUTPUT);
  Serial.begin(9600);
  Serial.println(F("BT+ETH"));

  initEthernet();
  initBluetooth();
}

void loop () {
  uart.pollACI();
  ether.packetLoop(ether.packetReceive());

  if (isOn && millis() > timer) {
    outputOFF();
  }

  // debugging commands
  if (Serial.available()) {
    char c = Serial.read();
    if (c == '0') {
      Serial.println(F("Still OK"));
    } else if (c == '1') {
      sendRequest();
    } else if (c == '2') {
      Serial.println(isBTConnected);
    }
  }
}

PS. I don't know if it has something to do with the problem. But the Arduino compiler reports that Global variables use 1,538 bytes (75%) of dynamic memory. I'm planning to get another Arduino model to make sure it works fine after I added data verification part. Don't know if it will help with the problem.

Check the amount of memory you need to run this sketch and library functions. My guess it that you are way over the budget (2K).

Are you toggling the slave select of the SPI slave you are not using LOW?

@MikaelPatel, I'm not sure how to check the memory needed to run the sketch. But my guess is same as yours.

@Avamander, I don't control the SS pin myself. I don't know if the libraries of the two slaves conflicted or not.

source: Stack Exchange

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

sort: votes


text:
Is a power off sufficient to avoid problems with the Watchdog on Arduino Mega 2560?
I'd like to offer some context about what I'd like to do because I might have misundertood something.
I'm trying to reduce power consumption on my device, an Arduino Mega 2560, and I've found this library
https://github.com/rocketscream/Low-Power
which uses the Watchdog to put Arduino on power saving for a predetermined interval of time; after that it reactivates what has been disabled and let the program continue its flow.
I searched for more information about the Watchdog and I found out several warnings about dealing with Watchdog on an Arduino Mega 2560, stating that it would only work with a modified bootloader:
This scared me a bit because I'm not very keen on risking to brick my Arduino (I absolutely need it to work on the next few days).
Now, I only have two Arduino Mega 2560 at my disposal and if I'm not mistaken, flashing the bootloader on an Arduino Mega 2560 using another Arduino Mega 2560 as a programmer can't be done because the procedure ends with errors:
( see http://forum.arduino.cc/index.php?topic=126160.0 )
Hence my most important question: if I test the watchdog functionality on my code (the sketch) and the Arduino happens to continually reset, can I fix the situation by powering off the Arduino?
(if you can help with my other issues as well, I'd be very grateful, I'm not sure I completely understood how these things work)

The problem you have is that once the watchdog is turned on it is very hard to turn it off again. There are certain procedures you have to go through to ensure it's turned off.
The default bootloader doesn't turn the bootloader off, and a reset doesn't turn it off either. The watchdog then fires whilst the bootloader is still waiting for communication from the PC thus making it reboot before your sketch has had a chance to run. Hence the change needed in the bootooader.
The only way to clear the watchdog is to remove the power. However as soon as your sketch runs and turns the watchdog back on you are then back at square one.
So you need to upload a new sketch to stop that happening, but that is tricky, since the watchdog keeps resetting and interrupting the bootloader. So what do you do? Well, there's a specific sequence you need to do.

Unplug the mega
Compile the new sketch
Hold the reset button on the mega
Plug in the mega
Press upload
As soon as avrdude starts release the reset button.

That way you have a chance of the bootloader running without your sketch having run first and enabled the watchdog. The bootloader runs just the once when the computer is tryung to upload the sketch, and with luck that will happen instead of your sketch running.

wow, that's a real gamble!
I'm not keen on taking such a risk for the moment, but I greatly appreciate your explanation, thanks!

It's not that much of a gamble - it's all a question of timing, and that just takes practice. Once you have the knack of releasing the reset button at the right time it's easy enough to replace the sketch with something that doesn't enable the watchdog. Until then, though, it may take you a few attempts to get the timing right.

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


text:
Sublime Text 2 with stino, compilation gives "filename ... is incorrect" Arduino IDE 1.7.8
I can't compile a simple blink sketch.
Error is:
[Stino - Start building "t5"...]
[  3%] Creating C:\Users\lov\AppData\Local\Temp\Stino_build\t5\t5.ino.cpp.o...
The filename, directory name, or volume label syntax is incorrect.

See also see similar question, that answer not working here.
Path to IDE app is C:\Program Files (x86)\added\Arduino.

Rename the program file to t5.cpp .

I suggest you do not install into 'C:\Program Files (x86)\added\Arduino'. Windows does some weird things with that directory, believe me. I usually put it on the desktop or somewhere I have normal write access to.

I've been working with Sublime Text 3, and trying to get it to work with Arduino IDE 1.8.1.  It has not gone well. From what I've read Stino is not compatible with the IDE beyond 1.6.2 or so, as the IDE library management was completely redone, among other things. I have just gotten that combination [Sublime 3 & IDE 1.6.2] to work ok, but still seem to have some library problems.  As for Stino, it looks like there is a new version in the works, but not complete.  More info on Github.
It you actually succeed, I would like to know about it.

Sorry but this is too big for a comment.
Firstly please can you check the obvious, in Windows Explorer paste the path C:\Users\lov\AppData\Local\Temp\Stino_build\t5 into the address bar and does the directory exist. (I have fallen for that so many times)
Secondly do you have permission to create a file there?
Have you updated the IDE? Does blink compile?
Have you tried running the IDE as admin?
Hopefully one of those will fix it.


text:
How to copy files from Yun to local computer?
I would like to copy a file that is in the root folder of my Yun, to my Macbook. They are connected with an ethernet cable and I am logged into the Yun through ssh.
The Yun's IP is 192.168.2.16 while the Mac's is 192.168.2.1.
How can I copy a file from the Yun?
Once I tried to copy a file from the Macbook to the Yun using "scp" and it worked, but now I don't know how to do for the other direction

You simply reverse the arguments.  Whatever you used to copy a file to the Yun you just do the opposite to copy from the Yun.
For instance, if you copied to the Yun using:
scp /my/local/file root@192.168.2.16:/where/you/want/it

Then you would change it around to copy from the Yun thus:
scp root@192.168.2.16:/path/to/file /where/you/want/it/to/go


text:
ESP8266 NodeMCU v3 basic questions
Can somebody please tell me what is the operating voltage of ESP8266?
What is the A0 voltage range?
I am powering it up from USB (5v) and have a sensor that comes back with Analog value, to calculate it correctly I am asked to provide "Logical Voltage" value that is either 3300 or 5000 (3.3v or 5v). Sensor is connected to 3.3V port as there is no 5v port on the board.
What do I choose here 3300 or 5000 for NodeMCU V3?
Thank you.

The subtle clue is in the voltage that is available. That is, the only voltage provided on the board is 3.3v. That's a slight hint that the board might run at 3.3v. And you would be right in that assumption.
The ESP8266 chips, as are most modern MCUs more powerful than 8-bit, 3.3v devices.
So you would choose 3300 as your "Logical Voltage" value.  Or better still, measure the 3.3V and find exactly what it is and use that value x 1000 (for example 3317 or 3295).

Thank you @Majenko, this was really helpfull. Do you know by a chance what is the Range of voltage that this board can take on AD0?

0v to 3.3v since 3.3v is the supply voltage.

Thank you very much Majenko! You saved my project with this :)


text:
How to use ITG-3500 evb

I am trying to make motion capture and someone gave me these boards.
I think it's a test board for MPU 9500. I tried to google but I only found datasheets. What boards are these?
"ITG-3500 evb" is written on the back of the green board.
I think this is datasheet of green board maybe
"EV_ARM_XXAXA_D" is written on the back of the blue board.

You mentioned that you found some datasheets - could you edit your answer to include the links, please?

I have had to, briefly, play with these boards a while back, and although I used different revisions and versions of the boards, they are probably the same functionally. Unfortunately, I don't have any of my old notes as I have moved country. Regardless...
As Majenko says in his answer the green board is an evaluation board for the ITG-3500 3-axis gyroscope, which is presumably the SMD chip (in a QFN format) mounted on it, in the lower part of the board (looking at your photo). A data sheet on the similar ITG-3200 (note not the evaluation board itself)  can be found on SparkFun. To quote part of the product description:

The ITG-3200 is the world’s first single-chip, digital-output, 3-axis
MEMS gyro IC optimized for gaming, 3D mice, and 3D remote control
applications. The part features enhanced bias and sensitivity
temperature stability, reducing the need for user calibration. Low
frequency noise is lower than previous generation devices, simplifying
application development and making for more-responsive remote
controls.
The ITG-3200 features three 16-bit analog-to-digital
converters (ADCs) for digitizing the gyro outputs, a user-selectable
internal low-pass filter bandwidth, and a Fast-Mode I2C (400kHz)
interface. Additional features include an embedded temperature sensor
and a 2% accurate internal oscillator. This breakthrough in gyroscope
technology provides a dramatic 67% package size reduction, delivers a
50% power reduction, and has inherent cost advantages compared to
competing multi-chip gyro solutions.

In addition, in case it is of any use, here is the datasheet for the, again similar, ITG-3701, which I located on the Digi sales site. Frustratingly, I am unable to locate a datasheet for the ITG-3500 - however, you mentioned that you found some datasheets - could you edit your answer to include the links, please?
The Blue board is a "Gyroscope Evaluation Board: EV_INV-ARM" manufactured by InvenSense Inc., and to quote its product description:

The InvenSense ARM reference board provides a bridge function between InvenSense evaluation boards and a PC. It connects to a PC via USB and to InvenSense evaluation boards via SPI or I2C. The ARM processor on the reference board is not meant to be reprogrammed by the user. It contains all code necessary to be used in conjunction InvenSense evaluation boards. (Note that separate demonstration software may accompany the individual evaluation boards with which this device connects.)

Here is a link to the EV_INV-ARM DataSheet. The Atmel chip on it is possibly the AT91SAM7SE512 MCU, and here is a link to its product specification.
Software wise, you may find this Linux kernel driver for the ITG-3500 extremely useful.

TL;DR
It seems like you need to get hold of the separate demonstration software for the ITG-3500 evaluation board, according to the EV-INV_ARM's product description, in order to easily make it do something.

i edit it
I'm not sure that is correct datasheet. but picture of board is same

i read both of data sheet. but i can't understand the EV_INV-ARM.
In datasheet it mentioned reference board is not meant to be reprogrammed by user.
then this board is just used as connect gyrscope board(ITG-3500) with pc?

@jen6 that is what I understood as well. It is purely a communication medium to use with the evb

The green board is an ITG-3500 (3 axis gyroscope) evaluation board of some form.
The blue board is some form of microcontroller evaluation board. It probably has one of the Atmel SAM chips on it since it mentions ARM.
That's about all you'll get from us I'm afraid, unless there is the highly unlikely situation that someone here happens to have the exact same boards as you.

can i upload program at blue board like atmega128?

I would imagine so, otherwise it would be useless. The real question is how do you do that. There appears to be a JTAG connection that could be used, but that is all I can tell you. Read what the chip is (it has numbers and letters on it), find a compatible JTAG programmer, and the right software, and you're half way there.


text:
Can I power a 9g servo from an arduino nano with USB power only?
I want to run a 9g servo off of the pins from an arduino nano board, using only the 5v USB connection.
The servo specifically is a SG90, which I have measured a stall current of ~250mA - I don't intend to stall it, just have it run with almost no load
I am not sure which pins to power it off of from the arduino itself - do I use the VCC or the +5v? does it matter which ground I use? should I use a breadboard to help me place any other components that may be needed, i.e. a capacitor or something? does the arduino nano negotiate to get more than the default of 100mA from a USB power connection?

The max current of the Arduino-Nano 5V Pin is 200mA. So if you draw more than that it might damage your Arduino.
Here is an interesting summary regarding the Maximum Ratings of the Arduino Nano: https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins

The 5V pin of the arduino is not connected through the
  microcontroller. As such, it can source significantly more power. When
  you are powering your arduino from USB, the USB interface limits your
  total power consumption to 500 mA.

So yes, it actually seems you can draw 250mA out of the 5V PIN.

do I use the VCC or the +5v?

You use +5V, because VCC is for powering your Arduino with an external Power Source. It allows you to use up to 7-12V (recommended), or up to 6-20V (limits).

does it matter which ground I use?

Doesn't matter

should I use a breadboard to help me place any other components that may be needed, i.e. a capacitor or something?

A breadboard makes it easier for you, to test your circuit. But you can do it without if you like. Then you possibly have to solder some connections
See also the offical Arduino Page for the Nano.

Thanks - might I ask a few more details - does the arduino negotiate for more than 100mA with the computer when connected to one, and also what would happen if more than 200mA are drawn - would it just lower the voltage and become temporarily unstable, or would something overheat? (does it even go through anything, or is it directly connected to the USB port?) - the breadboard was for if any extra components would be helpful, i.e. a capacitor or diode or something to keep the signal "clean" for the arduino

Isn't the 200mA limit only for when the board is power via VIN and not USB?

@Gerben Thank you. I researched it and you're right. Actually the USB-current-limit is much higher then 200mA. I have updated my answer. Source http://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins


text:
CLion + Arduino
Please, help me to set up Clion + Arduino.
Clion has an Arduino plugin which I've installed. Here is some instruction on Github but I'm fully noob about cmake and other things which are talking about in instruction. I have only used Arduino IDE before for my simple projects. Now in CLion I can create an Arduino projects but autocompletion doesn't work. Actually it works but does it on true C, not for Arduino code.
So if you can please explain like for complete idiot, what I should change to get working Arduino autocompletion.

What do you mean by Arduino autocompletion?

look here

It can't autocomplete what it doesn't know about. Have you installed all the libraries correctly according to what the plug in requires? (Try to compile the Blink example included with the Arduino IDE, do you get any errors?)

If u explain how to do, I will do it.

For anyone reading this now, Jetbrains has a very detailed blogpost on how to do this

Rather than using any plugin, I am using CLion with PlatformIO, which supports several IDEs. CLion then not only gives you code completion, but also full support for refactoring, Git, and much much more.
From its documentation:

[...] generate project via platformio init --ide command:
platformio init --ide clion --board %TYPE%

# For example, generate project for Arduino UNO
platformio init --ide clion --board uno

Then import the project in CLion and you're about done.
Some hints:

Make sure your code is in the src folder, and that the main file has a .cpp extension.

For other files: either rename all .ino files to use .cpp, or tell CLion to associate the .ino extension with C++ files. (Preferences, Editors, File Types.)

Whenever adding libraries to the lib folder (and using #include to refer to them), just run the above init command again.

If you're using ESP-boards and changed platform.txt for an alternative esptool, then note that PlatformIO needs a different hack.

Rather than using the CLion Serial Monitor plugin, I simply use a Terminal within CLion to upload and start the monitor as soon as possible:
pio run -t upload; pio device monitor -b 115200

If you always want to upload and monitor whenever using pio run, then add:
[env]
targets = upload, monitor
upload_protocol = esptool
upload_speed = 115200
monitor_speed = 115200

Nowadays, CLion has a PlatformIO plugin as well, including a menu Tools, PlatformIO with commands such as Re-init.

thanks for your informative answer. it helped me quite a bit. just one thing: could you further elaborate on the last bullet point? how do you open custom terminals? does that command work on all platforms or just linux? thanks in advance

@Neuron, in CLion on a Mac it's menu View, Tool Windows, Terminal. (On a Mac, the built-in bash shell is also called Terminal.) But there's no real difference with using a standalone terminal window, except for having all in one place, and it conveniently defaulting to the project's folder. As for the pio command: I only used it on a Mac, and it's exactly the same as platformio. (Both are installed when installing PlatformIO.)

you opened a whole new world to me! thanks ^_^

Thanks a lot, uploading code works for me! But not serilaports, it says:
> pio serialports monitor -b 115200
Error: No such command "serialports"

Okey, it is platformio device monitor now

But CLion don't see dependencies which I add with pio lib install --save {lib_name} Any ideas how to fix that?

@invis, doesn't the 3rd bullet point work for you?

@Arjan hmm, actually pio init with argumets helps. My lib directory is empty, thats why I was confused. pio adds dependencies to his own directory named .pio/libdeps

I know this was asked a long time ago, but maybe it will be useful for someone. I'm a beginner, regarding all this stuff, so if anybody knows a better way to do it, please correct me. here is how I set up CLion for Arduino (on Windows 10):
CLion 2016.1.3 + Arduino 1.6.9 + plugin

Download and install the official Arduino IDE (1.6.9).
Download and install MinGW to 'C:\MinGW'
In MinGW, install: 'mingw32-base' and 'mingw32-gcc-g++'
Download and install CLion.
Create an 'untitled' project, just to open CLion.
In CLion > Settings > Plugins > Browse Repositories > Search for and install: 'Arduino' (tools integration), and 'Serial Monitor' (misc).
In CLion > Settings > Search > type 'MinGW'
At the environment select 'Use MinGW home', and browse to MinGW folder ('C:\MinGW'). Press apply, and wait until CLion finds the environment.
In File > Close project.
Open any file manager and go to 'c:\Users\name\ClionProjects\' and delete the 'untitled' project you just created.
Open CLion, select 'New Arduino sketch project'
In the project directory > 'open cmakelists.txt' and configure lines:
6: set board version
7: set port (you can find out port# from the Arduino IDE)
8: set the path where you installed your Arduino libraries (Arduino sketch folder)

set(${CMAKE_PROJECT_NAME}_BOARD uno)
set(${CMAKE_PROJECT_NAME}_PORT COM3)
LINK_DIRECTORIES(c:\\ARDUINO\\libraries)

In the upper right corner in CLion, near the green 'Play' button, select 'Edit Configuration', on the left select 'Application' > 'Upload', and set:
-target: 'upload'
-configuration: 'debug'
-executable: the project name

then press ok.
In the project .ino file, write some really simple code (blink).
Connect an Arduino Uno via USB, and press the green 'play' button to upload the sketch.
To start serial monitor:

In CLion main window bottom left, click serial monitor tab (in 'the tool buttons')
Click the wrench icon to set up port and baud rate.
On the top of the wrench icon, click the blue 'connect' icon.
If values did not appear 'correctly', click the white 'switch to hex' icon (on the right of the wrench).
Before uploading sketch, disconnect the serial monitor.

For CLion to properly find the libraries, make sure to use the same name for the lib folder as for the '.h' file. example: for DallasTemperature.h use folder name DallasTemperature. After #inlcude-ing new libs, right click on 'External libraries folder' and select 'Reload cmake project'.
You may want to do further configuration in CLion settings like: theme, colours, text size, etc.
Also, you can configure some handy 'live templates', like: serialprintln, digitalwrite, pinmode, switch, etc. to enhance your productivity.

Its very nice tutorial dude, thx very much but unfortunately Im using linux (. Instead of mingw what should I install?

sorry, i don't use linux, have no idea about it.

@Kvach you will need to install cmake, gcc, git.

Thank you! This is the best way to do it for windows

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


text:
For loop question-Simulating a robot' s movement on a 2d array
i' m trying to simulate a robot' s movement on a 2d array. In my case, robot goes forward firstly, if it sees a engel, it turns left and continues its movement. The problem is that, i could not present turning left and moving on left-direction on the initial matrix.
Here' s my code:
#include <Servo.h>
#define x 7                                         //Matrix dimensions
#define y 7

const int trigPin = 12;
const int echoPin = 11;

Servo myServo;                                     //variable definations
Servo myServo2;

int pos = 0;

int counter;
int counter1 = 0;
int counter2;
int counter3;

int integer;
int integer2;
int integer4;

long duration;
long distance;

void setup() {
    Serial.begin(9600);
    myServo.attach(9);
    myServo2.attach(10);
    pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

void loop() {
    int my2dArray[x][y] = {                          // initial matrix
        {1, 1, 1, 1, 1, 1, 1},
        {1, 1, 1, 1, 1, 1, 1},
        {1, 1, 1, 1, 1, 1, 1},
        {1, 1, 1, 0, 1, 1, 1},
        {1, 1, 1, 1, 1, 1, 1},
        {1, 1, 1, 1, 1, 1, 1},
        {1, 1, 1, 1, 1, 1, 1},
    };
    // Clears the trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
// Calculating the distance
    distance = duration * 0.034 / 2;
    int robot = my2dArray[3][3];                   // first place of robot

    if (counter1 > 0) {
        for (integer = 0;  integer < counter1; integer += 1) {
            if (distance < 10) {                                  //seeing     the object
                for (pos = 0; pos <= 180 ; pos += 1) {              //turning left
                    myServo.write(pos);
                }

                for (pos = 0; pos <= 180  ; pos += 1) {            //moving on after turning
                    myServo.write(pos);
                    myServo2.write(pos);

                    if (pos == 180) {
                        counter3 +=  1;
                    }
                }

                Serial.println(integer);

                for (integer4 = 0;  integer4 < counter3; integer4 += 1) {     //modifying matrix if there is an object
                    my2dArray[3 + integer][3 + integer4] = robot * my2dArray[3 + integer][3 + integer4];
                }

                Serial.println("Break condition.");
                break;
            } else {
                my2dArray[3 + integer][3] = robot * my2dArray[3 + integer][3];    //modifying matrix in case of there is no object
            }
        }
    }

    for (integer2 = 0; integer2 < 7; integer2++) {                          //displaying matrix
        Serial.print(my2dArray[integer2][0]);
        Serial.print("|");
        Serial.print(my2dArray[integer2][1]);
        Serial.print("|");
        Serial.print(my2dArray[integer2][2]);
        Serial.print("|");
        Serial.print(my2dArray[integer2][3]);
        Serial.print("|");
        Serial.print(my2dArray[integer2][4]);
        Serial.print("|");
        Serial.print(my2dArray[integer2][5]);
        Serial.print("|");
        Serial.println(my2dArray[integer2][6]);
    }

    Serial.println();

    for (pos = 0; pos <= 180  ; pos += 1) {                               // moving forward as first movement
        myServo.write(pos);
        myServo2.write(pos);

        if (pos == 180) {
            counter1 +=  1;
        }
    }

    delay(1000);
}

The problem part is:
for (integer4 = 0;  integer4 < counter3; integer4 += 1){      //modifying matrix if there is an object

    my2dArray[3 + integer][3+integer4] = robot * my2dArray[3 + integer][3+integer4];

     }

"integer" value does not change in the problem part, it' s always 0 in despite of the first for loop. How can i pass the "integer" to the problem part properly?

Those variable names are really confusing. You really should name them after what they represent, not the data type that is in them.

Also you really should learn to format your code properly. It makes it so much easier to follow. I have done it for you this time, but you really do need to learn about proper indenting.

Your program is hard to follow with all those meaningless "integer" and "counter" variables, and the logic seems a little odd in places, but I believe the cause of your problems is the break statement:
for (integer = 0; integer < counter1; integer += 1) {
    if (distance < 10) {
        // ...
        for (integer4 = 0;  integer4 < counter3; integer4 += 1) {     //modifying matrix if there is an object
            my2dArray[3 + integer][3 + integer4] = robot * my2dArray[3 + integer][3 + integer4];
        }
        break; // << HERE
    } else {
        // ...
    }
}

What is the purpose of that break? I think you are using it to jump out of the if so that it doesn't run the else, which it won't run anyway since it's an else condition. Instead, what the break is actually doing is terminating the for loop after the first iteration that hits that inner if condition. That is, as long as the distance is less than 10 it will only ever run the for once, and so integer will only ever be 0.


text:
Arduino on breadboard Tension is 4.4V instead of 5 V,looking for some guidance
I build a circuit that work on breadboard now i try to prototype it,so i start solder it on a prototype board and the arduino is out of sync.So i check the tension and for some reason it's 4.4~4.6 on the Vin pin of Atmega328 so i try to find how to debug.I don't have a lot of theorical knowledge on electronic,but my thougt was as long as everything is plug in parrallel the tension should remain the same ( and i don't have any thing in serie) so for the tension to drop i may have something acting as Resistor, and i try to find how and what.
I use 22AWG 0.7mm wire o create a 5V line and my GND line on each side of the Atmega ( roughly 7 cm on each side),i start to wondering if it was not a bad idea. I have picture of my prototype bellow,but it's messy so not sure it help. My question is how to you proceed to troubleshoot this thing ? What are the step you do to find out where is the problem

Please edit your question and add a schematic diagram and a picture of the other side of the board.  Also say what your power supply is and if there is a voltage regulator on the board.  If your power supply puts out  4.4 to 4.6 V then it's ok for the "5V" line to measure  4.4 to 4.6 V.

Hi thanks,My input is 5V ( i measure it and it's from a generator ). The other side look like that frontside , i am drawing the schematic.

It's quite hard to see because a lot is in shadow. It sounds like, though, that you have shorted 5V to Gnd. Try doing a continuity test with a meter.

The yellow-boxed 5V and Gnd buses on the freetronics.com.au ProtoShield Basic for Arduino [like you used] already have copper strips connecting the holes.  The strips run on both sides of the board and the holes are plated-through, so there's no need (for this kind of circuit) to have additional bus wire running along above the boxes.  Having that extra wire there gets in the way of making changes, whether for debugging the circuit or for adding or replacing components.
From the frontside picture, it appears you may have a voltage regulator on board.  (However, I don't see the connections to 5V and Gnd, so might be misinterpreting things.)
If your board input is 5 VDC from an external supply, feeding that 5 V into a regulator will lose half a volt or so, which may account for what you are seeing.
However, let's instead suppose you are putting 7 to 12 VDC into an on-board 5V regulator and then measuring 4.4-4.6 V out.  One possibility is the regulator isn't working.  This can happen if the regulator's input or output capacitors are the wrong sizes or wrong kinds, and cause oscillation.  Diagnosing that kind of problem is straightforward if you look at the 5V line with an oscilloscope.  Another possibility is something drawing a lot of current (eg a couple of amps) and taking the 5V line out of regulation.  That's usually easy to diagnose because of all the resulting smoke and heat.
Drawing a good schematic is an excellent step to take to allow better problem debugging.
Other steps to take:

Measure the amount of current the whole board is drawing, or that the NRF24L01 is drawing.  (For the latter measurement, you might need to lift your ground lead off the NRF24L01 board and put the ammeter into the ground circuit.  In general you want all the grounds to be at the same voltage, so the voltage drop across the ammeter is a problem, but not much of one.)
Pull the '328P chip and see if that makes any difference.  In general, it's a good idea to work out a prototype board's power supply problems – such as shorts, reversed electrolytics, incorrect resistors – in advance of installing a microcontroller chip onto the board.
Remove the NRF24L01, if feasible, while debugging the power supply.  If you can't easily remove it, check your schematic and see if all of its pins except 5V and Gnd are open when the '328P chip is pulled.  If so, you can detach the NRF24L01  ground lead to take it out of the circuit.  If, during testing, you unsolder and remove the NRF24L01 board, consider making a socket for it from two 5-pin female header strips.

Thanks a lot ! I am looking at that ( i am trying to finnish my schematic,but my kicad skill are not the best). The onboard regulator is too convert 5V to 3.3V for my NRF24 and RFID-RC522.
Vincent

This is my schematic link . Btw does is a good way to post my kicad file on this forum ?


text:
millis() not working properly
I'm doing a little project that, on a press of a button, will light up three LEDs and then will turn off the LEDs in different times. I'm using the millis() function to control the time that each LED will be on.
On the first time that I press the button, everything works fine. But the problem starts when I press the button for the second time.
If I press the button soon after the loop ends, something goes wrong and the behavior of the LED become a mess (just one or two LEDs light up in weird times). But, if I wait about 2 seconds before pressing the button for the second time, everything goes right.
Here's my code:
const int ledPin1 =  11;
  const int ledPin2 =  12;
  const int ledPin3 =  13;
  const int buttonPin = 2;

  int buttonState = 0;
  long previousMillis1 = 0;
  long previousMillis2 = 0;
  long previousMillis3 = 0;

  int state = 0;

  void setup()
  {
    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
    pinMode(buttonPin, INPUT);

    Serial.begin(9600);
  }

  void loop()
  {

       buttonState = digitalRead(buttonPin);

       if (buttonState == HIGH) {
        state = 1;
       }

       if (state == 1)
       {
        taskExecute(3000, 2000, 4000);
       }
  }

  void taskExecute(int tMotor1, int tMotor2, int tMotor3)
  {

    int ledState1 = HIGH;
    int ledState2 = HIGH;
    int ledState3 = HIGH;

    digitalWrite(ledPin1, ledState1);
    digitalWrite(ledPin2, ledState2);
    digitalWrite(ledPin3, ledState3);

    do
    {
      unsigned long currentMillis = millis();

      if(currentMillis - previousMillis1 > tMotor1)
      {
        previousMillis1 = currentMillis;

        if (ledState1 == HIGH)
          ledState1 = LOW;

        digitalWrite(ledPin1, ledState1);
      }

      if(currentMillis - previousMillis2 > tMotor2)
      {
        previousMillis2 = currentMillis;

        if (ledState2 == HIGH)
          ledState2 = LOW;

        digitalWrite(ledPin2, ledState2);
      }

      if(currentMillis - previousMillis3 > tMotor3)
      {
        previousMillis3 = currentMillis;

        if (ledState3 == HIGH)
          ledState3 = LOW;

        digitalWrite(ledPin3, ledState3);
      }
    } while (ledState1 == HIGH || ledState2 == HIGH || ledState3 == HIGH);
    state = 0;
  }

Other strange thing that happens is that sometimes the time that i've been set in millis for the led get on become a little different. Example: when I press the button, the LED 1 needs to light up for 3 seconds, but he lights up just 2.5 seconds.
What i'm doing wrong? Thanks!!

The variables previousMillis (1-3) are not properly initialised.  So if you wait a while before pressing the button, that delay time becomes part of the time that the LED is illuminated for.
If your taskExecute() function sets them before the loop, this will fix that:
void taskExecute(int tMotor1, int tMotor2, int tMotor3)
{
    int ledState1 = HIGH;
    int ledState2 = HIGH;
    int ledState3 = HIGH;

    digitalWrite(ledPin1, ledState1);
    digitalWrite(ledPin2, ledState2);
    digitalWrite(ledPin3, ledState3);

    unsigned long time_now = millis();
    previousMillis1 = time_now;
    previousMillis2 = time_now;
    previousMillis3 = time_now;

    do
    {
        ...
    } while (ledState1 == HIGH || ledState2 == HIGH || ledState3 == HIGH);
    state = 0;
}

On a coding-style note - I did not initially see the resetting of the global variable state=0 at the end of the taskExecute() function.  It might be better to move this up to underneath the initial call to taskExecute() so all the state handling is in one place.

Perfect!!! The problem has gone! Thank you so much for the help! :)


text:
Two MPU 9250 connected to one arduino (Code of the MPU6050 edited for MPU9250)
I have done a lot of tries to make my two IMU work with my arduino. I'm also done with many research about it and I found this code:
 // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class
 // 10/7/2011 by Jeff Rowberg <jeff@rowberg.net>
 // Updates should (hopefully) always be available at
 //https://github.com/jrowberg/i2cdevlib
 //
// Changelog:
//     2011-10-07 - initial release

/* ============================================
 I2Cdev device library code is placed under the MIT license
 Copyright (c) 2011 Jeff Rowberg

 // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE   implementation
 // is used in I2Cdev.h
 #include "Wire.h"

 // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
 #include "I2Cdev.h"
 #include "MPU6050.h"

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68; (default for InvenSense evaluation board)
//AD0 high = 0x69;
MPU6050 accelgyro;
// accelgyroIC1.initialize();
//accelgyroIC2.initialize();
MPU6050 accelgyroIC1(0x69);
MPU6050 accelgyroIC2(0x68);

int16_t ax1, ay1, az1;
int16_t gx1, gy1, gz1;

int16_t ax2, ay2, az2;
int16_t gx2, gy2, gz2;

#define LED_PIN 13
bool blinkState = false;

void setup() {
// join I2C bus (I2Cdev library doesn't do this automatically)
Wire.begin();

// initialize serial communication
// (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
// it's really up to you depending on your project)
Serial.begin(38400);

// initialize device
Serial.println("Initializing I2C devices...");
//accelgyro.initialize();
accelgyroIC1.initialize();
accelgyroIC2.initialize();

// verify connection
Serial.println("Testing device connections...");
Serial.println(accelgyroIC1.testConnection() ? "MPU6050 #1 connection successful" : "MPU6050 connection failed");
Serial.println(accelgyroIC2.testConnection() ? "MPU6050 #2 connection successful" : "MPU6050 connection failed");

// configure Arduino LED for
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
// read raw accel/gyro measurements from device
accelgyroIC1.getMotion6(&ax1, &ay1, &az1, &gx1, &gy1, &gz1);
accelgyroIC2.getMotion6(&ax2, &ay2, &az2, &gx2, &gy2, &gz2);

// these methods (and a few others) are also available
//accelgyro.getAcceleration(&ax, &ay, &az);
//accelgyro.getRotation(&gx, &gy, &gz);

// display tab-separated accel/gyro x/y/z values
Serial.println("MPU1:");      Serial.print("\t"    );     Serial.print("\t"      );
Serial.print(ax1);        Serial.print("\t"    );  Serial.print("\t"    );
Serial.print(ay1);        Serial.print("\t"    );  Serial.print("\t"    );
Serial.print(az1);        Serial.print("\t"    );  Serial.print("\t"    );
Serial.print(gx1);        Serial.print("\t"    );  Serial.print("\t"    );
Serial.print(gy1);        Serial.print("\t"    );  Serial.print("\t"    );
Serial.println(gz1);
delay(1000);

// display tab-separated accel/gyro x/y/z values
Serial.println("MPU2:");     Serial.print("\t"    );     Serial.print("\t"    );
Serial.print(ax2);       Serial.print("\t"    );   Serial.print("\t"    );
Serial.print(ay2);       Serial.print("\t"    );   Serial.print("\t"    );
Serial.print(az2);       Serial.print("\t"    );   Serial.print("\t"    );
Serial.print(gx2);       Serial.print("\t"    );   Serial.print("\t"    );
Serial.print(gy2);       Serial.print("\t"    );   Serial.print("\t"    );
Serial.println(gz2);
delay(1000);

// blink LED to indicate activity
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
}

After running it, I'm wondering why the two MPU connections failed. Please see the attached image for the result I got.
And I guess that should be the probable reason why everytime I try to move the MPU1, the MPU2 varies like what is happening to the MPU1, and there are times that they get the same value.
I also even tried to edit the code I posted above, and here it goes...
 #include <MPU9250.h>

 // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class
 // 10/7/2011 by Jeff Rowberg <jeff@rowberg.net>
 // Updates should (hopefully) always be available at
 //https://github.com/jrowberg/i2cdevlib
 //
 // Changelog:
 //     2011-10-07 - initial release

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
 // is used in I2Cdev.h
 #include "Wire.h"

 // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
 // for both classes must be in the include path of your project
 #include "I2Cdev.h"
 #include "MPU6050.h"

 // class default I2C address is 0x68
 // specific I2C addresses may be passed as a parameter here
  int AD0LOW= 0x68; //(default for InvenSense evaluation board)
  int AD0HIGH= 0x69;
  //MPU9250 accelgyro;
  int accelgyroIC1 ();
  int accelgyroIC2 ();
  //MPU9250 accelgyroIC1(0x68);
  //MPU9250 accelgyroIC2(0x69);

  int16_t ax1, ay1, az1;
  int16_t gx1, gy1, gz1;
  int16_t mx1, my1, mz1;

  int16_t ax2, ay2, az2;
  int16_t gx2, gy2, gz2;
  int16_t mx2, my2, mz2;

  #define LED_PIN 13
  bool blinkState = false;

  void setup() {
   // join I2C bus (I2Cdev library doesn't do this automatically)
   Wire.begin();
   Serial.begin(38400);

  // initialize device
   Serial.println("Initializing I2C devices...");
  //accelgyro.initialize();
  int accelgyroIC1();
  int accelgyroIC2();

   // verify connection
   Serial.println("Testing device connections...");
   //    Serial.println(accelgyroIC1.testConnection() ? "MPU9250 #1     connection successful" : "MPU9250 connection failed");
   //    Serial.println(accelgyroIC2.testConnection() ? "MPU9250 #2 connection successful" : "MPU9250 connection failed");

    // configure Arduino LED for
    pinMode(LED_PIN, OUTPUT);
    }

    void loop() {
   // read raw accel/gyro measurements from device
   //    accelgyroIC1.getMotion9(&ax1, &ay1, &az1, &gx1, &gy1, &gz1);
   //  accelgyroIC2.getMotion9(&ax2, &ay2, &az2, &gx2, &gy2, &gz2);

    accelgyroIC1.getMotion9(&ax1, &ay1, &az1, &gx1, &gy1, &gz1, &mx1, &my1, &mz1);
    accelgyroIC2.getMotion9(&ax2, &ay2, &az2, &gx2, &gy2, &gz2, &mx2, &my2, &mz2);

    // these methods (and a few others) are also available
    //accelgyro.getAcceleration(&ax, &ay, &az);
    //accelgyro.getRotation(&gx, &gy, &gz);

    // display tab-separated accel/gyro x/y/z values
    /*Serial.println("MPU1:");      Serial.print("\t"    );              Serial.print("\t"    );
   Serial.print(ax1);        Serial.print("\t"    );  Serial.print("\t"    );
   Serial.print(ay1);        Serial.print("\t"    );  Serial.print("\t"    );
   Serial.print(az1);        Serial.print("\t"    );  Serial.print("\t"    );
   Serial.print(gx1);        Serial.print("\t"    );  Serial.print("\t"    );
    Serial.print(gy1);        Serial.print("\t"    );  Serial.print("\t"    );
    Serial.println(gz1);
    delay(1000);

    // display tab-separated accel/gyro x/y/z values
     Serial.println("MPU2:");     Serial.print("\t"    );     Serial.print("\t"    );
    Serial.print(ax2);       Serial.print("\t"    );   Serial.print("\t"    );
    Serial.print(ay2);       Serial.print("\t"    );   Serial.print("\t"    );
    Serial.print(az2);       Serial.print("\t"    );   Serial.print("\t"    );
    Serial.print(gx2);       Serial.print("\t"    );   Serial.print("\t"    );
    Serial.print(gy2);       Serial.print("\t"    );   Serial.print("\t"    );
    Serial.println(gz2);
    delay(1000);*/

    Serial.print("MPU1:");
    Serial.print(ax); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(ay); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(az); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(gx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(gy); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(gz); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(mx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.print(my); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
    Serial.println(mz);

     Serial.print("MPU2:");
    Serial.print(ax); Serial.print("\t");   Serial.print("\t");     Serial.print("\t");
     Serial.print(ay); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(az); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(gx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(gy); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(gz); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(mx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
     Serial.print(my); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");
      Serial.println(mz);

     // blink LED to indicate activity
     blinkState = !blinkState;
     digitalWrite(LED_PIN, blinkState);
      }

And please see the error that it displayed: (please see attached image)

With a result of: (please see image attched)
Please help me with these. I'm getting confused with my codes that I should be using and how to edit them. Please guide me on how to put connections in between them..
Thank you...
...Thom
This is the error message I copied:
Arduino: 1.6.7 (Windows 8.1), Board: "Arduino Mega ADK"

C:\Users\Jasmin.Morales\Desktop\_2MPU_Practice\_2MPU_Practice.ino: In function 'void loop()':

_2MPU_Practice:70: error: request for member 'getMotion9' in 'accelgyroIC1', which is of non-class type 'int()'

   accelgyroIC1.getMotion9(&ax1, &ay1, &az1, &gx1, &gy1, &gz1, &mx1, &my1, &mz1);

                ^

_2MPU_Practice:71: error: request for member 'getMotion9' in 'accelgyroIC2', which is of non-class type 'int()'

   accelgyroIC2.getMotion9(&ax2, &ay2, &az2, &gx2, &gy2, &gz2, &mx2, &my2, &mz2);

                ^

_2MPU_Practice:100: error: 'ax' was not declared in this scope

     Serial.print(ax); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:101: error: 'ay' was not declared in this scope

     Serial.print(ay); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:102: error: 'az' was not declared in this scope

     Serial.print(az); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:103: error: 'gx' was not declared in this scope

     Serial.print(gx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:104: error: 'gy' was not declared in this scope

     Serial.print(gy); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:105: error: 'gz' was not declared in this scope

     Serial.print(gz); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:106: error: 'mx' was not declared in this scope

     Serial.print(mx); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:107: error: 'my' was not declared in this scope

     Serial.print(my); Serial.print("\t");   Serial.print("\t");   Serial.print("\t");

                  ^

_2MPU_Practice:108: error: 'mz' was not declared in this scope

     Serial.println(mz);

                    ^

exit status 1
request for member 'getMotion9' in 'accelgyroIC1', which is of non-class type 'int()'

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

Please copy and paste errors into the post, not a screenshot of the errors. At least for the last screenshot. There is even a button: "Copy error messages".

Please see the edited version. Thanks. :)

Please edit your post and format the messages using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

Serial.print("\t");   Serial.print("\t");   Serial.print("\t"); - how about: Serial.print("\t\t\t");

What was wrong with the initial code (before the edit)? Please describe the circuit, wiring, of the two MPUs. If you set the addresses correctly?

can u please post hardware connection? did you gnd INT pin.
did u enable AD0 pin in second IMU?


text:
How to limit the number of message that an Arduino sends to a phone without terminating it
I just stayed on delay() since that is the only thing I know but the thing is delay() cannot be interrupted. What I'm trying to achieve with this code is:

When the soilSensor detects moisture it would send a text message to a number only ONCE without terminating the program even if in the next loop the soilSensor is still detecting moisture.
The soilSensor's delay is delay(60000) and we would still wait for while to finish the delay but what if in the middle of the soilSensor's delay(60000) there is a movement for just about 5 seconds? What to do so that the tiltSensor can overlap the soilSensor's delay and sends a message to a number?

I want this program to run forever. Please help me! I needed this ASAP!
#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);
int led=22;

void setup()
{
  Serial.begin(9600);
  SIM900.begin(19200);
  pinMode(led, OUTPUT);
  delay(1000);
}

void sendSMS1()
{
  SIM900.println("AT + CMGS = \"+************\"");
  delay(100);
  Serial.println("Water Detected");
  delay(100);
  SIM900.println("Water Detected");
  delay(100);
  SIM900.println((char)26);
  delay(100);
  SIM900.println();
  delay(100);
}

void sendSMS2()
{
  SIM900.println("AT + CMGS = \"+************\"");
  delay(100);
  Serial.println("Movement Detected");
  delay(100);
  SIM900.println("Movement Detected");
  delay(100);
  SIM900.println((char)26);
  delay(100);
  SIM900.println();
  delay(100);
}

void loop()
{
  int soilSensor = analogRead(A0);
  int tiltSensor = analogRead(A1);

  if(soilSensor >= 10)
  {
    digitalWrite(22, HIGH);
    Serial.println(soilSensor);
    sendSMS1();
    delay(60000);
  }
  else
  {
    digitalWrite(22, LOW);
    delay(60000);
  }

  if (tiltSensor >= 100)
  {
    digitalWrite(led, HIGH);
    Serial.println(tiltSensor);
    sendSMS2();
    delay(60000);
  }
  else
  {
    digitalWrite(led, LOW);
    Serial.println(tiltSensor);
    delay(60000);
  }
}

BlinkWithoutDelay is good reference material for solving this issue.

If you were the Arduino, how would you go about solving the problem?

You use millis() to keep track of time and also prevent blocking. Replicating your program logic:
long soil_timer = 0;
long tilt_timer = 0;
char soil_flag = 1;
char tilt_flag = 1;

void loop() {
    int soilSensor = analogRead(A0);
    int tiltSensor = analogRead(A1);

  if (soil_flag == 1) {
    if (soilSensor >= 10) {
      digitalWrite(22, HIGH);
      Serial.println(soilSensor);
      sendSMS1();
    }
   else {
      digitalWrite(22, LOW);
    }
    soil_timer = millis();
    soil_flag = 0;
  }

  if (tilt_flag == 1) {
    if (tiltSensor >= 100) {
       digitalWrite(led, HIGH);
       Serial.println(tiltSensor);
       sendSMS2();
    }
    else {
       digitalWrite(led, LOW);
       Serial.println(tiltSensor);
    }
    tilt_flag = 0;
    tilt_timer = millis();
  }
  if (millis() - soil_timer >= 60000){
     soil_flag = 1;
  }
  if (millis() - tilt_timer >= 60000){
     tilt_flag = 1;
  }
}


text:
How to change Multiple variable values through Serial Monitor
I am trying ... with minimal success to change/Check and also run voids through the serial monitor .the code i  put i am having probles is that when i am try to send a value larger than 9 the value assigns a diffrent number Ex i set to 200 but arduino sets it as 512.. i got around it deviding the value by 1.6 and got me the new number and only works upto 90 , but i am tryn to see how it should be done correctly...
const uint16_t inputLength = 512;
int ss = 0;
int bHold = 0;

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

 void loop() {
  if ( Serial.available() > 0 )
  {
    static char input[inputLength];
    static uint16_t i;
    char c = Serial.read();

    if ( c != '\r' && c != '\n' && i < inputLength - 1)
      input[i++] = c;

    else
    {
      input[i] = '\0';
      i = 0;

      uint16_t array[80];
      uint16_t j = 0;

      if ( !strncmp(input, "ss", 2) )
      {
        char* p = input + 2;
        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 10); //< changed from 16

        for ( uint8_t i = 0; i < j; i++ )
        {
          ss = array[i];
          Serial.println(ss);
        }
      }

      if ( !strncmp(input, "bHold", 5) )
      {
        char* p = input + 5;
        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 10);   //< changed from 16

        for ( uint8_t i = 0; i < j; i++ )
        {
         bHold = array[i];
        // bHold=bHold /1.6;
         Serial.println(bHold);
        }
      }

      if ( !strncmp(input, "Whos There", 10) )
      {
        Serial.print("me");
      }
      if ( !strncmp(input, "hello", 5) )
      {
        Serial.print("hi");
      }
      if ( !strncmp(input, "sa", 2) )
      {
        Serial.print("  ss= ");
        Serial.print(ss);

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

        Serial.println(" ");
        Serial.println("==============================");
      }
    }
  }
}

Thank you for any tips you can give...
EDIT: I am trying to pass a new value with command on the serial monitor "ss 500"..so that in the arsuino ss = 500. but in this case it makes it equal to 1280.
EDIT2: Chaged the strol to 10...works perfectly ...Thank you TisteAndii!!!!

What do you mean with "ss = array[i], DEC;". That is "ss=DEC" and gives the same value ss. Should be "ss = array[i]; Serial.println(ss, DEC);"

Edit the code in your post if you have made any changes to it so far.

You are setting the input string's base to 16 instead of 10 in your strtol conversions, which is why you are getting 1280 when you expect 500.

Ex i set to 200 but arduino sets it as 512 - TisteAndii is right. 0x200 is 512 in decimal.


text:
Connect function generator to Arduino
How do I connect a function generator that generates an analog signal to an Arduino Uno?
I don't know how to begin, so could you also tell me the settings for the function generator, e.g. its amplitude, frequency, etc, that won't damage my Arduino?
I plan to visualize the output on Processing.

(source: sonoma.edu)

I haven't connected it yet, am scared to break the board.

From googling i know it should be connected to pin 8 on arduino.

What do you want to achieve? Please describe the overall circuit.

From googling i know it should be connected to pin 8 on arduino. - all of the pins can take inputs. If you are trying to measure analog inputs you mean pins A0 through to A5. Do you have a specific reason for mentioning pin 8?

I have that same function generator! make sure you ground your ardunio to the FG, & output dc values not over 3.3V. you can set a dc offset to keep the wave above 0V.

Confirm with an oscilloscope
When I connect my function generator I usually always make sure that the output is in the range 0 to 5V, with my oscilloscope. The default is probably more like ±2.5V - but I don't have an Agilent so you would have to check. Press the Ampl button to check. (Mine reads 5VPP).

You can see from the above image that we indeed have (roughly) 5VPP - and that there is a -2.56V component, which will damage the Arduino, being negative.

Add an offset
So press the Offset button and add a 2.5V DC offset. Now the voltage jumps 2.5V and is between 0 and 5V:

The scope confirms that the minimum is 80mV and the maximum is 4.96V, which is in range for an Arduino pin (assuming you are running an Arduino at 5V, which is not always the case).
Now you should be safe to experiment with different frequencies and wave-forms. Just leave the Amplitude and Offset alone. :)

Extra precautions
You could feed the function generator through an input protection circuit, just in case you absent mindedly forget to carry out the appropriate steps.

The zener diode will conduct negative voltages to ground (dissipated through the 1k resistor) and will also limit positive voltages to around 5.1V.

I don't know how to begin, so could you also tell me the settings for the function generator, e.g. its amplitude, frequency, etc, that won't damage my Arduino?

That is not an Arduino question. That is a question about how to operate the function generator. Please check the users manual. You need to set the voltage output (DC + AC) so that it matches the Arduino.
An analog signal should go to an analog pin on the Arduino (not pin 8). It is also important to connect GND.
Cheers!

Using the built in USB interface would make things a lot simpler... :-)

Depends on how the OP wants to connect the function generator. My interpretation is somewhat different; Function Generator => Analog Pin (Arduino) => Processing (Serial).

Good point! :-)

Looking at the Agilent 33220A 20 MHz Waveform Generator User's Guide, I can see that the Function Generator has a USB port. If you have, or can get hold of, a USB Host shield for the Arduino, you should be able to link the two together physically. Then, using the USB Host Library for Arduino, you could get the two talking to each other.
Alternatively, if you fancy a bit more hard work, then you could get a MAX3421E, and wired it up yourself as an interface, but I wouldn't recommended it.
Note: If you have an Arduino Due (I know that you say that you have an Uno, but just in case) then you could use the USBHost library to connect the two directly, without the need for a USB Host shield.
Regarding, getting the two to talk together, that may not be exactly easy. From the manual I can see that the PC software can auto-configure the function generator, however, for receiving data it may not be so easy. You appear to have to send a GTL command to get the data sent to the USB (p251, and onwards, of the manual). Good Luck! :-)

I can see that the Function Generator has a USB port. - I think he wants to generate test signals, not control the function generator.

@NickGammon - Yes, re-reading the question, I can see that I got a little carried away! :-)

authors: Ηλεκτρολόγος Μηχανικός

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


text:
Why is there a clock in my arduino?
Of course I know it is usefull to control the time of a delay, but any other use?
With a 16Mhz clock, each line of my program will take 1/16000000 second, right?
even a very very big line will only take 1/16000000 of a second ?
With a 8MHz clock, each line will take the double of the time, right?
So the whole "main loop"  will take the double time too, right?

You are confusing between C instructions and machine (assembly) instructions. But even if you wrote directly in assembly, you could find good use of that because the program is NOT linear. I mean, interrupts, as the name suggests, interrupt the normal code flow by going at another instruction and then resuming. So maybe between one line and the next one it is forced to execute the ISR, which may be very long

If you clock your chip at eight millihertz, even the simplest line of code will take forever. I suggest you use a clock in the megahertz range (MHz).

The number of cycles needed to execute each machine instruction is stated in the Instruction Set Manual.

Damn I should go to sleep ;), edited thanks

Why is there a clock in my arduino?

Because that is how computers and microcontrollers, etc, work.

With a 16mhz clock, each line of my program will take 1/16000000 second, right?

No.

even a very very big line will only take 1/16000000 of a second ?

No.
The clock defines at what speed the machine code instructions are fetched from memory and executed. Most instructions take 1 clock cycle, but some take more.
One line of C code may be compiled into any number of assembly instructions, which then get converted into machine code (raw numbers).  That could be anywhere from 1 assembly instruction to thousands of assembly instructions, depending on what the line does.

With a 8mhz clock, each line will take the double of the time, right? So the whole "main loop" will take the double time too, right?

Every operation in the chip is governed by the clock. If the clock is half the speed the chip is running at half the speed, so every operation will take twice as long, yes.

also, interrupts.

Minor nitpick: Should be "...anywhere from 0 assembly instructions...", even without optimizer, but even more so after optimization.

Don't confuse the poor boy. He is having a hard enough time as it is.

@Majenko: the confusion is a necessity. IT is hard.

@intelfx "IT"? This is programming, not IT....

@BalinKingOfMoria: FYI. systems programming is a strict subset of IT :)

@intelfx Looked it up, you're right... Learn something new every day! Thanks :)

Not answered in @Majenko's post: Yes, with a 8MHz clock, each line will take the double of the time. Unless the line waits for something that is not clock driven - e.g. external input.
In addition to @Majenko's answer, a CPU has a clock to ensure the instructions are complete, before the next step starts. A CPU is made out of lots of transistors (I found a reference that indicated the AtMega was in the range of low millions, give-or-take an order of magnitude).
During a cycle, the electricity flows through the chip, turning transistors on/off, the results of which will turn more transistors on/off, and so forth down the line. While this is happening, some parts of the chip have a "wrong" value - you can think of this as being half-way through a calculation (you've added the one's column and the 10s column, and are about to start on the 100s column). You don't want this to affect the outside world, so (for example) your output pins are latched - held at whatever value they are - until the instruction is complete. How long it takes to complete an instruction varies, but the manufacturer works out the slowest instruction under the worst circumstances.
For the AtMega (which is the chip on the Arduino), Atmel (who designed the chip) has declared this is 1/20,000,000 of a second - this is 20MHz.
Note that not all microprocessors run all their instructions at 1 instruction per cycle - some instructions might take 1, or 2, or 10 cycles. Pipelining makes things even more complicated - a processor might do some of the work (e.g. fetch the next instruction) in one cycle, execute it in the next - but while it is executing instruction 1, it can also fetch the next instruction. To do this, it might need to take a guess at what instruction comes next (in the case of the machine-code equivalent of a "goto" - such is used for loops), and if it guesses wrong, it has to cope with that; throw away the instruction it retrieved and retrieve the next one, losing a cycle.
The Wikipedia page on instruction pipelining shows an example of a RISC chip pipelining in 5 stages - instruction fetch, instruction decode, execute, memory access, and write-back. So, you can have 5 instructions at some stage of execution, overlapping. Until the "writeback" phase, the instructions have no real effect. You can think of this as an assembly line - it takes 7 minutes to put a widget together, but it can be broken down into 5 stages, the longest stage taking 2 minutes. Once every two minutes, each partly completed widget is moved by the assembly line to the next station. You get one widget out every two minutes - The "clock" can only tick as fast as the slowest step. If you push the widget out any faster, the "bottleneck" will get more and more widgets queued up.

The AVR has a very shallow pipeline: only fetch and execute. Then, conditional jumps take either one cycle (jump not taken) or two cycles (jump taken).

Additional complication: cache misses.

There are many things I did not mention: cache (of any type), multi-threading, multi-core... I probably went into too much depth in my post already.


text:
How to get the MAC address of an Ethernet shield, if it is not printed on it?
Help me to find out how to connect an Ethernet shield over the internet using a LAN cable. I have tried many times but I'm not getting a MAC and IP address.

The MAC address is written to the Ethernet Controller.  The IP address can be given by DHCP or static in which it is also written to the Controller.

Have you read "Getting Started with the Arduino Ethernet Shield" and the "Arduino Ethernet+SD" section of Lady Ada's Arduino Tutorial?

If you do not have a MAC address then you have to make one up.  There are a couple of rules and regulations about what a MAC address can be, but most of the time you can just make one up:

It must be unique on your network
There are a set of prefixes that are reserved for special purposes:

The lowest bit of the first byte must be 0
The second bit of the first byte must be 1

You can read more about it here: https://en.wikipedia.org/wiki/MAC_address
Once you have provided a MAC address and physically connected it to the network then you need an IP address and netmask.  There are two ways you can get the IP address and netmask:

Through DHCP - For example your home internet router would provide the IP address for you.
By allocating your own. This must be within the range of your network's IP addresses, typically something like 192.168.0.x where x is between 1 and 255.  The IP address must be unique on your network.

The netmask, again, can be given by DHCP, otherwise you will have to enter the netmask of your network, typically 255.255.255.0
Then to access the internet itself you need to provide (or be provided with through DHCP) the address of the internet gateway and possibly a DNS server address. On a home network they are typically the address of the router, which may well be 192.168.0.1 or something similar.

Specifically, it is setting the second lowest bit of the highest octet to 1 which indicates a locally administered or "made it up yourself" address.


text:
esp8266-01 and arduino UNO communicating over i2c
i am not able to communicate over i2c with my esp-01 as master and UNO as slave. i get special characters sent back to esp, but my esp is sending correctly...
output on my esp-01

output on my UNO is

connections are esp-01 gpio-0 to uno A4 and gpio-2 to uno A5
is it because i am not using a level shifter or any mistake in my code..?
here is my esp master code
#include <Wire.h>
#define I2CAddressESPWifi 6
int x=32;

void setup()
{
  Serial.begin(115200);
  Wire.begin(0,2);//Change to Wire.begin() for non ESP.
}

void loop()
{
  Wire.beginTransmission(I2CAddressESPWifi);
  Wire.write(x);
  Wire.endTransmission();
  x++;
  delay(1);//Required. Not sure why!

  Wire.requestFrom(I2CAddressESPWifi,10);
  Serial.print("Request Return:[");
  while (Wire.available())
  {
    delay(100);
    char c = Wire.read();
    Serial.print(c);
  }
  Serial.println("]");
  delay(500);
}

and here is my Uno slave code
#include <Wire.h>
#define I2CAddressESPWifi 6

void setup()
{
  Serial.begin(115200);
  Wire.begin(I2CAddressESPWifi);
  Wire.onReceive(espWifiReceiveEvent);
  Wire.onRequest(espWifiRequestEvent);
}

void loop()
{
  delay(1);
}

void espWifiReceiveEvent(int count)
{
  Serial.print("Received[");
  while (Wire.available())
  {
    char c = Wire.read();
    Serial.print(c);
  }
  Serial.println("]");
}

void espWifiRequestEvent()
{
  String ts = getTime();
  Serial.print("Sending:[");
  Serial.print(ts.c_str());
  Serial.println("]");
  Wire.write(ts.c_str());
}

String getTime(){
  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;
  String ts = "U:";
  if (hr<10) ts+="0";
  ts += hr;
  ts +=":";
  if ((min%60)<10) ts+="0";
  ts += min % 60;
  ts +=":";
  if ((sec%60)<10) ts+="0";
  ts += sec % 60;
  return(ts);
}

Pullup resistors?

no... why should I ? and between what?

Try choosing an address that isn't reserved for special purposes. One that is between 8 and 119 inclusive.

I tried 15, that didn't make any difference... :(

Pullup resistors on the I2C bus (SDA, SCK) is required if not provided on the board. Check the I2C specification.

Perhaps the Serial.print()s in the slave's request event function are causing too much delay (clock stretching?). You should make the Wire.write() the second statement in that function right after the getTime call. Or you could use Wire.write("Hello") as the only statement in the function, so you can narrow down the problem.