text:
How to use Aiduino module to connect to computer network?
I have 4 usb Hard Drives and I just want to connect them to computer network directly without a traditional computer. Is there an any module with 4 usb ports and one RJ45 port. The module should able to connect drives to network as NAS (Network Area Storage) or other mounting possibility.

An Arduino is completely incapable of doing such a difficult task. It's literally impossible because the processor isn't strong enough, it has no built in network capabilities that support NAS, it has no USB software built in, and so on and so on.
But you can use a Raspberry Pi. They are cheap for their capabilities, they do require quite some programming to get it to work but there's a huge community that has guides for everything. Best of luck :)


text:
Follow up question to Calling a timer when a button is pushed
I have changed the code with some help here. There are two buttons each one is set to turn on a LED. When the LED turns on it is timed and when the time is up it turns off. The problem I am having is that only one LED can be on at a time even though I am not using the delay() and I am using millis() to keep track of time. So if I press button one the first LED will turn on. Even if I press button two at this time the second LED wont turn on until the first one turns off.
const int ledPin2 = 2;
const int ledPin3 = 3;
const int buttonPin6 = 6;
const int buttonPin7 = 7;

const unsigned long onTime = 10000;
unsigned long previousMillis = 0;

void timer() {

unsigned long previousMillis = millis();
unsigned long currentMillis = millis();
digitalWrite(ledPin2, HIGH);

while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

digitalWrite(ledPin2, LOW);
}

void timer2() {

unsigned long previousMillis = millis();
unsigned long currentMillis = millis();
digitalWrite(ledPin3, HIGH);

while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

digitalWrite(ledPin3, LOW);
}

void setup() {
Serial.begin(9600);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(buttonPin6, INPUT);
pinMode(buttonPin7, INPUT);

}

void loop() {

int buttonState2 = digitalRead(buttonPin6);
if (buttonState2 == HIGH) timer2();

int buttonState = digitalRead(buttonPin7);
if (buttonState == HIGH) timer();

}

If someone's answer is correct, you should tick their answer as correct.

As jogco says, you are (effectively) using a delay in your timer function, by doing this:
while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

What you want is to remember the time each LED was switched on, and each every time through the loop check if the required time has passed. Something like this:
const int ledPin2 = 2;
const int ledPin3 = 3;
const int buttonPin6 = 6;
const int buttonPin7 = 7;

const unsigned long onTime = 10000;
unsigned long led1_start = 0;
unsigned long led2_start = 0;
boolean led1_on = false;
boolean led2_on = false;

void timerOn(int led) {

    switch(led) {
        case 1:
            led1_start = millis();
            digitalWrite(ledPin2, HIGH);
            led1_on = true;
            break;
        case 2:
            led2_start = millis();
            digitalWrite(ledPin3, HIGH);
            led2_on = true;
            break;
    }
}

void timerOff(int led) {

    switch(led) {
        case 1:
            digitalWrite(ledPin2, LOW);
            led1_on = false;
            break;
        case 2:
            digitalWrite(ledPin3, LOW);
            led2_on = false;
            break;
    }
}

boolean checkTime(unsigned long startTime) {
      return ((startTime + onTime) >= millis());
}

void setup() {
    Serial.begin(9600);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
    pinMode(buttonPin6, INPUT);
    pinMode(buttonPin7, INPUT);
}

void loop() {

    int buttonState2 = digitalRead(buttonPin6);
    if (buttonState2 == HIGH) timerOn(2);

    int buttonState = digitalRead(buttonPin7);
    if (buttonState == HIGH) timerOn(1);

    if (led1_on) {
        if (checkTime(led1_start)) timerOff(1);
    }

    if (led2_on) {
        if (checkTime(led2_start)) timerOff(2);
    }

}

In fact I would look at arrays for the pin numbers and status/time variables, to make it more reusable...
int ledPins[2] = {2, 3};
int ledStart[2] = {0, 0};
int buttonPins[2] = {6, 7};

... and the like

I will look over this closely. I need more practice with using switch/cases and booleans. thank you.

Yes, it is because in timer() and timer2() you busy-loop with while until the condition is not met. Hence, when buttonState2 is HIGH, your code will execute timer2() until the condition of the while loop is not met. You are effectively doing a delay.

source: Stack Exchange

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

sort: votes


text:
Arduino-like ethernet only board?
I don't think USB chip is more expensive than Ethernet chip. So, I expect there should exist a board like Arduino, but where USB is removed in favour of Ethernet.
Are there such boards?

Yes, there's the Arduino Ethernet. Available from Sparkfun for example

Important to note: you need to use an FTDI serial to upload sketches. You cannot upload sketches through the Ethernet chip.

@Len Correct, this would require a bootloader with Ethernet support as mentioned by Majenko. In this context it is also worth to note that the original Arduino Ethernet is retired.

It is highly unlikely you will ever find an "Ethernet only" board. There are plenty of boards that have both Ethernet and USB, but one without USB? I doubt it.
To make an Ethernet only board you would first need to create a bootloader with built-in support for the Ethernet port as well as a way of configuring that port to suit your network. Than kind of program would be rather large and take up a fair proportion of the flash memory, leaving you with much less room for your own program.
And as you have rightly noticed, USB chips (especially the dreaded CH340G, the bane of my life) are so cheap now, so why wouldn't you include one on your board?
So you get boards with both USB and Ethernet, and you install the software (generally) through USB which doesn't need any special configuration or complex software to get it to work.
Some boards provide "OTA" (Over The Air) updates, such as the ESP8266, but these generally require the OTA software first installing via the USB (or UART) connection to allow it to communicate on your network and accept OTA firmware. Others, such as the Arduino Yun, use multiple MCUs to provide remote programming. In the case of the Yun you get a "host" microcontroller which is considerably more powerful than the AVR microcontroller that it is programming, which always strikes me as a little pointless.
So no, I doubt that anyone would ever want to make an Ethernet only board.

I don't understand, why would I need to create "bootloader" with Ethernet while I don't need with USB? What is magic difference between two jacks?

You need a bootloader whichever you use. The "magic" difference is that the USB bootloader has already been written. Also USB is much much much simpler than Ethernet. A full IP stack is large. Very large. And complex. Very complex.

What about just Ethernet, w/o IP stack?

And how is that supposed to work?

You are showing a fundamental lack of understanding of technologies and terminologies. Go look at just what Ethernet is.

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


text:
Cannot access "tools>Serial port" on Kali Linux
I just got my Arduino UNO delivered and I wanted to see if it's working properly or not.
I tried following this page to create a simple program and the program compiled successfully.
But when I tried to select the serial port on IDE, the port option was grayed out. I searched for the problem and I landed on this page. It says

Linux includes the drivers necessary to use Arduino, and no additional
  install is needed. However, permissions might need to be configured.
  For current instructions on how to set up these permissions, visit
  this page.
An alternative method is to run Arduino as root in the terminal.

But I still see the port option grayed out even as a root user. Any idea?

Have you tried following the instructions in any of the myriad of troubleshooting pages for Linux and Arduino?

@Majenko: Nope. Not yet. Any suggestion?

How about doing that thing I just asked if you had done?

Did you check if Linux created a new device in the /dev directory?  Did you perform a "tail -f" on the log file of your Linux distribution and watched the output as you plugged in your Arduino?  You didn't say which Linux you were using so we can only guess where it keeps it's log file.  BTW, you will probably have to have root permissions to look at the log file.  BTW, you can check on the permissions of new devices at the same time you are checking on what if anything gets created in the /dev directory.

@st2000 : I'm using Kali Linux and no, plugging in the Arduino doesn't create a new directory in /dev directory. I have the root permission and I tried running Arduino as a root user but the same happens. I do not see any new device/file in /dev.

Running the application with different permissions will do no good if there is not a device in /dev for the application to connect to.  Plugging in the USB device and creating a serial device in the /dev directory needs to be solved first. Kali is sort of an "attack" version of Debian (older versions were based on Ubuntu, but I'm just going to assume you have a new version of Kali).  So, if they didn't change anything the log file should be at /var/log/syslog.  You can "tail -f /var/log/syslog" and watch while you plug in your USB device and see what is happening.


text:
Sending data using Bluetooth SPP-C Module without a Breakout-Board
tl;dr
I can't send data using the raw SPP-C Bluetooth module without a breakout board.
The communication via UART works fine as I am able to issue AT commands and get proper responses.
But when connected over Bluetooth the data passed over UART does not show up on my computer while the other direction works fine.
Has anyone tried that module yet without using a breakout board?
The long story:
I started my project by using a regular HC-05 module on a breakout board. The prototype worked just fine as there are also plenty tutorials available. The drawback using that breakout module is that it works with two voltages, 5V for power and 3V3 for communication. I have also more components in my project that run best at 3V3. That is why it came to my mind to use 3V3 as the only voltage. The raw HC-05 module without breakout board is also powered with 3V3. So everything looked just perfect.
Looking at the specs to the HC-05 I noticed that there is also more on that module like SPI and USB (page 12 bottom). So I got curious and off track.
Anyway. Instead of ordering raw HC-05 modules without breakout board I ordered cheaper SPP-C modules that don't have all this fancy stuff but just UART communication.
Following the description from Martyn Currey I was quicky able to issue AT commands and receive data over bluetooth. But I am not able to send data over Bluetooth.
I am using the same setup as it is shown on page 4 in the Chinese datasheet. (no I can't read that crazy symbols but I can read and understand the images)

This is unanswerable until you clearly document in the body of the question itself what is different between the two cases.  Also consider if the computer may be paired to the unique ID of the old module and not the new, or even that the new module might be faulty.

The pairing is not an issue as I can transmit data from my computer. Just the other direction does not work (but works flawlessly with HC-05). I also considered a faulty module so I ordered a SPP-C module on a breakout board for reference. I'll post the results here.

I found a solution myself.
The modules are working as they are supposed to and are not faulty.
Also I did nothing wrong.
The Problem are my development machines. Mac mini (Late 2009) and MacBookPro (Mid 2009), both having a Broadcom 2046 Bluetooth host chip. I used those to connect via Bluetooth and open a tty session using minicom. Running macOS and using "Hardware IO Tools" to log Bluetooth packets I saw that there was clearly nothing coming in.
After that I turned over to my Windows and used Hype! Terminal. Everything worked!
Then I went to my Raspberry Pi and Linux. After pairing using bluetoothctl and issuing a few commands from Bluetooth as ttyUSB. Everything worked as well.
Then I tried BlueSPP on an Andriod phone. And again, it worked as it was supposed to.
So my conclusion is that there is some sort of incompatibility between the SPP-C module and the Broadcom 2046 host controller.


text:
WebSocket client for ArduinoHttpClient conditional if with readString() incoming data buffer
I'm having issues implementing a web socket on the Arduino/Genuino to procress a string received and do something respectively.
I'm using SimpleWebSocket example, edited for my purpose, from the ArduinoHttpClient...
don't seam to get the hangs of it. don't know what i'm doing wrong, cannot store the received string object on a string variable or use the readString() method on and if statement to compare with a string to decide what flow path to get in to
This is the code im trying:
/*
  Simple WebSocket client for ArduinoHttpClient library
  Connects to the WebSocket server, and sends a hello
  message every 5 seconds

  note: WiFi SSID and password are stored in config.h file.
  If it is not present, add a new tab, call it "config.h"
  and add the following variables:
  char ssid[] = "ssid";     //  your network SSID (name)
  char pass[] = "password"; // your network password

  created 28 Jun 2016
  by Sandeep Mistry

  this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "config.h"

char serverAddress[] = "192.168.1.140";  // server address
int port = 8000;

WiFiClient wifi;
WebSocketClient client = WebSocketClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
int count = 0;

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

  Serial.begin(9600);
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);                   // print the network name (SSID);

    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);
  }

  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
}

void loop() {
  Serial.println("starting WebSocket client");
  client.begin();

  while (client.connected()) {
    int messageSize = client.parseMessage();

    if (messageSize > 0) {
      String test = client.readString();
      Serial.println(client.readString());
      Serial.println(test);
      if (client.readString() == "off") {
        Serial.println("low");
        digitalWrite(6, LOW);
      }
      else {
        Serial.println("high");
        digitalWrite(6, HIGH);
      }
    }
  }

  Serial.println("disconnected");
}

On the example above, you can see in the void loop, after I check there's incoming data with messsageSize I store the incoming data using readString on a variable test, which I then println, this shows and empty line, although when I directly via println readString it shows some data, so the data is coming in... subsequently when I try to use the data from the incoming buffer on and if statement to compare with a string is wont work.
I've tried everything I can think off, puting the string to compare in to a variable and compare them, using Compare method from the object and I cannot even remember what else.
does anyone have any advice on how to do this, maybe the library is buggie, maybe I'm doing it wrong, any other libraries that anyone can recommend, I've looked around and this is the only one that looked simple enough to get started with and had the most examples.

this workes:
if (messageSize > 0) {
      //Serial.println(client.readString());
      String input = client.readString();
      Serial.println(input);

looks like reading from the method readString() empties the buffer hence cant use it again, what I did is store it on a String object variable "input" and use that.
It worked.


text:
do i need an I/O shield for quadcopter motors
I would like to know if I need an I/O shield for the 4 ESC's on a Quadcopter I am building using Arduino Mega2560.  The current to the ESC's should come from the battery itself and the data from the board so my first thought is that it is not needed however I wanted to be sure.

What's an I/O shield?

You really do not want to be flying a literal Arduino, especially not a mega - it just means excess weight, bulky awkward connectors, and unsuitable power circuitry.  Even the projects that were once Arduino derived have typically moved on, first to purpose-designed ATmega boards and now to ARM boards.

If the ESC accepts a signal that the Arduino can generate (i.e., 5V PWM) then no interfacing is required.
If the ESC is running from 3.7V (or similar) then some level shifting may be required to reduce the 5V signal to 3.7V, depending on the ESC. That may be built on a shield of some form or just with discrete resistors wired in manually to the leads.


text:
Arduino Driver can I use only PNP?
is it possible to use a normal PNP transistor to drive a motor?
I'm kinda new to this stuff so I want to be on the safe side, so I don't damage my Arduino Uno because of the motor.
I have made a motor driver? https://circuits.io/circuits/2493784-test-1
But I'm not sure if i have done right and I wont break any components.
So does this work without any problems and have I done it right?
I'm not trying to make a H-bridge because I need both PNP and NPN?
EDIT:Picture

That diode in the circuit is doing nothing. And it's not a good idea to put a resistor in series with a motor as the motor will draw a lot of current, thus the resistor producing heat. Get a motor that matches (by being above) the battery's voltage.

@Bradman175 Why do you think the diode is doing nothing? IMO it is absolutely vital for this circuit to protect it from overvoltage.

Look again at the way he wired it. I know diodes in reverse are used to prevent the inductance from creating too much voltage. Forgot to say that.

You can upload images as part of your post. That is preferable to including a link that some people can't open.

In addition to your circuit being seriously mixed up, you should really avoid using 9v "transistor radio" batteries for motors - they won't last long, and while they are working the motor performance will be reduced  by the internal impedance of these weak batteries.

You need an NPN transistor to run a motor like that off of an arduino. Take a look at this article: https://learn.sparkfun.com/tutorials/transistors

Similar to the NPN circuit, the base is our input, and the emitter is tied to a constant voltage. This time however, the emitter is tied high, and the load is connected to the transistor on the ground side.
This circuit works just as well as the NPN-based switch, but there’s one huge difference: to turn the load “on” the base must be low. This can cause complications, especially if the load’s high voltage (VCC in this picture) is higher than our control input’s high voltage. For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor. In that case it’d be impossible to turn the switch off because Vb would always be less than Ve.

Using an NPN transistor is the way to go here. Keep in mind that you can't control the direction of a motor with just one transistor, however.

Despite the fact that the circuit you have is completely wrong, there is one fundamental thing that is stopping you using a PNP transistor.
With an NPN transistor you have to raise the voltage on the base above the ground voltage (this voltage is called V_BE, the Voltage between Base and Emitter). Typically that voltage is around 0.7V.
With an PNP, because the emitter is wired to your 9V rail, V_BE must therefore be relative to 9V, not ground, so the voltage on the base must be less than 0.7V below 9V to turn on. Which in itself is fine - a LOW will be around 0V, which is about 9V less than 9V. So it will turn on. The problem comes when you want to turn it off. You need to get the base voltage above 8.3V (9V - 0.7V), and that is impossible for an Arduino to do.
So normally a PNP transistor is switched by using an NPN transistor to switch the base of the PNP between 9V (pulled up through a resistor) and 0V (switched through the NPN).
And that then becomes pretty much pointless, since you are then adding a second, NPN, transistor, and you could just as well use the NPN alone to switch the motor, making the PNP completely redundant.

When connecting together several circuits that have different supply
voltages, common practice is to make them all have a common negative
supply rail. This is called “common ground”. As explained in Majenko’s
answer, you would need an NPN transistor for that.
If you want to use a PNP instead, then you could forget the common
practice and do everything “backwads”: if you connect together the positive
ends of the power supplies, you will have a “common VCC”
instead of a common ground. Relative to the Arduino ground, your
9 V battery will have one pole at +5 V and the other at
−4 V.
The wiring is the following:

connect the emitter to +5 V (Arduino +5 and battery +)
connect the base to an Arduino output through a resistor
connect the collector to the motor
connect the other end of the motor to the battery −
put a free wheeling diode in parallel with the motor.

Edit: Below is an ASCII art rendering of the circuit. Beware that
the motor is ON when the Arduino output is LOW.
+-----------+
|         5V|-----------------+-------------------+
|           |                 |                   |
|  Arduino  |                 |                   |
|           |    ,-----.  B |< E                 ___ +
|        D13|----|     |----|    PNP              _
+-----------+    `-----'    |\                   ___
                              |C                  _
                              |                  ___
                              +---------+         _
                              |         |        ___ 9 V batt.
                              |         |         _
                             ---        |        ___
                              ^       motor       _
                             / \        |        ___
                             ---        |         _  −
                              |         |         |
                              |         |         |
                              +---------+---------+

Is this method safe or so-so? I have a lot of PNPs that can carry 80 volts, and always use NPNs for driving voltages higher than 5.

@user400344: We all use NPNs: it's the standard practice, and it feels kind of weird to have the + side of the supplies as a common reference. As always, it's safe as long as you are within the component's specs.

I don't know what you are trying to do, because the link fails to display in my browser.
In general there is no reason why you can not use a PNP transistor, providing you use appropriate polarities, and assuming common-emitter mode, reference to the +5V rail rather than Gnd.
Having said that, you would need some specific reason. In general NPN devices are cheaper and/or outperform PNP, all other things being equal.

Link works on my iPad. You just got to wait for the image for a while. It should at least have a loading animation.


text:
Why does my servo execute an action in the beginning when the odds are almost 0?
I made a servo motor turn if the result of random(0, 10000) is less than or equal to 1. If that is the case, the motor turns to 130 degrees, to 50 degrees, and then to default position(90 degrees). It works well except whenever I turn on the Arduino, it automatically executes the turning maneuver. It usually takes dozens of seconds for the randomNum to be 1 or 0. However, the servo always turns right away at the beginning. Here is my code. I will make comments to help you understand what I was thinking. I used no delays.
#include <Servo.h>
Servo servo;
unsigned long timer=millis();//counter
unsigned long servoTimer;
boolean turned130 = false;
int randomNum;//will hold value 0-9999
bool backCheck = false;//variables to keep track which code block to call
bool checkingAllowed = false;
bool turned50 = false;
bool startChecking = false;

void setup() {
servo.attach(12);
servo.write(90);//set default position
servoTimer=millis();
}

void loop() {
timer=millis();//update counter each time
if(checkingAllowed==false){
randomNum = random(0, 10000);//random number generator
if(randomNum<=1){//small odds
  checkingAllowed = true;//makes this codeblock unable to run
  servoTimer=millis();
  servo.write(130);
  turned130=true;/sets variables to allow other if statements to run
  turned50=false;
}
}
if(timer-servoTimer>=1000 && turned130==true && checkingAllowed==true && turned50==false){//next codeblock that runs if random <= 1 after 1 second
turn50();
}
if(timer-servoTimer>=1000 && turned130==false && checkingAllowed==true && turned50==true){
turnBack(); one second later this runs
}
if(timer-servoTimer>=1000 && checkingAllowed==true && backCheck==true){
  backCheck=false;//servo turns back to 90
  checkingAllowed = false;//allows the main code block to be called
}

delay(2);//small delay
}

void turnBack(){
random50 = random(0, 160);
servoTimer=millis();
servo.write(90);
backCheck = true;
turned50=false;
}
void turn50(){
turned130 = false;
random130  = random(0, 160);
servoTimer = millis();
servo.write(50);
turned50=true;
}

It takes a while for the random number to be 1 or 0. I do not understand how 100% of the time, the servo executes the maneuver in the beginning. I will give any more information if you need it to aid me. The random() will soon be replaced by ping() of ultrasonic sensor. Then, the problem will probably disappear. I just want to be clear on what is happening here.

Recognise that, despite the name, random() does not produce a truly random number. Because a computer is basically determinate, every time random() is called it produces results in a fixed sequence - it is possible that this sequence includes 0 or 1 straight away.
If you want it to start at a different point, you need to "seed" the random number generator by calling randomSeed() and passing in an integer. Note that it can't be the same integer every time - that would just move the sequence to the same point every time. The Arduino reference for random() suggests reading an unconnected analog input with analogRead() (which would produce different numbers at different instances in time) to "seed" the random number generator with a new starting position.
randomSeed(analogRead(A0)); // Seed random() with random starting point


text:
Using interrupts for two MCP23017
I am creating a simple shield with two i2c MCP23017 chips. Each MCP23017 has two interrupt pins, but the Arduino Uno only has two interrupt pins (pin 2 and pin 3).
The way I understand it, interrupts are there to tell the Arduino something has changed, so it can then poll the MCP23017 for the latest pin reads.
How can I connect the 4 interrupt pins to my Arduinos 2 pins?

Read the datasheet for the MCP23017. It tells you how to turn the two interrupt pins into one.

I see There are two interrupt pins, INTA and INTB, that can be associated with their respective ports, or can be logically OR’ed together so that both pins will activate if either port causes an interrupt. but I'm new to electronics so I'm not sure what this means. Do I need to connect a chip to the two pins then connect the output to one of the interrupt pins?

No, you need to keep reading, down to where it tells you what all the registers do.

The MIRROR bit controls how the INTA and INTB pins
function with respect to each other.
• When MIRROR = 1, the INTn pins are functionally
OR’ed so that an interrupt on either port will cause
both pins to activate.
• When MIRROR = 0, the INT pins are separated.
Interrupt conditions on a port will cause its
respective INT pin to activate.

This MIRROR bit is set by software?

Yes. You can also set the ODR bit to make it open drain, then you can wire both chips into one int pin with a pull-up, should you wish.

Thanks so much for your help - for my purposes I have two chips and two interrupt pins so enabling mirroring would work well. If you would care to move your comment to an answer I can mark it as accepted.

The MCP23017 (and it's sister the SPI-based MCP23S17) can have their interrupt pins set to "mirror" mode. In this mode both pins are internally joined so when an interrupt occurs on any port both pins activate.  This is done using the MIRROR bit of the IOCON register.  Using this will turn your 4 interrupt pins into just 2, one for each Arduino INT pin.
Should you want to add more in the future, or if you find you want to use one of the interrupt pins on the Arduino for something else, there is also the ODR bit in the IOCON register. This sets the interrupt pins to be open drain, which means that all of them can be wired together into just one INT pin on the Arduino. Add a pullup (or enable the internal pullup) and you have have many IO expanders on one INT pin. Of course, that then means that you have to poll all the expanders to find which of them triggered the interrupt, so could slow things down somewhat depending on how you are using it.


text:
LED Strobe based on switch press through Arduino
I have a problem I can't see to solve. I'm trying to program my Arduino, which I just got. I have read a lot of programming scenarios, but can't seem to find one that fits my problem.
I can get the LED to turn off and on like I want.
Assume a switch is pressed or even two wires to the LED are put together. Once the switch is pressed I'd like the LED to flash briefly, even though the LED has power to it. Is there a way to do this with Arduino code?
(1) Press switch
(2) Flash LED briefly
(3) Switch is still being pressed
(4) LED remains off until switch is pressed again
(5) loop through routine again.

Check for a state change instead of just the state.

"I'd like the LED to flash briefly, even though the LED has power to it." I'm guessing this is not what you really need. If you DO keep power to it, the LED will stay on. What I think you mean (correct me if I'm wrong) is that you want to power the LED briefly (the blink period) when the button is pressed and for however long it is pressed, until the button is released again. With an LED, power => light (as long as the power we're talking about is logic HIGH or logic LOW; not just any old source of power).

This is a modified Example program that i have tested and seems to do what you expect. I have used a 2 position switch instead of a button. using a pointer "ledState" to indicate that the LED has flashed and have then combined 2 conditions with the "&&" in the IF statement.
/*
  Button

 Turns on and off a light emitting diode(LED) connected to digital
 pin 13, when pressing a pushbutton attached to pin 2.

 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground

 * Note: on most Arduinos there is already an LED on the board
 attached to pin 13.

 created 2005
 by DojoDave <http://www.0j0.org>
 modified 30 Aug 2011
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Button
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
int ledState = 0;
void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if ((buttonState == HIGH)&&(ledState == 0)) {
    // Flash LED:
    ledState = 1;
    digitalWrite(ledPin, HIGH);
    delay(500);
    digitalWrite(ledPin, LOW);
    delay(500);
  } else if ((buttonState == LOW) && (ledState == 1)){
    ledState = 0;
    delay(50);
    }
}

You might want to add a bit of delay after ledState = 0; to prevent switch bounce from re-triggering.

Yes, You are correct, I have edited my answer post to reflect that change...thanks.    no more bounce.


text:
How to handle low temperatures using Arduino Uno?
I want to create a simple electronic temperature sensor using the Arduino Uno.
The environments I want it to handle is inside a fridge and near a heater.
Although I am sure the Arduino can easily handle a heater; my issue is that the Arduino may not be able to handle a fridge.
A fridge also has the added problem of causing water vapor (and we all know water + electronics is never a good idea).
So my question is:

How would I create a temperature sensor using my Arduino Uno, that I can put in my fridge?
Are there any other problems I have not considered and how do I solve them?
Will I need a special type of casing? If so, which type?
Is an Arduino Uno even the best tool for this task?

Condensation is mostly a problem when you take the cold Arduino out of the fridge, into the warm room. Putting the entire project into a ziplock bag is probably sufficient protection.

Your Arduino does not have to be in the fridge, just the sensor. You can always choose waterproof sensor like this one to use with the arduino. Then you can always store your arduino outside the fridge. Same goes for the heater. Try to keep the arduino at room temperatures to avoid decreasing its life unnecessarily.
As for an actual answer to the temperature ranges, here is a good answer

That makes sense, but I kinda want the entire object in the fridge for my specific use case. The reason being is that I'm making a game, where the player is tasked to put this cube (i.e. a packaged arduino) in different temperatures (although the player of course doesn't know that). If the correct temperature is found it does something (like open a door via wifi).

in that case you just need an airtight box (look up one on google). Any box will do, like the food boxes. You can also drill holes for probes and seal them with silicon. here is a commercial box

My other issue is ensuring enough ventilation. Wouldn't a airtight box cause humidity?

Regarding moisture you could use a moisture absorbing package (e.g. filled with salt or some silicate).

like @LStrike said, use a moisture absorbing package to absorb the moisture already in the box. Since it is airtight moisture from the fridge will not get in. The component on the board in your case do not need any special cooling, especially in such a cold environment.

Humidity would be your biggest enemy. The fridge is a very moist environment for two reasons:

The colder the air temperature, the less moisture it can hold overall, thus saturating more quickly and reaching a higher relative humidity.
Lots of moist foodstuffs in an enclosed space.

You should be OK as long as the enclosure you choose has plenty of ventilation to avoid a temperature differential or trapping moisture.  Either of those two conditions could cause and even larger increase in humidity or, worse, condensate to form.

But how can I ensure I have a container that is both waterproof and enough ventilation

You don't need a waterproof case unless you plan on submerging the Uno in water as well.


text:
Using Arduino Yún to send data through Ethernet
I'm still new to Arduino Yún and I can't find any tutorials or examples on making the Yún send data through Ethernet, which will then be showed on a web server.
I've seen other tutorials but they use Uno with an Ethernet shield.  Is it the same with the Yún too?
How can I send data through Ethernet using Yún?

There are three bits of information you need to know:

The Ethernet port is connected to a tiny Linux computer
On Linux you can do HTTP POST and HTTP GET using a program called cURL
The AVR chip can tell the Linux computer what to do using the Process library.

Putting all those together: You need to use the Process library to tell Linux to run curl with the right parameters.
Just like the tutorials show you:

https://www.arduino.cc/en/Tutorial/Process


text:
How can I convert PID correction values to an PWM brushless command?
Please I'm working on a quadcopter, and I have to made my own flight controller based on arduino uno.
First of all please how can I get a filtred angular velocity and linear acceleration from the MPU6050, is the following code give us the angular velocity in deg/sec and the linear velocity in m/s² ?
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
and is this pid value in this following code is right ?
  accel_reading = ax;
  accel_corrected = accel_reading - accel_offset;
  accel_corrected = map(accel_corrected, -16800, 16800, -90, 90);
  accel_corrected = constrain(accel_corrected, -90, 90);
  accel_angle = (float)(accel_corrected * accel_scale);

  err = angle_setpoint - accel_angle  ;

  P = Kp * err ;
  I += (Ki * err) ;
  D = Kd * (err - errp);

  pid = P + I + D;

Thank you.

How can I convert PID correction values to an PWM brushless command?

you have to do that yourself. you have to figure out first how to correct a pid value directionally. for example, should you increase the duty cycle if pid is positive or negative?
after that, you will need to map the pid value to a range for your pwm dc.
basically, it is application / task specific, and you are in complete charge.

You convert PID outputs to process outputs by selecting appropriate Kp, Ki, and Kd constants -- they translate the error components into a process output.   For example, if you want 10 degrees of error to give you a full-scale analogWrite() adjustment, set Kp=255.0/10.   Ki and Kd will depend on the (unspecified) sampling interval.  If the measurements are noisy, you can use the Ki term to do some filtering work, but if you filter it prior to the PID, it will reduce the performance of the PID.
Code-wise, you are missing some sort oferrp=err; code, you need more than acceleration in the x direction to calculate an angle, (atan2(az,ax) or some such, depending on orientation), and your PID scheme doesn't protect against common problems like out-of-range, integral windup, or inconsistent sampling interval.   You should investigate the http://playground.arduino.cc/Code/PIDLibrary for a more robust implementation than you've half-coded above.


text:
do i need to also connect GND and 3.3v
I am trying to run this code:
https://github.com/miguelbalboa/rfid/blob/master/examples/ReadNUID/ReadNUID.ino
Using an ESP8266 based D1 board and an RFID-RC522.
I am not able to get it to detect the rfid tags ...
the serial monitor just shows:
 ets Jan  8 2013,rst cause:4, boot mode:(3,4)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v00000000
~ld

The "Typical pin layout used" section of the above document does not mention any connections on the 3.3V & GND pins of the RFID-RC522 card.
Does this mean that I do not need to connect them?
Or is is just so obvious that I should connect them that they did not bother to write it in that section?

Where is this "written down" that you are talking about?

in the  "Typical pin layout" section of the document I mentioned above.

Stupid question, but apart from connecting the power, have you uploaded the code?

It is just so obvious that you should connect them that they did not bother to write it down.
The reader needs power. That is taken as read. Without power it can do nothing. Why would they bother to waste time telling you to connect the things that you have to connect regardless? The only things that they tell you to connect are things that are specific to the sketch - i.e., which IO pins to connect to which function on the reader. Power doesn't change - it's the same from sketch to sketch and from person to person. The IO pins do, though, and need to be detailed. Power and ground don't.

o.k. thanks. Its the first time I try to connect anything to my arduino... wat about an IRQ pin on the RC522? is this another standard pin I should know about? or does it just remain un connected?

@epeleg You said you were using a D1.

Sorry, your are right of course.It is indeed a D1 board. being new to this area I still think of all those boards as "arduinos" but I now start to understand that this is not the case and each board is different. So to be more precise I am using a an ESP8266 based D1. and I think its considered a "retired" board as it turns out that there are newer releases of it (R2).
That said, I do own also an "adeept" uno - is this considered an arduino? or arduino compatible board?

Even after connecting the 3.3V and GND wires I still cant get the RFID-RC522 to detect neither the plastic nor pvc tag. I wander if I will have better luck if I use the "adeept" Uno... because I realy don't know why it does not work... maybe i need to initialize the tags somehow?

just to add - I do manage to send a program to the D1 board and for example blink its onboard led.


text:
Confusion about PNP transistors
I was reading through SparkFun's article on transistors when I came across something that confused me. The article showed this circuit:
With this description:

Similar to the NPN circuit, the base is our input, and the emitter is tied to a constant voltage. This time however, the emitter is tied high, and the load is connected to the transistor on the ground side.
This circuit works just as well as the NPN-based switch, but there’s one huge difference: to turn the load “on” the base must be low. This can cause complications, especially if the load’s high voltage (VCC in this picture) is higher than our control input’s high voltage. For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor. In that case it’d be impossible to turn the switch off because VB would always be less than VE.

I am confused because the part about the Arduino not being able to turn off a PNP transistor makes sense, but doesn't the circuit shown feature exactly the situation described that the transistor wouldn't work in? Is this an oversight by me and is there something else going on here that I don't understand, or is this a mistake in the article?

"this circuit wouldn’t work"

That's what I'd think, but this is what was shown on the article....

I pulled that text from the posted description verbatim.

.... For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor. ....

Don't actually do this to your arduino. The 12v will damage your arduino, especially when the 5V state is meant to output voltage, not taking in the 7v difference from the 12v.

I explained all this in the answer to your other PNP question. If you choose not to believe me then that's fine...

@Majenko ehehe funny thing, he wasn't the OP of the other question, he was the answerer to the other question.

@Bradman175 So he is. It was late and I'd spent the evening singing in Welsh, so my brain wasn't firing on all cylinders.

The article is saying that the circuit wouldn't work, thus it illustrates (correctly) something that won't work. What is the confusion?
To turn the PNP transistor off, the base voltage needs to be low with reference to the emitter voltage. Thus with an emitter voltage of 12V, and the most the Arduino can output is 5V, the transistor will never be off.

Sorry learner comment here. I tried it on a bread board with 3.3 and 5v interestingly applying either +3.3 or gnd turned it on and floating was off? 1k resiter to base. I thought you could never turn it off. I must be missing somthing?

I'm not sure what you mean by "floating was off". Perhaps you should make a new question and reference this one if needed.

@AndrewT  As a general rule applying a floating input will result in undefined behaviour. With floating input there might be leakage from other parts of the circuit, enough to produce behaviour you are not expecting.


text:
Arduino - RF 433 Mhz transmitting string and but receiving ASCII values of those characters
When I am using RF 433 MHz module with ARDUINO MEGA then it is transmitting any text or anything in ASCII values. Now how to decode those ASCII values to alphabets? If I use ASCII conversion programme then what if I send a number and that conversion program converts that number also to text or related ASCII character? please suggest any way.

Nothing gets "converted" - ASCII values and text are one and the same thing. It's all down to how you print it.

Lokesh, to expand on what Majenko said when you transmit something over this sort of link you are transmitting either a 1 or a 0.  When 8 ones or zeros arrive you have a byte.  A byte has a value of between 0 and 255 and what this means is entirely up to the 'protocol' you are using.
In your case your sending program is sending a letter, lets say A.  Now the A that you are sending is held in memory as a byte with the value of 65, 65 is the ASCII [code] for A. So 65 is sent as 8 different transmissions to the other end of the link and is received, built back into a byte and your program receives a byte with the value of 65.  Your receiver program is using the same protocol as your transmitter program, so it 'knows' you don't meant the number 65, the colour green or an elephant riding a bicycle, you mean the character A.
To show that A you might need to cast the data you receive to a character i.e.
unsigned char rxData = 0;
Radio.ReceiveData (&rxData, 1);
Serial.println((char)rxData);

An elephant riding a bicycle is 64, not 65.


text:
Steppermotor+Arduino Mega+ Adafruit
I have 2 Stepper Motors (QMot stepper motor1 Amp, 5.3Ohms, 5.3 volts and 200 steps/rev.)
, which are connected to the Adafruit shield2.4, they are mounted to Arduino Mega, the motors pull generally 2 A from external current from Adafruit. My problem is, they don´t rotate smoothly, clearly and fast at the same time.
When I use DOUBLE to define my Stepps, speed is ok but rotation is lout and shaking. When I use MICROSTEP is more smoothly but too much slow. The program is running two stepper motors to roll up optical cables. The cables have to be really precisely come together and accurately be installed on pulley.
Also I need a solution to run my Steppers Motors smoothly, clearly and fast.
Incidentally, I want to know, do I need BigEasyDriver for that?
 If you need more info oder fotos feel free to ask
Regards,
Paria

What's an Adafruit shield2.4? Where is your code?

Adafruit do hundreds of shields. Many of them have multiple versions. WHAT shield is it?!?!

If you have two motors that always need to do the same thing at the same time why are you controlling two motors.  It would be easy to splice [which means join] the two motors control wires together,

adafruit motor shield v 2.3

my motors do diffrent things at the same time. I have to control the speed of second Motor, this motor shakes always according to its duty, that is too bad,  I don´t know how to let it running smoothly and fast. With MICROSTEPS is too slowly and with DOUBLE is shaking...
what should I do?
can I begin with MICROSTEPS and change it into Double and again in MICROSTEPS at the end. Because the Motor have to roll up cabels. The cables have to be really precisely come together, because of that I need Smoothly running, specially at the beginning and at the end....

And your code...? Or do I have to ask you for that ten times as well?

my code is too long, and it is impossible to post it hier !!!! I have tried 10 times...

as an anwser i have postet, if you can read it....

That is not how to do it. I suggest you read the help files and edit your question adding the code properly. Delete your answer. An answer is not the place to add information pertaining to your question.

it is impossible to post it hier - edit the question and post the code. Use code formatting (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

I'd look for a proper stepper driver, e.g. something based on A4988 or similar. I wasted a fair amount of time on the Adafruit motor-shield 2.3 until I finally abandoned it after failing to achieve higher speeds (I also had lots of issues with the motor getting hot). The A4988 takes care of step sequencing including micro-stepping and interfacing and programming is very simple. It only comes in surface-mount packaging but there are bread-board friendly carriers costing a few dollars available from multiple manufacturers.

authors: ชญานนท์ เนตตะพันธ์


text:
Declaring literal strings
When I want to write a literal string in Python, I use r before the string (or @ in C#):
in [1]: print r'\no esca\pe ch\ara\cters'
out [1]: \no esca\pe ch\ara\cters

In straight c++ I can use R, but in the Arduino IDE, this throws the following error:
Serial.begin(9600);
Serial.println(R"\no esca\pe ch\ara\cters");

<output> invalid character '\'in raw string delimiter

So how do I do the same in Arduino c++?

Raw strings in C++11 must have parens within the quotes in order to allow for a custom delimiter. Since your string lacks those parens, it is not valid.
Serial.println(R"(\no esca\pe ch\ara\cters)");


text:
Arduino Due - using built in ADC as a DSO causes issues at high frequencies (kHz)
I am trying to use the inbuilt ADC of the Arduino Due to measure voltage signals. The frequency range I'm interested in measuring is  up to about 30 kHz.But I'm observing a strong capacitor behaviour as I increase the frequency ( from 10kHz onwards this is quite visible).
This is most visible when measuring a square wave. When I get close to 30 kHz the signal looks exactly like the text book capacitor charge/discharge wave and nothing like a square wave. Even at around 15 kHz, the square wave looks more like a sine wave/ ramp signal than a square wave.
Based on the behaviour my guess is that a capacitor in the Arduino Due ADC is causing this (as  the frequency increases, the capacitor cannot charge/discharge fast enough). But I'm not sure whether I'm correct about this.
Even if I'm correct, how can I fix this?
Any help would be much appreciated.
Thanks.
I don't have screenshots for the behaviour for a range of frequencies, but I will attach a hand drawing of what it looks like.

Also NOTE that As the frequency increases, the amplitude of the observed wave decreases ( I couldn't show this in my drawing). Think this again links back to the capacitor charge/discharge speed behaviour.
My Vin circuit : I tested by adding a voltage follower at the right most end(not shown on the schematic), but that made no difference.

What is your signal source? If the source impedance is high, it is possible that capacitive loading is reducing the rise time, or your signal source itself has poor rise time. Show a plot where the distortion is less obvious too.   My initial thought was aliasing, so do pay attention to the whole frequency range to rule that out.

I'm using a laboratory signal generator, so don't think that is the issue.
And I am simultaneously measuring the signal using  a laboratory DSO and it shows up perfectly as it is supposed to.
I also updated my original post to show the behaviour for a range of frequencies.

Fixed : The issue was with the LM324 op-amp. It has a small slew rate (0.5 v/uS) which was causing the signal to flatten out at high frequencies. So had to change to an op-amp with a better slew rate.

Well, if you have source output impedance about 1k and Sample-And-Hold capacitance is 14pF, then RC time constant is about 14us.
You need something with low output impedance. Non-inverting Voltage Follower would be perfect for this (see source):

I already have a Non-inverting follower op-amp in my input.

Which op-amp? It might be insufficient output impedance for this aplication.

I think you might be correct.
My input impedance to the ADC might be quite big because I have voltage divider resistors to allow for a bigger voltage range. I will try with a voltage follower right before the ADC input.
BTW I'm using LM324 op-amp.

LM324 seems not be symetric in sink/source capabilities. But it shouldn't be this case, because your arduino chart seems to be symetric for charge and discharge.

So I tested with the Voltage follower just before the input goes into the ADC, and it made absolutely no difference. I expected at least some improvement, but the signal did not change at all.
I will attach my Vin circuit to the original post, it might be that the resistors I have used are just too high. But a voltage follower at the very end should have fixed that anyway. So still no progress.

Any chance to use oscilloscope? Or at least connect DSO directly (without destroying DUE)?


text:
How do I read numbers from a serial sequence
I have read through a number of posts including How do I split an incoming string? However I cannot work out how to extract numbers from a serial string.
My challenge is this;
I send a serial command 'freq\r' to a radio which will return a string like this 'FREQ: 10138.7 RX, INHIBIT TX'. The only thing I want out of this is the 1013 so I can then manipulate it and send out a second serial port. It sounds easy enough but I just don't seem to be able to extract those numbers easily because I don't have a separator to use.
The other thing is if the number is below 10 e.g. 9138 I only want to extract the first 3 numbers then add a leading 0 so I end up with 0913.
Once I have the four numbers I can then divide them so I end up with e.g. 09 and 13 or 10 and 13. I can then send these as HEX to my second serial device.
If you are wondering what the numbers are they are frequencies in kHz which I am extracting from a radio then converting to HEX to tune a pre-selector.
Any help would be greatly appreciated as this is my last stumbling block on this serial translator project. I hope this makes sense.
Thanks
Callum

I don't have a separator to use

You do. There is a space before the integer part of the frequency, and a
decimal point just after it. You can use strchr() to find them. Then,
you will have to prepend a zero if needed, and terminate the string one
character before the decimal point.
The following code does this by overwriting the original string. If you
need to keep that string, you will instead have to copy the relevant
characters to another buffer:
char * get_freq(char *message)
{
    char *space = strchr(message, ' ');
    char *dot   = strchr(message, '.');

    if (!space || !dot || dot - space < 5)
        return NULL;    // invalid message

    if (dot - space == 5)
        *space = '0';   // prepend a zero

    *(dot - 1) = '\0';  // terminate the string

    return dot - 5;
}

Forgive me if I sound a little dense with this question but how do I fit that in to a routine that is called every 5 seconds. I call the serial command 'freq\r' command every 5 seconds to check the frequency of the radio? Not sure why this is not obvious to me but I am, obviously, a beginner.

@Callum: Standard approach: whenever a char is .available() on the Serial port, you .read() it into a buffer[]. When you see a '\n', you know you have a complete message and you can get_freq(buffer). Do this in loop(), not in the query-sending routine that you call every 5 seconds.


text:
Bluetooth radio control of a motor
I need to purchase the correct bluetooth module for interfacing some simple functionality between an arduino and a motor. The tricky bit is getting the bluetooth radio to play nice with android and apple ios. There are things like MIT App Inventor, but I'd love to hear from someone with experience how to reliably control arduino from tablets/phones. Preferrably in a way that lets me define the control on the arduino. I can build android apps (slowly), not ios apps, but I would then have to either ask users to install untrusted apks or get it out through the google app store, which would take too long. Any help on this would be great.

This isn't an Arduino question, but an Android / iOS / Bluetooth one.  Putting something through the google store takes minutes, but many Anrdoid devices still have serious BTLE issues.  Meanwhile in the iOS world, last I heard app reviews take days, and you couldn't use classic bluetooth without jumping through MFI hoops.

You may want to have a look at the Adafruit BLE modules:
https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend/bleuart?view=all
They have provided great examples of how to connect from Android and iOS devices, as well as providing apps or code to integrate into your own apps and you get to implement the motor controller code yourself on the Arduino so should have full control over that side.
They even have an example where they are controlling a motor using an Arduino and Bluetooth, it may not be exactly what you need but hopefully gets you closer to an answer:
https://learn.adafruit.com/bluetooth-motorized-camera-slider/overview?view=all

Happy to help :-)


text:
Arduino Micro: how to switch off its blue power LED?
everybody!
I have a genuine Arduino Micro ("designed with adafruit", made in Italy) which is working perfectly well.
One thing I'd like to do but cannot figure out how (or at all), is to turn off the blue power LED. I hate blue LEDs, they hurt my eyes, and this one is particularly bright too.
I could just paint it over with black paint but maybe there are programmatic ways to switch it off?
Regards

The Blue LED is permanently connected to +5 volts through R5.
You would have to either remove R5 or the LED from the circuit board.

Unfortunately the blue LED is a direct connection between 5V and GND. You can see below in the schematic exactly how it is connected

The only way to 'turn off' the LED would be to remove either the 1K resistor or LED with a soldering iron.
Another possibility is to take a sharp knife and make a cut in the track directly before or after the LED. I've marked the locations where to cut on the eagle screenshot.

Just gooped the led under black paint, works well enough:)

@AlexeiDolganov that will work, as long as you don't care about the current being consumed by the led. For example in projects running on batteries.

No, it will be connected to USB, no need to count every mA spent.

There is not way to turn it off in software.
The only thing you can do is desolder the led, or it's resistor. Just add some solder to the joints on both sides. Then angle the iron, so it touches both side. The led/resistor will tend to get loose and stick to the iron. Cleanup the board, by removing the excess solder.
I tend to just destroy the led using a utility knife. Just try to lift the "glass" on top of the led with a bit of force. Scrape over the white remains to make sure there isn't any connection left.


text:
Arduino as a custom I2C slave device
I'm trying to interface with a master I2C device that doesn't exactly follow the normal I2C protocol.
The only difference really is in the read request. A "normal" I2C read operation looks like this ([M]aster, [S]lave):
S | SLA+R | ACK | Data | Ack | Data ...some number of bytes... Nack | P
^M  ^M      ^S    ^S     ^M    ^S                              ^M     ^M

But this device expects to do a read like this:
S | SLA+R | ACK | Data | Ack | Data | Ack | Data | Ack | P
^M  ^M      ^S    ^M     ^S    ^S     ^M    ^S     ^M    ^M

Essentially a read request goes to the slave device, and then the master sends an 8-bit register address, and then the master expects 2 data bytes back from the slave with the Master responding with an ACK on both.
I've been able to set up a master device to do this style of protocol pretty easily by just manipulating the I2C registers directly. But I can't seem to find a way to get the slave device to accept that it is going to receive a data byte after it has been selected by a SLA+R, which leads to a bus contention problem and the slave not giving the master an ACK.
Is this possible to do with the built in I2C hardware on the Atmel chips? Is there any alternative if it can't (bit-banging)?

with a master I2C device - what device?

Are you writing the code for both ends? Master and slave?

I'm missing something on the bus operation. Pretty much whenever I get NAK'd I know I need to redo the operation. On the i2c bus it should be an ACK'd or NAK'd on every byte.
Usually you send the address of the device then the command. So the master initially sends the address, which is ACK'd and then the master sends the command that it wants executed. Your diagram has the slave answering when it's the master that's required to give it an operation?
Here's a good document on it... :)
Philips I2C Document


text:
Nano onboard "test" LED blinks when powered via 5V pin
I have a Nano (clone) that I am powering from a regulated supply via the 5V pin; I have checked this at the board and my multimeter reads 4.92V, which seems close enough (?). The main reason I don't use the microUSB jack is a space constraint. In any case, thus far it does work fine.
Except the leftmost (considered with the microUSB jack as "top") of the four onboard LEDs, on the opposite side from the rx/tx lights, blinks at a steady one second interval.  Searching around, the only association I've found for that LED is that it is connected to D13, which I'm not using for anything.
What does this indicate?  I have not tried disabling it (by setting 13 low) but I am hoping to do so if it is a benign issue.

Do you have the Blink sketch loaded by any chance?

@Majenko No, I've never used that.  To double check it wasn't something I'd done though, I took it out to reflash it and noticed it did the same thing w/ the USB power :\ When I reflashed it it stopped, and it doesn't do it anymore via the 5V pin either.  I just assembled this one, and D13 is attached, but the only thing it might conceivably have been used for would be driving a servo or reset.  Since there was a pin connected to reset, I tried that driven low instead of high and guess what?

So, as per the comments on the question here's what I think happened:
That "test" LED lights briefly when the board is first powered on, indicating I suppose that it's booted and setup() is either complete or about to run.
It also lights briefly when the reset button is released.
In the sketch I'm using one of the digital pins is connected to RST -- the arduino is being controlled via UART.  I have swapped some of the pin numbers and wiring around, so I tried leaving the one driving RST low instead of high and indeed, this seems to be the issue: It's resetting at ~1s intervals.
(I honestly believe I checked this before by removing all connections, but since I did not note that in the question, perhaps I never did...)


text:
ESP8266 stuck in flash mode?
I have the setup described here: https://learn.adafruit.com/esp8266-temperature-slash-humidity-webserver/wiring
I currently have the reset pin set to float and the GPIO0 pin grounded, which should make it execute the uploaded program, but instead I get the flash mode output:
    writing flash
...................................................................................................................................................................................................................................................

How do I put it into execution mode?

Try putting a pullup on Reset and GPIO0.

GPIO0 pin grounded, which should make it execute - no, GPIO0 grounded is how to put the thing into programming mode

What is the correct configuration then?

I was stuck in a similar scenario. I managed to exit programming mode by floating GIPO0, then grounding RST for ~3 seconds, then floating it. If you power off the esp, and now turn it on, it should have exited programming mode. Powering it off is actually optional.

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


text:
analogRead values all over the place, while measuring light
I'm trying to detect light using an led that's already attached to the circuit. I have a flashlight shining on the led.
Minimal sketch:
while( true )
{
    int photoValue = 0;
    analogReference(INTERNAL);
    photoValue = analogRead(A5);

    Serial.println(photoValue);

    delay(300);

}

While I have my multimeter attached, it reads a pretty constant value around 5mV. The serial output however swings around, as seen in this sample output:
0
0
4
4
0
16
15
22
21
25
20
36
40
34
36
24
5
0
3
6
0
0
0
0

That would translate to values between 0 and 43mV.
When I disconnect the multimeter only get 1023 printed.
I don't get how the values from the ADC and the multimeter, totally don't match.

Can you show your circuit?

I strongly suspect that the LED isn't able to produce enough current to charge the S&H capacitor. Plus the LED, when not generating enough voltage, will most likely make it look like the pin is floating somewhat. You may need a high impedance buffer between the LED and the ADC.

In a few days I will have high impedance buffers available on eBay based around the OPA355. I will experiment with one when the components arrive to see what a difference it makes.

Not enough current; makes sense. The circuit is 8 LEDs in parallel, connected between gnd and A5. Tomorrow I'll try adding a small capacitor to the A5 pin. I don't have any room for something like an opamp. So if that doesn't work I'll just have to scrap this, nice to have, extra feature.

What is it you're trying to do, ultimately?

I have a string of tiny SMD LEDs attached to some fake eyelashes. I currently have a few different animations/patterns programmed. I thought it would be fun to make them more interactive, by e.g. turning the LEDs  on after camera flash is detected. Or just a regular increase in light hitting the LEDs, as camera flashes are very short. Pretty weird project but they look awesome when attached to a models eyelids.

That sounds fun! I'd love to see it when it's done. So I can imagine that space is at a premium. I can't imagine how / where you have stashed the Arduino... Does the model have a big hooter? ;)

The PCB is a 3 cm circle. ATMega328 on the front, CR2032 battery on the back, along with a hearclip. PCB will be placed on the back of the head, with wires going to the eyes. The wires are 0.1mm enameled copper. Here is an older photo. Final version will be two color (charlieplexed). Adding a 2.2nF capacitor (>100x the 13pF S&H capacitor) seems to stabilize at least a bit, though I haven't had much time to do some proper testing.

That is awesome! I love it! I expect to see it on the catwalks of London, Madrid and New York soon!

I have tested with an OPA355 and it improves things massively.

I printed the analogread values to the serial port. With the 2.2nF capacitor. You can see the voltage rising relatively slowly, when I point the flashlight on it. About a second. Removing the light does produce a sharp edge. Read values are still a bit is noisy, but I didn't put a cap on the aref pin in my pcb.

The problem you are facing is that the output of the LED is too high impedance for the ADC to work reliably.
Basically the LEDs can't produce enough current to charge the S&H capacitor properly, and on top of that the LED doesn't act as a resistive load when not forward biased, so the input is basically floating and picking up noise.
The best cure is to add a voltage-follower buffer with incredibly high input impedance in front of the ADC input.
By high impedance I mean something measured in the 10s to 100s of TΩ. Something like the OPA355.

Thanks for all the feedback. Due to the deadline I have to scrap the idea for now. But the next competition is in October, so maybe then. Anyway; much appreciated.


text:
How to structure data for HTTP upload
I'm building a GPS tracker using an arduino nano, Adafruit Ultimate GPS breakout, a SD card slot and a SIM800L module.
So far everything works, the tracker uploads the data to a server as well as saving an extra copy to the SD card. The problem is now, that I don't really think that sending a HTTP request every cycle (gps data point) is very efficient and I would also like to have a way of storing information if there is no GPRS reception.
The idea is to save the GPS data to SD card and bulk send it out every 5 minutes or so.
What would be the best way to set up the data structure? I'm saving the deta in a csv style file:
2016-8-2 22:23:44, 52.53251922, 13.31121666, 18.30, 7, 1.33;

Parsing that is not the problem, but rather how to keep track of what has been sent already and what not. I was thinking about Marking the lines that I sent with a # or something similar as first character.
The only problem I could see with that would be performance, since it could take a while to go though it every time once it's getting a bit larger.
Thanks!
Lukas

The only alternative structure I can think of is, since you have a number of data fields to send, you could create a struct to contain all the fields. Write the gathered GPS data to the file in its raw format, with file.write(&your_struct, sizeof(your_struct)) and read in a similar manner into a struct.

This will reduce the number of bytes written or read for any data point, and
Reduce the overall size of the file, compared to your original method, for the same number of GPS points.

The former improvement means there will be about 3 times as many GPS data points in a single block of data read from or written to the SD card, when compared to your current structure. Another more subtle advantage is that each data point occupies a known number of bytes in the file, making file navigation potentially easier. But you can only use this structure if you don't intend to view the CSV file with some spreadsheet program like MS Excel. You could, of course, very easily write your own PC program to parse the file and write to proper CSV. The Python struct module is very capable.
However, if you wish to continue with your current format, you can keep track of your current position in the file with file.position(); no need to use # as an indicator. You create 2 position variables, one to hold the position of the next line to be uploaded, curr_pos, and the other to hold the position of the end of the file for writing new data, end_pos. Initialize the former to 0.

You gather data as usual, and after 5 mins, you save the current file position to end_pos and seek to curr_pos with file.seek().
You read a line from the file and send it to the server.
If it's sent successfully (use the return code), you update curr_pos with file.position() so that it's now pointing to the next line in the file to be uploaded and go to step 2.
Else if the upload fails perhaps due to service, you stop uploading and don't update curr_pos. You seek to end_pos with file.seek() and go to step 1.

You will, of course, use available() to know when you've hit the end of the file to stop uploading, or you can compare curr_pos with end_pos for equality, whichever's more direct for you.
This involves a lot of operations on the file and I/O operations don't come cheap with SD cards, both in terms of current drawn and latency. Depending on how often you collect data and if you don't need to view it on a PC, you might consider some other means of storage (SPI flash, perhaps) or use a more capable Arduino like the Mega with more RAM and store the data temporarily in an array before upload, granting you faster access by orders of magnitude and much reduced power drain in the long term, since each block of file data will be accessed only once.


text:
Frequency generator
Can arduino generate the frequency with the resolution of 2 decimal places?
i.e. 100.12 Hz, 98.23Hz, 1.92Hz...
recently I need to generate a frequency to allow a stepper motor to move accordingly. But to ensure the stepper motor to functions normally, frequency must be generated , and it must be of 2 decimal places.
Can Arduino do that? Or is there any specific product that may generate frequency resolution as such?

There are better choices (processors with faster clocks, programmable oscillators, FPGAs) but it may be possible via use of interpolation or microstepping to get close enough to the desired behavior to work in your application.  This will not be a simple project, so the usual reasons for picking an Arduiono may not apply, especially as some of the other solutions will more easily get you close to this goal.

Do you need accuracy in addition to resolution? The answers so far show you can probably get the resolution you want, but if you also want accuracy, you will have to choose an Arduino clocked off a quartz (e.g. a Leonardo) rather than a crystal resonator (like the Uno).

What frequency? There is a big difference between 123456.22 and 1.22 in terms of significant digits, although they both have 2 decimal places.

@EdgarBonet - good point. I am 2.5678432 meters tall. That is a very precise measurement. It is also inaccurate. :)

thank you Chris, Edgar & Nick. Awesome respond.  Edgar: yes I need accuracy as well. Nick: there are several different frequencies I need to set which all of them need to be set at 2 dp. Wow, with that height u can be an NBA player hehe.

The standard Arduino Uno is clocked at a nominal 16MHz, and has three timers: Timer0, 1 and 2. Timer1 uses a 16 bit counter (the others are 8 bit), and can be prescaled by 1, 8, 64, 256 and 1024. That lets you do very precise timings (assuming an accurate clock!), simply by choosing different prescaler values and the relevant values.
Using your example rates, and assuming that you want a square wave (hence the "Halved" column), here are the calculations:
 Hertz Prescaler  Calculated      Halved  Actual Hz
100.12         8  19976.02876548   9,988  100.120144173...
 98.23         8  20360.3787      10,180   98.231827112...
  1.92       256  32552.08333333  16,276    1.9200049...

Note that to do this, you need to program the Timer yourself - the standard Arduino library sets Timer1 to a default setting, which won't do what you want.

thanks for your suggestion. Where can I refer on how to program the Timer myself?

The definitive work is the Atmel datasheet: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf . You'll want to read chapters 16 and 17.

I happened to do a similar analysis for Timer 1 on 328 / 32U4 clocked at 16MHz the other day and produced this plot:

This shows the frequency resolution as a proportion of frequency in red assuming optimal prescaling (the jumps are where prescale changes). The blue markers are realized frequency errors at frequencies drawn at the E12 series in magnitudes from 0 to 5. Unsurprisinly these are half or better than the resolution.
As a conclusion, you get a relative error of around 5e-5 for frequencies up to about 1kHz. After that you loose an order of magnitude per order of magnitude (which of course makes perfect sense).

The other answers about the way you can configure the timers are very good, but Edgar Bonet's comment goes to the heart of the matter. Do you need accuracy?
Your example of 98.23Hz suggests that you want 98.23Hz and not 98.22Hz or 98.24Hz. That means therefore that you require an accuracy of around 1 in 10000 (0.01%).

Can arduino generate the frequency ...

You haven't said which Arduino, but assuming one of the basic models, like the Uno, they come with a resonator which will have an accuracy of around 1%.
If the system clock is only good for 1% accuracy there isn't much point worrying about trying to get a frequency within 0.01%.

thanks and yeah I forgot to mntion the type. Other than the Uno, which Arduino might give the precise and accurate setting for 2 dp?


text:
Installing Pyserial
I will be running my CNC Via Arduino UNO R3, so i have found out that it runs on GRBL and that i need to load Python and Pyserial and a graphic interface.
Loaded Python 3.5.2, no problems, opened dos window typed Python, got the python >>> prompt, so far so good, downloaded/unzipped/copy/paste Pyserial  into c:/python35/lib/site-packages/pyserial.
at this point, at the dos prompt i type >>>python setup.py install. All i get is a syntax error.
I have included the dos script for comment
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Goblin>python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> import os
>>> os.getcwd()
'C:\\Users\\Goblin'
>>> os.chdir("/users/")
>>> os.getcwd()
'C:\\users'
>>> os.chdir("/../")
>>> os.getcwd()
'C:\\'
>>> os.chdir("/python35/lib/site-packages/pyserial/")
>>> os.getcwd()
'C:\\python35\\lib\\site-packages\\pyserial'
>>> python setup.py install
  File "<stdin>", line 1
    python setup.py install
               ^
SyntaxError: invalid syntax
>>>

This is about the 7th attempt.
I seem to be following the instruction correctly but it wont install ....HELP Please, this is so frustrating, what have I done wrong.
Thanks in advance
Doug

Dont do this within the python environment. Its meant to be run from the system command line. Navigate with 'cd' in Command Prompt to the pyserial folder and then run this command again.

not exactly related to Arduino but here it goes...
First check if you have pip installed:
pip --version

if not installed go here and download the get-pip script.
then on directory where you saved get-pip run on console:
python get-pip.py

this will install pip into your system which makes installation of packages in python way more easy.
if installed but not latest version ( at momment 8.1.2) do an upgrade before:

On Linux or OS X:

pip install -U pip

On Windows:

python -m pip install -U pip

after install pyserial using pip:
pip install pyserial

Did it work?
If not, try:
python -m pip install pyserial

if it still doesn't work install from source. Get the latest version here extract it and in the dir where you extrated run:
python setup.py install

PS: change to dir first, no need to do it inside python.

I'm pretty sure that what you are trying to do is actually call 'python setup.py' within the python script itself. Which you cannot do. The easiest way to install pyserial is via pip like so. (Windows)
python -m -U pyserial --upgrade

Now if you still want to use setup.py or you don't have pip installed. Make sure that you meet all of the package dependencies. Which in pyserial there are no others. Try exiting out of the python interpreter and just running
python setup.py install

In the same folder location as the extracted zip (use cd to change directories)

Thanks All...by running the command at a std DOS prompt I was able to install the Pyserial.py file.
i have since seen comments that some of the 3.x.x series Python has glitches,(I am running Windows7). I have gone to 2.7 Python as a program i would like to use doesn't appear to run under 3.x.x   bCNC likes the earlier versions, not sure why, but it does run under 2.7  . for those interested JCNC, EFL CNC, Grbl Controller seem to run OK under 3.x.x


text:
Software Serial and multiple shields for Arduino Uno
I have a SIM900 GPRS/GSM Shield (details here) and I am looking to stack a GPS shield (such as this one here).
My question is: I believe that they both require software serial, also it says to use software serial on D7 and D8 for both. Is this possible on an Uno?
I am a bit confused at if software serial has to have these two specific pins, or if these are just what is chosen on schematics?
What would be the most effective way to stack these two shields so they don't interfere with each other?
EDIT: Using a gps shield such as this gives the option  of

If you need to move the software serial port pins, they can be custom-routed to any other pin by cutting the solder jumpers between pins GPS-RX and D8 and/or GPS-TX and D9.

This isn't entirely clear to me, but am I right in thinking it means I can have multiple software serials on my Uno, just using different pins?

SoftwareSerial can use any pins. That's the whole point of it. However, some shields are wired to use specific pins. If two shields try and use the same pins then you can't use them together. Not stacked, anyway. You will have to use flying leads, or physically alter the shield (cutting tracks, soldering in "bodge" wires) to use them together.
That said, though, you can only use ONE SoftwareSerial port reliably at a time. That means, regardless of what pins they use, you can't use two shields together that require pins other than 0 and 1 (hardware serial).
To use them both you will need a board with multiple hardware UART ports and modify the shields (as mentioned above) to use the correct pins for those UART ports.

Ah, so even if I have for example:
SIM900 on D7 and D8,
Wifi on D5 and D6,
GPS on D3 and D4.
and set up each of these with their own
SoftwareSerial serial1(7, 8);
SoftwareSerial serial2(5, 6);
SoftwareSerial serial3(3, 4);
It still wouldn't work?

Not reliably. SoftwareSerial is a blocking system. It uses interrupts to start reception of a character through a port, but while that character is being received nothing else can happen. So you can only receive through one port at a time. If anything arrives on one of the other ports while something is being received on one port it is lost forever.

If I did the same kind of pin redirection, just on a Mega to the hardware serials, then used serial1, serial2 and serial3. Would this be the best way to reliably communicate with each shield?

Yes. That would be ideal.

Just to confirm, in this case I could redirect all the shields hardware serial pins (D0 and D1 of each shield) to each hardware serial of the Mega. Meaning I don't even need software serial?


text:
Simple IR Receiver code
Can I know a code for simple IR receiver. I using external trasmitter, and when the receiver (on arduino board) get the input (detect signal from transmitter), LED will be HIGH.

This isn't a code-writing service. I suggest you ask a more specific question. There are plenty of examples of code that detects IR codes. It would be simple to turn an LED on if a certain code was received.

Here is a library that might be able to help you out: https://github.com/cyborg5/IRLib/. Also a specific example of controlling a server from a sony remote control. https://github.com/cyborg5/IRLib/blob/master/examples/IRservo/IRservo.ino
I am slightly confused on what you mean 'get input'. So I am assuming an input from a button. Here is some pseudo code compiled from the IRservo example that might point you in the right direction.
#include <IRLib.h>

#define MY_PROTOCOL SONY
#define BUTTON_0 0x90bca  //LED ON
#define BUTTON_1 0x00bca  //LED OFF

#define LED_PIN 13 //Pin to LED

IRrecv My_Receiver(11);//Receive on pin 11
IRdecode My_Decoder;

void setup() { //Code to run once
  My_Receiver.No_Output();//Turn off any unused IR LED output circuit
  My_Receiver.enableIRIn(); // Start the receiver

  pinMode(LED_PIN, OUTPUT); //Set LED 13 to out
  digitalWrite(LED_PIN, LOW); //Start off in the off position
}

void loop() { //Code that runs forever
    if (My_Receiver.GetResults(&My_Decoder)) {
       My_Decoder.decode(); //Convert the values into types
       if(My_Decoder.decode_type==MY_PROTOCOL) { // Match the controller
          switch(My_Decoder.value) {
            case BUTTON_0:      digitalWrite(LED_PIN, HIGH); break; //Turn the LED on
            case BUTTON_1:      digitalWrite(LED_PIN, LOW); break; //Turn the LED off
          }
       }
     My_Receiver.resume(); //Wait for next input
    }
}

This should theoretically work, but has never been tested. Now if you are just wanting any result to turn on the LED you might be able to do this
void loop() { //Code that runs forever
    if (My_Receiver.GetResults(&My_Decoder)) {
        My_Decoder.decode();
        digitalWrite(LED_PIN, HIGH); //Turn the LED on
    }
    My_Receiver.resume(); //Wait for next input
}

Edit:
A sample from getting text (Different library) from the receiver and printing it to the Serial Monitor. Link to library: https://github.com/z3t0/Arduino-IRremote
    #include <IRremote.h> //Link: https://github.com/z3t0/Arduino-IRremote

#define IR_PIN = 11; //The data pin to the IR recv
#define LED_DATA = 13; //Either the builtin LED or plug one in

IRrecv irrecv(IR_PIN); //Start recv obj
decode_results results;

void setup()
{
  Serial.begin(9600); //Start Serial at 9600 baud
  pinMode(LED_DATA, OUTPUT); //Set LED pin to out
  digitalWrite(LED_DATA, LOW); //Start recv data view pin in low
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    //We have recieved something... lets print it and turn on the LED
    digitalWrite(LED_DATA, HIGH);
    Serial.println(results.value, HEX); //Send line in ascii hex format
    delay(200); //Make the LED visible
    digitalWrite(LED_DATA, LOW); //Turn off data led
    irrecv.resume(); // Receive the next value
  }
}

Edit #2
Since an image has been provided I believe this is what you want. To turn the ir data into a visible light... To do that is a little more tricky in just doing code. Here's an example that doesn't require any external libraries and will do what you want.
    #include <avr/interrupt.h>
#include <avr/io.h>

#define TIMER_RESET  TCNT1 = 0
#define SAMPLE_SIZE  64
#defome LED_PIN 13

int IRpin = 2;
unsigned int TimerValue[SAMPLE_SIZE];
char direction[SAMPLE_SIZE];
byte change_count;
long time;

void setup() {
  Serial.begin(115200);
  Serial.println("Analyze IR Remote");
  TCCR1A = 0x00;          // COM1A1=0, COM1A0=0 => Disconnect Pin OC1 from Timer/Counter 1 -- PWM11=0,PWM10=0 => PWM Operation disabled
  // ICNC1=0 => Capture Noise Canceler disabled -- ICES1=0 => Input Capture Edge Select (not used) -- CTC1=0 => Clear Timer/Counter 1 on Compare/Match
  // CS12=0 CS11=1 CS10=1 => Set prescaler to clock/64
  TCCR1B = 0x03;          // 16MHz clock with prescaler means TCNT1 increments every 4uS
  // ICIE1=0 => Timer/Counter 1, Input Capture Interrupt Enable -- OCIE1A=0 => Output Compare A Match Interrupt Enable -- OCIE1B=0 => Output Compare B Match Interrupt Enable
  // TOIE1=0 => Timer 1 Overflow Interrupt Enable
  TIMSK1 = 0x00;
  pinMode(IRpin, INPUT);
  pinMode(LED_PIN, OUTPUT);
}

void loop()
{
  Serial.println("Waiting...");
  change_count = 0;
  while(digitalRead(IRpin) == HIGH) {}
  TIMER_RESET;
  TimerValue[change_count] = TCNT1;
  direction[change_count++] = '0';
  while (change_count < SAMPLE_SIZE) {
    if (direction[change_count-1] == '0') {
      while(digitalRead(IRpin) == LOW) {}
      TimerValue[change_count] = TCNT1;
      direction[change_count++] = '1';
      digitalWrite(LED_PIN, LOW);
    } else {
      while(digitalRead(IRpin) == HIGH) {}
      TimerValue[change_count] = TCNT1;
      direction[change_count++] = '0';
      digitalWrite(LED_PIN, HIGH);
    }
  }
  Serial.println("Bit stream detected!");
  change_count = 0;
  time = (long) TimerValue[change_count] * 4;
  digitalWrite(LED_PIN, LOW)
  Serial.print(time);
  Serial.print("\t");
  Serial.println(direction[change_count++]);
  while (change_count < SAMPLE_SIZE) {
    time = (long) TimerValue[change_count] * 4;
    Serial.print(time);
    Serial.print("\t");
    Serial.println(direction[change_count-1]);
    Serial.print(time);
    Serial.print("\t");
    Serial.println(direction[change_count++]);
  }
  Serial.println("Bit stream end!");
  delay(2000);
}

If you want a non code example check out the answer below. It is a great solution. Without needing any arduino.
best regards, David

I mean "get the input" is receiver get signal from transmitter

I've added the new sample with getting data and printing it, and a library that seems slightly easier to use.

I know you want code.  However your question is how to light up an LED when an external remote control is transmitting.  This can be done with the following hardware:
Many ASK sensors integrate an IR photo sensor, AGC & PLL into a 3 pin package that has an appearance of a transistor.  Supply power and get back a signal when an ASK IR transmitter is detected.  Check the current capabilities of the ASK receiver, you might have to add a transistor to drive an LED.  No Arduino needed for detection.
Here is an example found on the web:


text:
Error when using buzzer and IR sensor
I am doing code for IR sensor. My problem is when I put this code (below) for buzzer, there will be error.
C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Tone.cpp:536: multiple definition of `__vector_7'
IRremote\IRremote.cpp.o:
C:\Program Files\Arduino\libraries\IRremote/IRremote.cpp:312: first defined here
collect2: error: ld returned 1 exit status
  tone(buzzer, 4000); // Send 1KHz sound signal...
  delay(500);        // ...for 1 sec
  noTone(buzzer);     // Stop sound...
  delay(500);        // ...for 1sec

Both the IRRemote library and the tone command use the same timer. You can't use them both together without modifying one of them to use a different timer. And that means looking at the source code for them both.

can I know how to solve it?

I already found the solution. Thanks for your advise. :)


text:
Parse HTTP Request Arduino
I am sending a HTTP Request to my WiFi module http://192.168.4.1/STA/ID=HelloWorld/Pass=Testin123
How can I parse above string in Arduino. First I need to check for STA, if it exists, continue to scan the string. Put Value of ID, in this case HelloWorld should be store in String data type SSID and Value of Pass, in this case Testin123 should be store in String data type Pass.
How can achieve above using ARDUINO code! Please help.

Are you sure you don't need to parse GET /STA/ID=HelloWorld/Pass=Testin123 HTTP/1.1, as that is what's send in the http request?

I would use strtok() using / as the token separator.

@Gerben Exactly that is!

Your incoming string, as Gerben has mentioned, will actually be more like:
GET /STA/ID=HelloWorld/Pass=Testin123 HTTP/1.1

My personal preferred method is to use strtok() to split the string up.  I'd use a two-pass method for this.
First split the string up into three parts - one GET, one the request, and the third the request type (though you don't need to use that for anything).  Assume the string is in C string incoming:
char *get = strtok(incoming, " ");
char *request = strtok(NULL, " ");
char *rtype = strtok(NULL, " ");

The request is now pointed to by the *request pointer and the string has been sliced up in-place.  So now you can do something similar with the request, this time splitting on / instead of space:
String SSID;
String Pass;

if (request != NULL) {
    char *part = strtok(request, "/");

    bool seenSTA = false;
    while (part) { // While there is a section to process...

        if (seenSTA) {
            if (!strncmp(part, "ID=", 3)) { // We have the ID
                SSID = String(part + 3);
            } else if (!strncmp(part, "Pass=", 5)) { // We have the password
                Pass = String(part + 5);
            }
        } else if (!strcmp(part, "STA")) {
            seenSTA = true;
        }

        part = strtok(NULL, "/");
    }
}

I thought Strings are evil :D

@TisteAndii they are, which is why I do it all as C strings and then finally convert it to String which Anuj wants (supposedly).

@Majenko What about STA part? How to check that?

The same way as the others, but you don't need to specify the length since it's the entire string you are looking for. if (!strcmp(part, "STA")) { ... whatever here ... }

@Majenko I tried this but It can't find STA in entire link. Always showing Not found. Here is ArduinoCode

You can't nest like that. You get exactly ONE part of the string each pass through the while. If you want to only look for specific things if you have seen STA then you have to remember the fact that you have seen STA in an earlier pass.

@Majenko What actually I need to do is, confirm the presence of STA in string. If it is not present, do not enter into loop. If it exits, search for ID and Pass. It should only be single loop process. No need of while loop. Also using while() loop in arduino void loop() is not preferred, it crashes the program.

There is absolutely nothing wrong with using while on any platform. If it takes longer than the watchdog timeout then kick the dog. I have told you what you need to do. What part of it don't you understand?

I have enhanced my example to show you explicitly how to implement it.

@Majenko It worked well. Sorry for bothering you everywhere! I was really confused. It works well now. I understand the whole thing as well.


text:
Connecting external mic to the Teensy
I have a Teensy 3.2 and the Teensy audio board.
I was going to connect lavalier microphone to its audio jack but learned that it's only for output.
There are line-in pins though (see "Back Side" scheme). And MIC+GND pins, but these are for, ehm, radio parts microphones, I guess?
Being a complete novice I have no idea how to connect microphone jack (or audio connector) to line-in pins and whether I would need an amplifier between microphone and pins. If so then probably I just can't do it.
I would be grateful for detailed instructions.

It is easier than I thought! I soldered audio jack to MIC+GND, inserted microphone in and it works!
And pretty well :-)
Cheap random lavalier model: Panasonic RP-VC201. I guess any consumer model will do.