text:
Esp8266-01 AT commands returns random chars and/or "ERROR"
I'm trying to make my esp8266 work with my arduino.
But when I send AT commands I get some weird symbols and some functions return "ERROR"
Here's the code I'm using.
#include "SoftwareSerial.h"

SoftwareSerial esp8266(6, 7); // RX, TX

void setup()
{
  Serial.begin(9600); // serial port used for debugging
  esp8266.begin(115200);  // your ESP's baud rate might be different
}

void loop()
{
  if(esp8266.available())  // check if the ESP is sending a message
  {
    while(esp8266.available())
    {
      char c = esp8266.read();  // read the next character.

      Serial.write(c);  // writes data to the serial monitor
    }
  }

  if(Serial.available())
  {
    delay(10);  // wait to let all the input command in the serial buffer

    // read the input command in a string
    String cmd = "";
    while(Serial.available())
    {
      cmd += (char)Serial.read();
    }
    // send to the esp8266
    esp8266.println(cmd);
  }
}

Here's the Serial Monitor:
AT

OK
AT+RST

OK

 ets Jan  8 2013,rst catse:2, boot lode:(3,7)

loab 0x40100000& len 1396, qoom 16
tail 4C�,kk�������e
load 0x3fge8000, len 776, room 4 tak0  t0�v�
�!jH+��
����(j5�!
,�2%1�

j
�sl��o�
Ai,Thinker Technology Co. Ltd.

invalid
AT+CWMODE?

+CWMODE:1

OK

AT+GMR

AT version;0.25.0.0(Juo  5 2015 17:27:16)
SDK version:1.0
ryJ 0

AT+CWLAP

+CWLAP:(4,"�P��R�*bj��b���*��2��*����Ҋ�b�Jj
��*A�B�br������Յź�aj��b����2j
":6�*AՉ����J
"�́������

The commands where, AT, AT+RST, AT+CWMODE?, AT+GMR, AT+CWLAP
Why am I getting this weird symbols and etc? I haven't upgraded the firmware, should I?  There other commands I tried return "ERROR" or even "ERROQ"
I don't have a USB to TTL or any other board. I connected my board in the arduino with this schematic:

Cap = 10uF
VolReg = LM1117 3.3v

ESP8266 is a 3.3V device that means it's logic HIGH is not 5V. That means you need to convert ESP's serial output from 3.3V to 5V logic and serial input must be converted from 5V to 3.3V to avoid damaging the ESP. It is not meant to be fed 5V signals!

I'm not feeding 5v to my ESP. But do I have to step up the output signal from 3.3v to 5v? How can I do this?

Yes you are. Look at digital pin 7 and 6 they operate at 5V, ESP8266 is not a 5V device. So signals going from Arduino to ESP must be converted (5V->3.3V) and signals coming from ESP to Arduino can be converted, but Arduino should handle 3.3V HIGH just fine (to minimize possible issues you might want to do this). TisteAndii has mentioned it in his answer too.

The problem is mainly in using Serial and SoftwareSerial together. Or it can be due the esp getting less current than it requires from the Arduino(you are also damaging your Arduino!), use an external 5V source (I use my computer USB)
Why dont you directly use Serial for communication with pins 0 and 1. Just upload a blank sketch, connect Arduino Tx, Rx to esp's Tx, Rx(reverse Tx, Rx if not working). What you type into Serial will then be sent to the esp. Later if you wish to communicate to esp in sketches, use only SoftwareSerial.
Also, the esp is not 5V tolerant so you need to use a level shifter(like the cd4050 ic) or a voltage divider(less efficient) for signals from the Arduino to the esp. 3.3V is considered as a logical HIGH so you dont need to do any changes for signals from esp to the Arduino.
I highly recommend getting a USB TTL converter, this will save you a lot of headaches and debugging will be easy. I did things without it for 1-2months and now I can totally feel the difference.

SoftwareSerial is reliable only up to 9600 baud or so. You can either swap ports and use Software serial as your debug output (but requires disconnecting/reconnecting the ESP8266 chip each time you upload to the UNO); or write a short sketch to set the device's baud rate to 9600 baud (and convince yourself that at least that much ran OK!) and set your SoftwareSerial to that rate.

The Arduino pin 7 (TX) signal must be level-shifted from 5V to 3.3V using a voltage divider, because the ESP cant handle 5V signals.
The Serial baud is a lot lower than that of SoftwareSerial plus you are spending a lot of time waiting for the whole command to come in. SoftwareSerial is also unreliable at 115200 baud. Use 57600 baud for both serial ports.

Use this code:
SoftwareSerial esp8266(6, 7); // RX, TX

void setup()
{
  Serial.begin(57600);
  esp8266.begin(57600);
}

void loop()
{
  while (Serial.available())
    esp8266.write(Serial.read());
  while (esp8266.available())
    Serial.write(esp8266.read());
}

It will do the exact same thing you want to do. Good luck.

I had the same issue before and it is a little bug in your code - while reading all the data from the serial port, you also read the CR & NL and then you send that as a line (with probably another NL). I solved it as such:
  if(Serial.available())
  {
    String command="";
    uint8_t c=0;
    while(c!=10) // read the command character by character
    {
      if (Serial.available()) {
        c=Serial.read();
        command+=(char)c;
      }
    }
    //Serial.print("Sending: ");
    //Serial.println(command);
    esp8266.print(command); // send the read character to the esp8266
  }

As you can tell, I was suspicious of the code and echoed back to make sure the reading from the Serial function. Also I went back to straight USB->Uno->ESP mode to confirm all was working, even the firmware with the 9600 Baud uploaded and then it clicked.

When I tried one simple scetch which just communicates between Serial monitor and ESP I got "ERROR" when typed AT in the monitor. Then I switched from "Newline" to "Both NL & CR" in Serial monitor and after that I got OK when typed AT.

These values mostly come when you are unable to communicate with any UART device on proper baud rate. Best is to change the baud rate of ESP8266 from dafault 115200 to 9600 using
AT+UART_DEF=9600,8,1,0,3

And then use the regular program. And you will get what you want.
#include <SoftwareSerial.h>
#include<stdio.h>
SoftwareSerial mySerial(2,3);
void get_wifi_list();
uint8_t flag = 0;

void setup() {

    Serial.begin(9600);
    Serial.println("Starting the code, initial set-up");
    mySerial.begin(9600);
    delay(1000);
    Serial.println("Inside the main loop, going to start communicating with ESP8266");
    delay(1000);

}

void loop(){

  char data[1024];
  uint8_t ch = -1;
  uint8_t index = 0;
  memset(&data,0,sizeof(data));
  char data1[200];
  uint8_t index1 = 0;
  memset(&data1,0,sizeof(data1));

  if(mySerial.available())  // check if the ESP is sending a message
    {
    while(mySerial.available())
        {
            char c = mySerial.read();  // read the next character.
            data[index] = c;
            index++;
            if(index >= 2000){
                Serial.print("Data received exceed allowed length \n");
                return;
                }
                if (c == '+' ){
                    Serial.print("got start char");
                    //data1[index1] = c;
                    //index1++;
                    //if ( c== '\n');{
                    //    Serial.print("First data1 is :  ");
                    //    Serial.println(data1);
                    //    return;
                    //    }

      if( strstr(data,"OK")!=NULL || strstr(data,"CWLAP") !=NULL){
      Serial.print ("Get reply as OK \n");
      Serial.print (data);

        }
      }
    }
  }
  if (flag == 0){
      get_wifi_list();
      Serial.println("Getting the wifi list");
      flag = 1;
      return;
  }

  if(Serial.available()){
    delay(10);
    String cmd = "";
    while(Serial.available()){
        cmd += (char)Serial.read();
        }
    mySerial.println(cmd);
      }

}

void get_wifi_list(){
  String cmd = "AT+CWLAP";
  mySerial.println(cmd);
}


text:
Is my Arduino board defect? No matter what program I upload the pin 13 turns on and off 3 times and that's it
Just trying to find out if my Arduino UNO R1 board is broken or not.
First of all, everything seems normal, Arduino board shows "on" (green) when I plug it on my computer, I also can verify and upload programs to my Arduino board. But, no matter what program I upload the pin 13 turns on and off 3 times and that's it. I'm checkin it by using a LED.
Eg. if I want to use another pin (ex. 7, 8, 12) it doesn't work, or even to write a program for turning on/off 9 times pin 13 doesn't work...
Note: I noticed that pin 8 turns the LED for less than a 1/2 a second.
I already tried to restart board by bridging the reset pin and also by pushing reset directly on the board, I also reinstalled Arduino Genuino Application. I thought to update Atmega8U2 firmware but accordingly to Arduino site I don't need to update since I have firmware rev. 0.01.
It would be also great not to have to buy a new Arduino UNO. Thanks for your help
Edit:
Here is how I'm trying to make pin 12 work
int ledPin = 12;

void setup()
{
    pinMode(ledPin, OUTPUT);
}

void loop()
{
    digitalWrite(ledPin, HIGH);
    delay(2000);
    digitalWrite(ledPin, LOW);
    delay(2000);
}

Maybe the board is fine, but your programs are bad?

@Majenko that's also an possible. But I'm checking with a really basic tutorial. See my update please

And what do you have wired to pin 12?

The anode of a LED and the cathode to GND

No resistor? Maybe you are suffering from brownouts then.

Tried also with 220 ohms resistor. Yes I'm afraid it's broken

If it's broke you probably only need to replace the ATMega328, which is conveniently in a socket. Just make sure you buy one with the Arduino bootloader already programmed into it.

The best way to check if Arduino is working or not is to install Firmata. Here's the necessary steps:
1) Download Firmata application from the official website.
2) Connect Arduino to the computer
3) Open the Arduino IDE and burn the example Standard Firmata [File - Examples - Firmata - Standard Firmata]
4) Open the application, leaving the Arduino connected.
5) Chose the right serial port and debug every pin =D

So it turns out, that I was uploading my program to the wrong board. Thanks for the help!

source: Stack Exchange

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

sort: votes


text:
Water heater coding problem
I need help with my coding. I'm still learning on how to use interval millis().
Currently I'm working on a water heater with a safety feature. This means that you can only pour water out when you activate the child-lock feature. The child-lock feature will turn on for 5 seconds and within that 5 seconds if you pour the water out, the timer will pause until you finish pouring your water and the 5 second timer will start again and the system goes off after that.
If the child lock feature on for 5 second without any action, it will turn off the system again. My lecturer does not allow me to use the delay() function so I already did my coding using millis().
This is my code so far:
const int redLed = 2;
const int greenLed = 3;
const int yellowLed = 4;
const int greenbigLed = 7;

const int buttonPin1 = 5;
const int buttonPin2 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
float tempC ;
int analogPin = A0;
int yellowLedState = 0;

const long interval1 =0;
const long interval2 = 5000;
unsigned long previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,INPUT);
pinMode(6,INPUT);
Serial.begin(9600);
digitalWrite(yellowLed,yellowLedState);

}

void loop() {
  // put your main code here, to run repeatedly:
int analogValue = analogRead(analogPin);
int buttonState1 = digitalRead(buttonPin1);
int buttonState2 = digitalRead(buttonPin2);
int yellowLedState = digitalRead(yellowLed);
tempC = analogValue / 10 ;
Serial.println(tempC);
unsigned long currentMillis = millis();
unsigned long currentMillis2 = millis();

if (tempC <= 89.9 && tempC >= 0){
  digitalWrite(redLed,HIGH);
  digitalWrite(greenLed,LOW);
}else if(tempC == 102){
  digitalWrite(redLed,LOW);
  digitalWrite(greenLed,HIGH);
}

if(currentMillis - previousMillis >= interval2){
  previousMillis = currentMillis;
  if(buttonState1 == HIGH){
   // if(currentMillis2 - previousMillis2 >=interval2){
     if (yellowLedState == LOW) {
          yellowLedState = HIGH;
}
digitalWrite(yellowLed, yellowLedState);
  } else{
  digitalWrite(yellowLed,LOW);
    }
}

if (buttonState2 == HIGH && yellowLedState == HIGH){
  digitalWrite(greenbigLed, HIGH);
}else{
  digitalWrite(greenbigLed,LOW);
}

}

Now, I'm able to pour out water when child lock feature activated, but the problem is the timer (interval) still ticking.
Is there any solution on how can I pause the interval whenever I'm pouring water (button2) and the interval starts back 5 sec when I release button2 (pouring water)?
I would glad if someone can help me. Ask me anything about my code.

Something else to think about in your code: What would happen if somehow the temperature got above 102? Wouldn't you want the heater to shut off in that case? And do you really want the heater to not go on if the water is frozen?

Well in this case I am using potentiometer to appear as my tempC by dividing the reading by 10. Its kinda hard to use LM35 in class, so using potentiometer would give all the temperature I want easily.

Thanks @Arjan for reminding me. I would love to contribute to the community. So this is my final coding and its worked for me :
const int redLed = 2;
const int greenLed = 3;
const int yellowLed = 4;
const int greenbigLed = 7;

const int buttonPin1 = 5;
const int buttonPin2 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
float tempC ;
int analogPin = A0;
int yellowLedState = 0;

const long interval = 5000;
unsigned long previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,INPUT);
pinMode(6,INPUT);
Serial.begin(9600);
digitalWrite(yellowLed,yellowLedState);

}

void loop() {
  // put your main code here, to run repeatedly:
int analogValue = analogRead(analogPin);
int buttonState1 = digitalRead(buttonPin1);
int buttonState2 = digitalRead(buttonPin2);
int yellowLedState = digitalRead(yellowLed);
tempC = analogValue / 10 ;
Serial.println(tempC);
unsigned long currentMillis = millis();

if (tempC <= 89.9 && tempC >= 0){
  digitalWrite(redLed,HIGH);
  digitalWrite(greenLed,LOW);
}else if(tempC == 102){
  digitalWrite(redLed,LOW);
  digitalWrite(greenLed,HIGH);
}

if(currentMillis - previousMillis >= interval){
  previousMillis = currentMillis;
      if(buttonState1 == HIGH){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
  } else{
      digitalWrite(yellowLed,LOW);
    }
}

if (buttonState2 == HIGH && yellowLedState == HIGH){
  digitalWrite(greenbigLed, HIGH);
  digitalWrite(yellowLed,HIGH);
}else{
  digitalWrite(greenbigLed,LOW);
  if(currentMillis - previousMillis >= interval){
  previousMillis = currentMillis;
      if(buttonState1 == HIGH){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
  } else{
      digitalWrite(yellowLed,LOW);
    }
}
}
}

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


text:
Debugging with ISP
I would like to connect the Atmega328p chip to my desktop, through the USB, so I can run teraterm or hyperterminal for debugging purposes.
I have already ordered a USB to TTL serial cable but it won't be arriving for about a week.
I recently bought a usbASP ISP to program the chip on my Arduino.
My question is: can I use the usbASP in place of the TTL cable? or is there some conditioning circuit in the usbASP that won't allow this?
It seems for the usb to ttl, all that is required to interface with the chip is VCC, GRD, RX and TX. So, which pins are the RX and TX?
Hope my question makes sense, they usually don't! thanks in advance!

For simple debugging you could just add a few leds. Optionally make them blink in certain patterns for more complex information.

There is provision in the USBasp specification for a UART connection, however, not all manufacturers copy the original schematic exactly, and no firmware actually contains the appropriate code for CDC/ACM required in order to enable it. And even if they did, technically low-speed CDC/ACM is a violation of the USB protocol and not all operating systems will acknowledge it.
As for your title of "Debugging with ISP", if you have an Atmel programmer and are using Atmel Studio then you can perform debugging over ISP (actually debugWIRE, but they use the same connections).

So i can output messages to Atmel Studio? Say, outputting a voltage as a turn a pot, from the adc?

No. But you can use debugWIRE to inspect the register contents when the code hits a breakpoint.


text:
Is this a USBasp I can use with Arduino?
I bought the following USBasp off of Aliexpress.

The Arduino UDE doesn't recognize it. When I try to run avrdude with it, it says:
avrdude -cusbasp -Pusb -patmega328p
avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'

Looking at the USB enumeration, it says:
USBHID:
  Product ID:   0xc8b4
  Vendor ID:    0x03eb  (Atmel Corporation)
  Version:  1.00
  Speed:    Up to 1.5 Mb/sec
  Manufacturer: zhifengsoft
  Location ID:  0x14200000 / 8
  Current Available (mA):   1000
  Current Required (mA):    100
  Extra Operating Current (mA): 0

Looking online, I see one blog post (http://www.sciencetronics.com/greenphotons/?p=938) about a device with the same VID/PID, and it says it can be reprogrammed but is not clear how to do it.
In particular, I know there is a jumper that I need to set to put it in self-programming mode but I can't figure out where to put this jumper. Once the jumper is in, I understand I just match the SPI pins and program it using the firmware.
Can someone help?

That's not a USBasp, that's some other programmer that has co-opted Atmel's vendor ID invalidly. If you want to use it then you will need to find and use some program called "ProgISP" that is only available for Windows.
That particular device does not show the jumper required for reprogramming, so I wouldn't attempt it (and in fact I would find the nearest bin to toss it in and get a couple from Baite and/or LC Tech instead).


text:
Do external battery packs need to connect to ground on the arduino?
I am going to be controlling 2 servo motors with an arduino. I will use an external battery pack for power. Do I need to connect the negative of the battery to ground on the arduino? If I just use the battery pack to power an LED, it works without connecting it to ground. Can someone please explain the logic behind this in simple wording? Thank you

Ground is merely a label. It is a logical point in the circuit relative to which you measure all other voltages against.
For instance the 5V pin on the Arduino is actually 5V relative to the ground pin.
A 12V battery's + terminal is 12V relative to the - terminal. In this situation the - pin can be labelled Ground.
Electricity only ever flows when there is a circuit.  That is, current can only flow when it has some way of flowing back to where it came from.
A battery with an LED and resistor attached has a circuit: Battery -> LED -> Resistor -> Battery.  An Arduino itself is a circuit: Power -> Arduino -> Internal Gubbins -> Power
By the rule above, electricity can only ever flow out of an I/O pin if it has some way of getting back to where it came from. That route back is the Ground pin of the Arduino.  Interfacing some external device with the Arduino, whether it has its own power supply or not, requires that connection back to the Arduino's ground in order for the signal you send from the Arduino to have a complete circuit.

In short, always connect the grounds!

@NickGammon Unless you don't need to, such as if you have an opto-coupler.

@NickGammon so because the arduino is sending a signal to one of the pins on the servo, the servo needs to be connected to Arduino's ground. If the arduino has nothing to do with that circuit, then the negative battery terminal is enough. Is that correct? Thanks for your help

Yes, the signal needs to be in reference to something. So you would have ground on the servo going to both the Arduino and the battery negative terminal. Then the signal from the Arduino goes to the servo control pin, and the positive side of the battery to the servo motor pin.

I like the Majenko's answer, but I'm going to explain it with a different approach. You know that there are some quantities that are measurable in an absolute way (mass, lenght, weight) and other that need a starting point to refer. Think about the distance: you cannot say "New York" is distant 10km.. the question that obviously would come in mind is: 10km from what? So you have to decide a point in the world, from which you can measure the distance of every city.
The voltage measure the potential, that is the energy that a single charge would have. Now the question is: is the potential energy an absolute value? Of course not, i have to define a point where it is zero, and measure everything from it. In a circuit this point is called Ground, evry potential measured in the circuit is calculated to the ground.
The last step is to know that charges goes from the points at higher pot to the lowest one (the ground), usually preferring the path with lower resistsnce (but that's another story). A wire has the same potential all along it and in order to compare the voltage of arduino and the battery pack they must refer to the same ground.

so because the arduino is sending a signal to one of the pins on the servo, the servo needs to be connected to Arduino's ground.

Here is typically how you might wire a servo:

Note the shared ground. The Arduino provides the control signal (data) via the orange wire. The battery provides the motor power via the red wire. The grounds must be shared or the voltages on each wire are meaningless.


text:
How to send data from Arduino Uno with SIM900 GPRS to Firebase
I'm creating a real-time vehicle tracking Android application using the Arduino Uno and SIM900 GPS. I want to use Firebase as the database for the coordinates which will hold just the longitude and latitude. My question is about sending the data through the GPRS to Firebase. Right now I've only been able to use a terminal program to send AT commands to create a connection but I've been getting errors when connecting to firebase using AT+CIPSEND. I know that it only excepts https traffic so I've been trying commands from here. Here is some code that I've tried:
AT
OK
AT+CREG?
+CREG: 0,1

OK
AT+CGATT?
+CGATT: 1

OK
AT+CIPSTATUS
OK

STATE: IP INITIAL
AT+CIPMUX=0
OK
AT+CSTT="att.mvno","",""
OK
AT+CIICR
OK
AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","80"
OK
CONNECT OK

and
AT+CIPSHUT
OK
AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","443"
OK
CONNECT OK

If I use CIPSEND, how should my message be formatted to send lat or long in a way Firebase can interpret?
Or am I going about this in a convoluted manner? Is there an easier way? I appreciate any help/comment. Thank you.

Like you said, Firebase only accepts HTTPS traffic, which the Arduino Uno cant generate. Your HTTP requests first need to be sent through a proxy server that supports SSL, before being sent on to your Firebase database using a PUT or POST request. This site explains how to do everything from setting up your own proxy server to writing the GPS data (in your case) to Firebase. You may want to look at alternatives if this is too tedious for your purposes.

just remove "https://" its working


text:
Controlling an RC car using Arduino
I'm trying to replicate this: https://zhengludwig.wordpress.com/projects/self-driving-rc-car/ using pretty much the exact same controller and car.
I've soldered 4 wires to the controller, 1 for each direction. If I let the wires touch the ground on the controller everything works perfect. However, when I connect the wires to the Arduino nothing works. Sometimes left/right works for about 0.5 seconds then it goes back to doing nothing. Any idea on what the problem might be? Do I need to connect the controllers ground to the Arduino ground?
I've tried removing the batteries from the controller and connecting 3.3V and ground from the Arduino, which sorta works but I feel like it shouldn't be needed.
If I use the buttons on the controller while it's connected to the Arduino it goes either forward, right or forward+right.
The code I'm using to test everything looks like this:
void setup() {
  //Initialize the pins and serial
  pinMode(reversePin, OUTPUT);
  pinMode(forwardPin, OUTPUT);
  pinMode(leftPin, OUTPUT);
  pinMode(rightPin, OUTPUT);
}

void reset() {
  digitalWrite(forwardPin, HIGH);
  digitalWrite(reversePin, HIGH);
  digitalWrite(leftPin, HIGH);
  digitalWrite(rightPin, HIGH);
}

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

  digitalWrite(forwardPin, LOW);
  delay(4000);
  reset();
  digitalWrite(reversePin, LOW);
  delay(4000);
  reset();
  digitalWrite(leftPin, LOW);
  delay(4000);
  reset();
  digitalWrite(rightPin, LOW);
  delay(4000);
}

Images: https://i.stack.imgur.com/mCpcI.jpg

Can you measure how much current goes through the wire when grounded (A: 2 mA from measurements in comments) ? And the open circuit voltage between the controller's ground and the control wire?  (A: 3.1V, from 2xAA)
If the current isn't more than the 40mA per pin/100mA per port, 200mA total, and the open circuit voltage of the controller pins is less than 5V, then you should be able to connect the Arduino's output pins and ground to your controller's wires and ground.
If the voltages and currents are higher, then you would need protection to prevent damaging your Arduino.
The controller and the Arduino should share a common ground, but without a circuit and without the controller's voltages and currents, it is hard to tell exactly what is wrong.
Edit: Since the controller's open circuit voltage and short-circuit currents (3.1 V, 2mA max) fit within the Arduino's capabilities, you can wire them directly to the pin outputs, and make sure the controller and the arduino share a common ground.
You need a fifth wire between the controller ground to the Arduino ground to make the logic levels actually communicate between the two devices.
You likely also need some 5V->3V level shifting to isolate the Arduino's output levels from the controller's inputs.   Top of the line would be MOSFETS, but you could possibly use a voltage dividing resistor pair.  See the hints in https://arduino.stackexchange.com/a/419/6628

Can't measure the current, it just shows 0. Open circuit voltage between controller's ground and control wire is 3.1V. Controller is powered by 2 1.5V batteries btw.

At 3.1V, a 150 ohm resistor would limit the current to 20mA.   If you can put a 150 ohm resistor between the control wire and control ground, does the motor operate normally? Also can you measure the voltage across the resistor?  If it works with the 150ohm resistor, you could put the resistor in series between the control wire and the arduino input and use it as a current limiting protection resistor.

Didn't have a 150 ohm resistor, used a 330 ohm one instead. Voltage across the resistor is 0.54V. Every possible combination of directions now works. Does it matter if it's 330 or 150 ohm? Thanks for the help, this was more complex than I thought.

A 0.54V drop across a 330 ohm resistor is 0.0016A of current, which is well within the Arduino's I/O capability.  That same current through the 3.1V - 0.54V=2.56V voltage drop inside the controller implies it has about 1600 ohms of internal resistance, so you could rely on the controllers's internal protection you just measured and go without any resistor at all.  I assume you connected the common ground as well -- If so, that is the main improvement.   The resistor fiddling was testing that the controller would not overload your arduino.

Tried connecting the controller ground to the Arduino ground and that didn't change anything. It only works when I'm using the resistors.

Hmm.  If the controller ground is not connected, and the only connection between the two are the four controller signal lines, I'm confused.  Please post  a schematic and maybe a picture of your controller and  connections in your Question.  If only the 4 controller signal wires are connected between the two, the best I can guess is that it is storing a charge somehow relative to the other pins/device, which seems sort of magical and unreliable.

Added image of controller and arduino in the question. Can't provide a schematic for the controller unfortunately.

Ah.  The Arduino's output of 5V is probably feeding too much voltage into the controller, confusing it when you have the ground connected.  You will  probably need something like the level-shifting in http://arduino.stackexchange.com/a/419/6628

We have to add 1k resistors and 2k resistors as 330 ohms instead and follow the link below..!

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


text:
Receiving and transmitting messages simultaneously
tldr; I am writing a mesh network software using arduinos. I need to wirelessly receive, process, and transmit data, all simultaneously. I am aware of protothreads library, and the other software solutions, such as using interrupts, however, I am using relatively high baud rates. Thus each nanosecond is of the essence. Does anyone have any other ideas for me to achieve this? my initial thought is to have 2 Arduinos functioning as a single node in the mesh. One will receive while the other transmits.
I am currently using these antennas to receive and send messages. I want to create a mesh network of Arduinos using these modules. I found several mesh libraries for Arduino, but none seem to quite do the task I need. So here is my plan which I will work through using an example. (This is a very naive explanation, and has flaws in it's implementation. This is just to give off the general idea).
Each Arduino will be connected to a receiver and a transmitter. Let's say I have just 4 nodes in the mesh.

Node #1 -> Address = 0xA031
Node #2 -> Address = 0xB042
Node #3 -> Address = 0xC053
Node #4 -> Address = 0xD064

I send a message to node A through USB. Let's say the message is "SOS!"
Node A will reconstruct the message in the following way so that the new message is "0xA031_SOS!"
Now, Node A will begin transmitting this message continually. Let's say only Node C picks up the message. Node C will pick up the message and perform the following checks. (I will have 2 queues. A receiving queue and a transmitting queue. So as soon as a node receives a message, it will be placed in the receiving queue. And then it will run the following checks before sending it to the transmitting queue.)

Is the address a recognized/valid address? Handle appropriately
Is the address of the received message the same as the node's own address?
If address is same, check if the message received is the same message being transmitted currently by itself. If so, discard the message and tell transmitter to stop transmitting that message(This means that the message was originally transmitted to another node and came back, which means, it doesn't need to be re-transmitted any more). If the address is not the same, then send the message to the transmission queue.

Now the transmission will be handled the following way.

Check if there is anything in the transmission queue. If there is, transmit this message continually until told not to.
If the transmitter is told to not transmit that message any longer, that message will be popped of the queue.

So what happens? Node A continually sends a message. Node C receives the message and re-transmits. Because Node C was able to pick up Node A's message, it is in range and Node A will pick up Node C's message. Now, Node A will check the address, and say "oh, this is the same address as me." Then it will check if the message being transmitted is the same as what was received. If so, then it will tell the transmission queue to no longer transmit that message. (This almost like a form of back propagation).
Now I realize there are a million ways to have collisions and infinite loops. I will be eventually writing a software to resolve these things. But I hope I am giving off the general idea of how the network will work.
My questions:

As is clear from my explanation, because I am receiving and transmitting simultaneously, is there a way for me to do multi-threading? I am aware of protothreads and the other things mentioned in this post. However, all of them only offer a software solution, and not a hardware solution. So does anyone have any ideas of how I'd work around this? My initial thought is to have each node be composed of 2 Arduinos. Any one have any other ideas?
Also, does anyone have a better idea of implementing the mesh to do what I want it to?

I know this is a very convoluted, hefty post. Please let me know what I should clarify. Thank you.

It is not clear from your explanation why you would want threads at all. void loop() { process_snd_queue(); process_rcv_queue(); }. As long as you do not use blocking calls (see Blink without delay), that should work just fine.

Well, I am constantly receiving, and at the same time, I am processing the received data and transmitting data. The arduino either receives or processes or transmits the data. But it's not able to do this simultaneously. This wouldn't be too much of a problem, but timing must be maintained given the high baud rate I am using.

I hope I'm not completely missing what you're suggesting.

The Arduino has a hardware UART which enables it to send, process and receive, all at the same time. If you take care not to fill the send buffer, then Serial.print() returns immediately, and you can do other stuff while the data is sent in the background. Receiving is also done on the background: just call Serial.available() from time to time to see if you have received something.

Here is my "receive" code: http://arduino.stackexchange.com/questions/17021/unable-to-tell-if-error-is-from-receiving-or-transmitting-end
Given this, and my above explanation, when I receive a message with a certain key, I want to send it to another queue that will transmit that data. Now, won't my buffer lose information by the time the information is processed, sent from one queue to another, then transmitted? Especially since the transmission happens continually until the receiver receives a certain key.

The collision is that, the receiver receives something, sends it to process bytes, then process bytes will send it to the transmission queue. Which might continually transmit a message until a certain key is received. But the program will never return to "read" command in the while loop if it is still transmitting. Thus, I am still not quite able to piece together how I would do what you are suggesting. Can you please elaborate? Sorry if I'm totally missing it.

You can just piece together your two setup() and two loop() functions. But since you are using SoftwareSerial, the performance will disappoint you.

There is no point in listening and sending at the same time. Since you are sending at the same frequency as you are receiving at. So if you listen while sending, you'd receive exactly what you are sending. Which is pointless!

You cannot do this simultanously Because all the arduino ucontroller works at 8 bit RISC architecture. May be you can do it faster bu using assembly language

Also wireless protocols is not full dublex cammunication.


text:
How to set Delay on GSM shield?
I bought a Gsm module recently(not official arduino shield) and i connect it to Arduino uno. The problem (I guess) is , i can't set delay properly, the terminal send it too fast that i missed it or too slow even i set its baud rate to 4800 (I have tried it with many baud from 4800-to-115200).
I uploaded the code to Git ,with this address.
More details: For example when i enter d in terminal it act like this message came up : +CMTI: "SM",3 and it want to save it but it miss plus at first of it and it save CMTI: "SM",3,
After that it perform this : AT+CMGR=3 the terminal show the message in half size : +CMGR: "REC UNREAD","+9*********2","H/E.3D/1","16/02/28,00:27:02+14" which totally missed body part.
The weird thing is when i put some println on the program it miss more characters , and second weird thing is it missed more character in second run or i push d again.
I have tried to change the delays but no success.How can i fix it ? any help would be appreciated.
Edit:
If i make it simpler, when i use these code i get half message :
#include <SoftwareSerial.h>
SoftwareSerial serialGPRS(7, 8);
void setup()
{
  Serial.begin(19200);
  serialGPRS.begin(19200);
}
void loop()
{
  serialGPRS.println("AT+CMGR=1");
  delay(1000);
  while(serialGPRS.available()!=0)
    Serial.write(serialGPRS.read());
}

like: +CMGR: "REC READ","+9*******",".H/E.3D/1

The SoftwareSerial receive buffer is getting filled up and discarding characters. You are not reading fast enough from the buffer. Adding Serial.println() will slow down your reading even more. The simplest solution to this is to increase the size of the SoftwareSerial buffer from its default size of 64 bytes to 256 bytes (or smaller, depending on what works for you).
On a Windows PC, go to C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial. Open SoftwareSerial.h and change the line:
#define _SS_MAX_RX_BUFF 64 // RX buffer size

to
#define _SS_MAX_RX_BUFF 256 // RX buffer size

Save the file and try your sketch again.

It took so long so i changed the code, And there is no way i can test it ,but thank you.(I cant test it but i click it as accept).


text:
How to connect GPS to IMU?
I'm planning to connect GPS to IMU, Is't possible ? I tried my best to find an article that can help solving my curiosity.  How can i connect GPS and MPU to arduino uno?

Is not really connecting GPS to IMU, is more like you read GPS values, read IMU values and after apply what is called a sensor fusion algorithm.
One of the most common used sensor fusion algorithms is called Kalman filter (the Extended Kalman Filter more likelly). However, if you do not have some basis on control theory you may have more trouble in applying it.
here is a good example of use of this kind of sensors and fusion algorithms. It is also very commonly used in drones or autonomous vehicles.
The implementation will be specific to what you are trying to do.

thank you so much ! :) But how can i connect them to arduino ?

@GeorginaPattinson it depends on your sensor models. For instance this from Adafruit uses serial (Example tutorial). The most modern IMU digital combos usually use I2C/SPI interfaces (Example of MPU9150)


text:
Simple webpage serve with Arduino ethernet shield on SD card
I have been experiment with the arduino uno board from few days but can't seem to make it serve web page stored in SD card of ethernet shield.
If I print the contents of the file to serial it works properly, even embedding the HTML code works fine, but client.write() just produces a never ending garbage text of ÿÿÿÿÿÿÿÿÿÿÿÿ
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 115);
EthernetServer server(80);

File webFile;

void setup()
{
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);
    Ethernet.begin(mac, ip);
    server.begin();
    Serial.begin(9600);

// initialize SD card
Serial.println("Initializing SD card...");
if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;
}

Serial.println("SUCCESS - SD card initialized.");
// check for index.htm file
if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;  // can't find index file
}
Serial.println("SUCCESS - Found index.htm file.");
}

void loop()
{
EthernetClient client = server.available();  // try to get client

if (client) {  // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {
        if (client.available()) {   // client data available to read
            char c = client.read(); // read 1 byte (character) from client
            // last line of client request is blank and ends with \n
            // respond to client only after last line received
            if (c == '\n' && currentLineIsBlank) {
                // send a standard http response header
                client.println("HTTP/1.1 200 OK");
                client.println("Content-Type: text/html");
                client.println("Connection: close");
                Serial.println("starting to open htm");
                client.println();
                // send web page
                webFile = SD.open("index.htm");        // open web page file
                if (webFile) {
                    while(webFile.available()) {
                        client.write(webFile.read()); // send web page to client
                    }
                    webFile.close();
                }
                break;
            }
            // every line of text received from the client ends with \r\n
            if (c == '\n') {
                // last character on line of received text
                // starting new line with next character read
                currentLineIsBlank = true;
            }
            else if (c != '\r') {
                // a text character was received from client
                currentLineIsBlank = false;
            }
        } // end if (client.available())
    } // end while (client.connected())
    delay(1);      // give the web browser time to receive the data
    client.stop(); // close the connection
} // end if (client)
}

Sorry for the poor formatting, I just copied it from tutorial, please help me out.

Where are you viewing the results of client.write()? From a web browser? Have you tried opening the file before you start writing to the client, maybe in setup()? In case opening the file takes too long and is causing the process to time out? Show us the contents of "index.htm".

"ÿ" is character code 255, the erased state of a Flash/EPROM/SD. Check if your SD card format OK, 'index.htm' file is there, and your code can read it.

SD card is formated in FAT16, and I've been able to get the data of files on serial output | replacing client.write() to Serial.write() ; i.e. it seems file is accessible

Me I solve the problem by using : "/index~1.htm"
I see that the file name is seen like that using the cardinfo.ino from Example

because you copied a file with 4 characters length "html" extension to file system with max 3 chars extension


text:
First time set up- permission denied to usb port- ubuntu 14.04
I just plugged my arduino in and the light is on, but the blink test failed to upload. here is my error:
Arduino: 1.6.7 (Linux), Board: "Arduino/Genuino Uno"
Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

https://www.arduino.cc/en/Guide/Linux#toc9

@IgnacioVazquez-Abrams - can you turn that into an answer? We are trying to get our percentage answered up. :) Maybe with a bit of copy and paste, so it isn't link-only.

I did all the steps and it worked the first time.
Now I try to upload my second program and I get this Message 'avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied' i did this:
roquet@roquet-HP-ENVY-x360-m6-Convertible:~$ sudo adduser roquet dialout The user roquet' is already a member of dialout'.
roquet@roquet-HP-ENVY-x360-m6-Convertible:~$ sudo chmod a+rw /dev/ttyUSB0
roquet@roquet-HP-ENVY-x360-m6-Convertible:~$ ls -l /dev/ttyUSB*
crw-rw-rw- 1 root dialout 188, 0 Jan 20 13:12 /dev/ttyUSB0
roquet@roquet-HP-ENVY-x360-m6-Convertible:~$ but still get the 'permission denie

From the documentation:

Open Terminal and type:
ls -l /dev/ttyACM*

you will get something like:
crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).
Now we just need to add our user to the group:
sudo usermod -a -G dialout $USER

then:
sudo chmod a+rw /dev/ttyACM0

You will need to log out and log in again for this change to take effect.

Note that the preceding is old Ubuntu instructions. On modern distros that use ConsoleKit create the file /etc/udev/rules.d/01-ttyusb.rules containing the following and then reload the udev rules and replug the Arduino device:
SUBSYSTEMS=="usb-serial", TAG+="uaccess"

Great answer. On newer installations you do not have to reload the udev rules. Udev will watch /etc/udev/rules.d for changes. You do have to replug the arduino.

@ppareit what counts as "newer installations"? This doesn't work for me on Ubuntu 16.04 with or without reloading the rules (via sudo udevadm control --reload).

I think it didn't work because the board is identified as belonging to the "tty" rather than "usb-serial" subsystem. Anyway, creating the following udev rule worked for me instead:
SUBSYSTEM=="tty", ATTRS{idVendor}=="(vendor)", ATTRS{idProduct}=="(product)", ATTRS{serial}=="(serial)", SYMLINK+="ttyUSB.arduino", GROUP="adm", where (vendor) and (product) are taken from lsusb and (serial) is taken from the output of udevadm info -a -n /dev/ttyACM0|grep '{serial}'|head -n1.

At least with Ubuntu 16.04, I don't saw this problem on Mint 18.1. Glad to hear that you found a solution!

NAILED IT!!!! UPVOTED.  I have a 17.04 distro and the 1st solution was not persistent!

I followed these instructions and it doesn't work for me. Only thing different my device is on /dev/ttyUSB0. I am using Ubuntu 18 and Arduino Uno.

@CaioCaio: Which instructions? There are two sets.

@IgnacioVazquez-Abrams, I added my user to the usergroup and changed permissions on the /dev/ttyUSB0

@CaioCaio: Did you read the end of the answer, and the comments?

@IgnacioVazquez-Abrams, I did but I had misunderstood it, I read 'proceeding', not 'preceeding', sorry... let me give it a go

@IgnacioVazquez-Abrams, yeah, the second set of instructions didn't work either. My arduino IDE (v1.6) was installed thru Ubuntu software manager, I removed it and then installed it by downloading the IDE package from Arduino.cc (v1.8) and now it works. Thanks for the help!

'sudo chmod ug+rw,o-rw /dev/ttyACM0' or 'sudo chmod 660 /dev/ttyACM0' only gives read and write access to the user/owner (root in the ls output above) and group (dialout in the ls output above), while others are explicitly denied read and write access.

All you need to do is add yourself to the dialout group as described in the answer by Ignacio Vazquez-Abrams. This is done in the terminal by typing:
sudo usermod -a -G dialout $USER

You do not need to use chmod. This gives read/write access to all users and not just members of the group. Before attempting to connect, however, you must logout and log back in. Once you log back in you will be recognized as a member of the dialout group and will be able to open the device.

On Ubuntu 18.04, the only way I found the Arduino IDE installation to work straight out of the box, was using the documentation steps described here:
https://www.arduino.cc/en/Guide/Linux/
No changing groups nor permissions required.

Nothing above have helped me. When I have installed from file, from official site, it doesnt even start. Then I have installed Arduino IDE from "linux app store" and was working but have a problem like our friend from top. So I have uninstalled it and installed via terminal    sudo apt install arduinoand now it`s working. Cheers.

Or just use the chown command.
sudo chown <username> /dev/ttyACM*

This worked for me

This question has been asked many times in this site, and the same answer has been giving by another user.  I will cite Chris Stratton on this subjedt: This is a bad idea, in particular on a typical dynamically configured linux with udev or similar managing /dev nodes you will have to do it every time you connect the device. Add your user to the appropriate group instead, which is a lasting fix.


text:
How to remote control Arduino using an old 2.4Ghz toy remote controller?
I have been wondering how to remote control my arduino robot using an old 2.4ghz car toy transmitter which has 4 buttons, up down left and right.
I have the nRF24L01(+) 2.4GHz transceiver to use it as a receiver.
Is there anyway to detect the signals going out from the remote controller and use them to make my arduino works,
I am a newbie so i am sorry if any mistake.
Thanks guys!

You have two options:

Use an nRF24L01+ on the Arduino and dismantle the controller to rip out the innards, replacing them with another Arduino and another nRF24L01+.
Do not use the nRF24L01+, instead, rip apart the car and salvage the receiver from it, then work out how you can wire that to the Arduino.

The car's controller will not talk to the nRF24L01+. Yes, they may be in the same frequency band, but they do not talk the same language. After all, your WiFi is on the same band and that doesn't talk to the car, and your microwave, which is also 2.4GHz, doesn't sit and watch satellite TV all day. As you can see the 2.4GHz band is used by a huge number of devices (the band is actually getting quite crowded) and everything talked to everything else in the same band it would be utter chaos.

Its actually not entirely impossible that the existing system is on-air compatible with an nrf24l01 - many are based on workalike chips and have been reverse engineered.  But without recognizing it as one of the known schemes for compatible chips, or recognizing the chip used and sniffing its spi traffic to determine the scheme, steps like you recomend would indeed be necessary.  The fact that it has buttons and not proportional sticks may point to a cheap, unique chipset and not a distinct MCU and transceiver.

@ChrisStratton Not impossible, granted, but either not likely or, as you say, too much work to decypher the protocol. Chances are it's all just a CoB anyway.


text:
Are there any constants for default SPI port pins defined?
I'm writing a library which controls a device using SPI bus. For the communication I need to manually toggle the chip select pin. On most Arduinos SS pin is on D10, but there are also other models where it's different like D53 on Mega. Is there a way to know where it is? Like a global #define? I would like to avoid any pin configuration parameters in my library. At least for default configuration...

As jantje answered (he beat me by a couple of seconds :P ) just use SS; in the files pins_arduino.h (folder \hardware\arduino\avr\variants\your variant) you can see them all. BUT I highly discourage you to use it in your code. You can use it as a default value, but give the user the possibility to change it (otherwise he won't be able to attach two different SPI devices, for instance)

Welcome to Arduino SE Gamadril! About your question, SS pin can be any pin as that pin just needs to be toggled, no high speed data transfer is done with that pin.

Yes there are. They are defined in pins_arduino.h Below the pins for the yun.
// Map SPI port to 'new' pins D14..D17
static const uint8_t SS   = 17;
static const uint8_t MOSI = 16;
static const uint8_t MISO = 14;
static const uint8_t SCK  = 15;

Use SS MOSI MISO and SCK in your code

you was some seconds faster, so get your point :)

This is defined in the platform variant specific file pins_arduino.h in the variants folder (\hardware\arduino\avr\variants). Each platform variant (standard, mega, leonardo etc) gets their pin definitions set here. For instance the mega:
static const uint8_t SS   = 53;
static const uint8_t MOSI = 51;
static const uint8_t MISO = 50;
static const uint8_t SCK  = 52;


text:
Start timer when pins connected
I have switch is a line connected to Digital pins 1,2,3,4,5 . When pins 1 connects, I need a timer to start. as the rest connect i need it to mark the time in the console output of each one and End on the timer on connection to pin 5. ex
START:
0.00
1.43
2.12
2.94
3.89
END

Also is there a way to Save the data to a log (.txt or whatever) If not its fine but I need to record results.
(This is for a school project)
THANKS!

Why two pins per switch? You only need one.

my bad, Thats what I meant. Sorry.

@DisplayWord Please update the question too to reflect what pins are used and how the buttons actually are connected.

@Avamander Done

I will not give you code, only clues on how to write the code yourself.
The way to tackle this is to (at first) remove the Arduino from the equation. Replace it, instead, with you.
Imagine you are doing the timing yourself. How would you go about doing it?
This is how I would set about the task:

When the first button gets pressed I would look at the clock and jot down the current time.
When the second button gets pressed I would again look at the clock, and subtract the first time from the current time to find out how much time has elapsed. I would jot that down.
When the third button is pressed I would do the same again - look at the clock, subtract the start time, and jot down the difference.
And I would keep going until I had run out of buttons.

So now you need to find the right code to read what buttons are doing, get the current time, and finally send the times somewhere useful.
For all those there are many many many examples on the web.

The point of the experiment is to get the most accurate results as possible (Im using photocells and lasers). I have no Idea how to code the arduino. I was give one with the software by my teacher.

But i will keep this in mind

+1 for the way of explaining the replacement of a person and the logic

Yes, Did help my understanding. Thank You!

Are you familiar with interrupts? The best/most efficient way to do this is with pin interrupts on each input pin (and make sure your switches are wired correctly and debounced).
Unfortunately, within the Arduino libraries, there are only two pin interrupts (0 and 1), which correspond to pins 2 and 3.
You have two options:
Use a polling solution. Use one pin with an interrupt to start the timer (save the value of millis()) and then poll the other switches in a loop, capturing the millis() value at each switch closure.
Alternatively, the ATmega can fire an interrupt when any pin in a port changes, but IIRC this isn't built into the Arduino libraries and requires direct register manipulation.


text:
How to use a Bi-color matrix led 8x8 with 24 pins?
I've just buy this 8x8 LED matrix WLG M20088A/BEG and I'm trying to light all the LEDs in one single color (green) but I don't understand how the 24 pins work for this specific model.
I know that every manufacturer makes different models. Does anyone have any experience with this particular model?

Take a closer look at the device schematic diagram, which I copy below. It will tell you how each of the LEDs are wired. For example, the green LED on the upper-left corner (which I marked with a green circle) has its anode (positive terminal) wired to pin 5, while its cathode (negative terminal) is wired to pin 1. Can you see that?

To light up that LED (green LED on the upper-left corner), you must apply voltage (with limited current), to pins 1 (-) and 5 (+). If you wanted to light up the red LED at the same position instead, you should apply voltage to pins 1 (-) and 20 (+).
To light up all LEDs of a given color, you'll have to connect pins 1, 2, 3, 4, 21, 22, 23 and 24 to the negative terminal of your power supply. These are the LED common anodes. They are called common because they are shared among each pair of red and green LEDs. If you choose to use the red LEDs, you'll also have to wire pins 13 through 20 to your positive supply. On the other hand, if you pick green, you'll wire pins 5 through 12. These are the LED cathodes.
Don't forget to wire a current limiting resistor in series with each LED.

It seems to be:
Row 1 - 8 --> common cathode pins per row.
To light up a whole row, you must connect row X pin to Gnd and all green or red columns to High (Vcc). Do not forget to add a resistance in series!

authors: هاني البخاري


text:
questions about sketch
int k ;
int q ;
int f;//pot

void setup() {
  pinMode(k, OUTPUT);
  pinMode(q, OUTPUT);
  pinMode(f, INPUT);
}
void loop() {
  zzf();
}

void gf()
{
  int a = f;//test the conditions of f and store in new variable int a
  if (a == 80)//if a reads 80 then increment a by 1
  {
    ei();//run the ei() function
  }
}

void ei() {
  int k = 3;
  int a = Serial.read();
  {
    digitalWrite(k, a);
  }
}

void zzf() {
  for (f = 0; f < 80; f++) {
    analogWrite(q, f);
  }
}

You have now changed your question, but I'll give you a hint. Learn C first. Then look carefully at the errors. They are telling you exactly what is wrong; a little bit of searching through StackOverflow will help you immensely.

And may I suggest to give understandable names to functions? Maybe to you they are so meaningful, but I bet that if you'll read this sketch in a week you won't understand it at all. It's just an advice :)

A practice in writing gibberish? What's the problem with giving functions good names?

Which is the question?

@fabrosel the question was answered

There is no question, this should be closed.

@jai Insulting and other vulgarities are not tolerated on Stack Exchange.

Lean the proper C syntax. This is completely wrong:
void gf()
int a = f;//test the conditions of f and store in new variable int a
{

And this is just as wrong for the same reasons:
void ei()
int k = 3
int a = Serial.read();
{digitalWrite(k, a);}

Majenko is right. The { comes after the function name and arguments, not a few lines further on.

@Majenko telling me what i did wrong does not contributes towards the help, the ide debugger already tells me that theres is something wrong and thats what im looking for help on here

And I have told you that your syntax is wrong and that you need to learn the right syntax. Look at your code and then look at someone else's code and spot the difference. That way you will learn.

@NickGammon thank you for being helpful, im not sure why this guy just dint lead of with you very simple approach of helping. i did noticed not what i was missing i was stuck on the fact that i had already used those brackets but i failed to see how i forgot to initialize for the function itself

@Majenko like i said telling me whats wrong is what the ide debugger did, i did not wanted any one to reiterate that but to point to me in detail what i did not understood about the debugger

@jai This is the first time I'll say that you need to open a C(++) tutorial and start from the beginning and learn what's C(++)'s syntax. I can tell that you need to put { after a function name and (). For example void learnthesyntax(){ <code here> } but it won't help you much without you understanding what's right and why.

updated my original post

@jai You've been so busy arguing about the answer that you haven't actually learned anything, have you? Look at your ei() function and tell me what is wrong with it.

If you write "ei()" the compiler sees it as the calling of a function, but the compiler doesn't know where is the function defined, so is say ei' was not declared in this scope. Since compilers are clever they search for the body of the function after "ei()" but it doesn't find the braket: here comes the second error you get expected initializer before 'int. As Majenko said you should learn the syntax, and then learn how to understand the esoteric language of the compiler. I'm still learning so don't worry.

@Majenko yeah its called cant focus with you bashing on the kid rather then focus on keeping the bashing away from the post and focus on being understanding, but yes thanks for the point out, i just noticed

@FrAxl93 thanks for the looking out...i just got it to compile, now i gotta learn about using Boolean Op in my conditionals in order to tell if a function is currently being exercise i can have the program do other functions if one of the other functions are being bool as TRUE


text:
Clock drift - is the precision of the crystal the only culprit?
I've a wall clock (sorry, code's a mess, look for updateClockVars) which makes use of the Timezone library (and ultimately Time). Nothing fancy, call millis() every loop; turn to Hrs, Mins, Secs; display on LEDs.
The magnitude of the drift I am seeing on my 2 Arduino Pro Mini - compatible boards - up to ~8% lag, not a typo - blows my mind. Replacing the 16MHz quartz with one bought at a local retailer didn't help much (~33% improvement). Is something else at play here?

Can you please extract from the code only the part regarding time? There are 300 lines and it's difficult to understand everything.

Didn't check the whole code, but here is an idea: Since your LED strip is quite long, the NeoPixel library may be blocking interrupts for too long when you strip.show();. You may then be missing timer interrupts. Try with a much shorter strip and see if the problem persists.

Much better idea would be using a RTC module (the easiest way to be honest).

I get 40-60 loop iterations per second. I don't keep track of time on my own, I ask for millis(). RTC: even having read so many suggestions for it, I still didn't catch WHY that is better - it's a quartz either way, and if that's not the only relevant thing - than we have an answer to the original question. @frax93: updateClockVars(). All else is just setting the LEDs based on the acquired values.

I have read some things here that I didn't understand but may be relevant (or not even true). Author claims PWM can keep more acurate time that timers and main clock (!?), and having read that "Using the millis() creates issues using some functions such as delay()".

I would encourage you to have a look at the code behind millis(), micros() and the Timer Overflow ISR. Please notice the accumulated error and the leap milli-seconds. It is possible to adjust the Timer handling and get within better accuracy. Please see Cosa Clock and Calibration Tools. Start here: https://github.com/mikaelpatel/Cosa/blob/master/examples/Tools/CosaClockCalibration/CosaClockCalibration.ino.

@EdgarBonet Still trying to wrap my head around the PPM value. I deleted my comment, as was wrong.

The problem is the interaction between the interrupt handler that updates the value for the millis() function and the neopixels show() function.
To maintain the counter for the millis() function a interrupt is triggered approximately every 1.024 ms.
When the show() function is called all interrupts are disabled to get the precise timing needed to send the data to the neopixels.  For a 60 led strip this takes about 1800 microseconds (60 leds * 24 bits * 1.25 us per bit) so at least one interrupt is skipped each time you update the display.
This page has details about how the millis() function works.

“at least one interrupt is skipped each time you update the display”. This is incorrect. See my answer.

TL;DR You're doing it wrong. Use RTC.
Ok, longer explaination is required here. millis() is not accurate and here is why.
First, grab official Arduino source code from their Github repo.
The file Arduino-master/hardware/arduino/avr/cores/arduino/Arduino.h
contains few interesting macros (I'm pasting grep output here):
Arduino.h:#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
Arduino.h:#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )
Arduino.h:#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() )

At 16MHz clockCyclesPerMicrosecond() will evaluate to 16. Keep this number in memory.
Those macros are used in Arduino-master/hardware/arduino/avr/cores/arduino/wiring.c:
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

// the whole number of milliseconds per timer0 overflow
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)

MICROSECONDS_PER_TIMER0_OVERFLOW macro is evaluated as (64 * 256)/16 -  a dodgy looking 1024. Look how they round it down to calcuate MILLIS_INC.
Let's assume that you run your Arduino with ideal main clock signal.
At 16MHz main clock, the timer frequency is 1.024kHz, not 1kHz. This results in 2.4% inaccuracy. You can get away with that in most cases, but not when you're building a clock.
This 2.4% error is best case. Your main oscillator is not 16MHz - it has it's own inaccuracy, that is unknown and it sums up.
You should use an external, accurate time reference provided by RTC module. When assembled properly, they guarante low time drift, temperature compensation and other goodies. Be smart - use RTC. :)
If you are scared of I2C RTC modules, you may find my tutorial
and another tutorial on MCP7940N RTC module. Know-how is applicable with other RTCs as well.

Thank you. I had assembled a DS1307 module, but only used it for sync on startup, as in the timeRTC example. Ditched it in favor of NTP via an ESP8266 (so the Arduino is I2C slave now).

I hope you aren't calling an NTP node every second. You might get IP blocked if you keep doing that. They are supposed to synchronize your clocks, not replace them.

−1 because you visibly do not know what you are talking about. The timer frequency is 1/1.024 kHz, not 1.024 kHz. (the period is 1024 µs). Most importantly, this does not imply millis() is inaccurate: the extra 24 µs are accounted for: see timer0_fract and FRACT_INC.

Expanding on my previous comment...
As I said before, I suspect the NeoPixel library to be blocking
interrupts for too long when you strip.show(). If a timer interrupt
fires while interrupts are blocked... it's not a big deal: the interrupt
request is put on hold and serviced as soon as interrupts are enabled
again. If two timer interrupts fire while interrupts are blocked...
you have a problem: the interrupt service routine will be called only
once, and your clock will miss a tick.
Craig has worked out the timings in his answer: the timer interrupt
fires every 1.024 ms, and NeoPixel blocks interrupts for
1.8 ms. So it is perfectly expected that, from time to time, you
will have two timer interrupts within this 1.8 ms window.
Here is a quick hack that could solve your problem: if you
strip.show() right after a timer interrupt is serviced, then only
one more interrupt should fire during the subsequent 1.8 ms window,
and you should be fine. So you could simply add this right before
strip.show():
/* Wait for a timer interrupt to be serviced. */
uint32_t lastMillis = millis();
while (millis() == lastMillis) /* wait */;

A possibly better solution would be to avoid blocking interrupts for so
long. NeoPixel blocks them in order to comply with the very tight timing
requirements of the WS2812 LEDs. But it turns out the WS2812s are not
nearly as picky about timings as their datasheet suggests. You can drive
them in a more relaxed way, with interrupts enabled except for 1-bit
durations, and they still work fine. For a detailed explanation and
sample code, see NeoPixels Revealed: How to (not need to) generate
precisely timed
signals.
A third solution would be to follow the general advice given here and
grab an RTC. However, although it certainly is a good and clean
solution, I have to admit I completely agree with your comment “I still
didn't catch WHY that is better – it's a quartz either way”.

Alternatively, you could use a second timer that ticks slower, and implement your own version of millis. This function could also implement some kind of calibration. By measuring how much the clock is of after a longer period, you can see if the 16mHz clock is too fast or too slow, and by how much. You could use this value in your millis implementation to get better accuracy.


text:
Need help figuring out the pinout of a seven segmented display
A friend of mine gave me a 2in. 4 digit seven segment display. But when I sat down and looked at it, I found it has 7 pins on one side and 5 on the other and no indicators of its pinout on it. The only information I could gleam from it was the (presumably its model number) which said "PARA LIGHT A-5V4G-12-U1 H H0615". I searched online for it but only found ambiguous information that didn't help me. I have a feeling this is a fairly easy question, if so: sorry I am a noob.

Do you have a 1k resistor and a DC power source handy?

Without an image of the display, I'll have to guess. With 12 pins in total, what you most likely have is: 8 pins for 7 segments and the decimal point, and 4 COMMON anodes or cathodes, a detail you will have to discover yourself. This process requires a power source that can safely light LEDs. A multimeter in diode test mode will do since theres usually about 2 V across the probes and some internal resistance, enough to light up the LEDs in the display, though they wont be very bright. I will try to list the minimum number of steps needed to determine the pinout using this method.

Using a multimeter set to diode test mode, place the red probe on any pin (though its good to start at the edges). Now lazily run (i.e. make contact) the black probe through the remaining pins. If the display is a common anode display, you should see the all the segments of a particular digit (not different digits) light up in sequence.
Else, keep running the black probe through the pins until any segment at all lights up. Hold the black probe on that pin that caused the segment to turn on. Now run the red probe through the other pins. If all the segments of a particular digit light up in sequence, this indicates a common cathode display.
Another possibility is that no segment lights up at all, despite steps 1 & 2. Substitute the red probe, where it is held steady, for the black probe. Run the red probe through the remaining pins. If all the segments of a particular digit light up, then the display is a common cathode display.
On the other hand, if no digit's segments light up sequentially while running the red probe through the pins, but at least one segment of any digit lights up, then hold the red probe steady on its current pin, and run the black probe instead through the other pins. If all the segments of a digit light up in sequence, then you have a common anode display.

Take note of the pin that was held constant, in any of the cases above.
Now that you know what kind of display you have, you now need to discover the pinout for the segments and common anodes/cathodes. Get paper and pen so you can label each pin with its function. Create a table with pin numbers in one column (pin 1 - 12) and the pin functions (which you will find out) in the second column.

This image shows the segment labels. During the testing above, one
probe (PROBE A) was held steady on one pin while the other (PROBE B)
was run through the other pins. This caused all the segments of a
digit to turn on. The pin connected steadily to PROBE A is the COMMON pin for
the digit whose segments lit up. So in your table, Pin xx = COMMON
for Digit yy.
To get the COMMON for other digits, move PROBE A to another pin and
run PROBE B through the other pins until another digit has all its
segments turned on in sequence. The pin connected to PROBE A is the
COMMON for that digit. Include this in your table. Repeat until you
have identified the COMMON for each digit.
Finally to get the segment pins A - G and DP, place PROBE A on any of the COMMONs you have in your table and run PROBE B through the other pins. Each time a segment lights up, the pin connected to PROBE B should be associated with that segment's label in your table. E.g. if segment C lights up when PROBE B is on pin 10, then the table should have something like pin 10 = C. Keep going until you have all the segment pins identified.

An ok answer, +1, except in first bullet you should mention (1) that if no LED lights up then try reversing red and black probes, and/or other pin combinations and (2) the LEDs won't be particularly bright using this method, and it may be necessary to reduce room light slightly

@jwpat7 ok...editing now...

Nice step by step how-to. +1


text:
How to write a sketch when adding more devices to an I2C data line?
I am building a weather station, using a battery-operated outside unit, that transmits data from a DHT22 sensor to a unit inside my house.
The inside unit is using I2C communications from my Arduino Uno to my LCD display.
I would like to add a BMP180 sensor which also uses I2C communications.
My question is, how would you write a sketch to incorporate both the BMP180 sensor and the LCD display on to one I2C line?

Have you tried combining code for polling the BMP180 and the LCD yet? There's really nothing special about doing both at once, as long as both libraries are well-written.

What's the problem? If they both have different addresses, read from the sensor, then write to the LCD.

Yes you can connect multiple devices on one I2C bus. Every device on the bus needs to have its own address. Some libraries have the default address included. Some do allow to change it. Others don't. For example the SE95 temperature sensor (page 10) does allow for setting a few bits of the address allowing more than one sensor on a bus.
You can use the Wire library from Arduino to request data from I2C. When you want to pull data from a sensor, you have to send a command depending on the specs than request data from the address.
Example: for the SE95 address 0x4F (you can repeat this for any address you have a sensor on your bus) the SE95 ranges from 0x49 to 0x4F depending on the pin settings:
//Please note that the example is not complete because Wire has to be loaded and initialized
byte address = 0x4F;
byte read1;
byte read2;
Wire.beginTransmission(address);
Wire.write(0x00);
Wire.requestFrom(int(address), 2);
if(Wire.available()) {
  read1 = Wire.read();
  read2 = Wire.read();
}

So depending on the libraries, this would be quite easy.

Like Nick Gammon said, they have different addresses, so there shouldn't be a problem. Connect their SDAs and SCLs together, with the necessary pull-ups.
The libraries you are using should handle the low-level reading and writing. Proceed as though they are any 2 devices connected to your Uno. Print to the LCD as usual, and poll the sensor with library functions.


text:
How to serially transfer/read an image to Arduino
I am using Arduino Uno and the image size is 12.7 kb. I want to read a jpeg image from computer and convert into bitmap in arduino. Later on it will be implemented using SD card.Is it possible to read a .jpeg image from computer to Arduino using serial communication? If yes, then how?

Which Arduino? How big is this image? Why do you want to do this? Please read How do I ask a good question?

This is almost certainly a bad idea.  On the more conventional Arduino boards, you could only accomplish it by streaming the image from the source, through whatever processing you are doing and to the permanent storage, as you just don't have the on-board RAM to hold more than a tiny part of it at any time.  Depending on the processing you want to do you may need simultaneous access to more of the image than you can fit in memory at once, unless you can "rewind" the source or destination to multiply process it.  Much better to do your conversion on the real computer!

@ChrisStratton I am not going to implement this idea in the final project. All I am asking is for experimenting purpose. And besides the final project will be on Arduino Mega, one entire image can be loaded from SD card, processed and written back to SD card. I just want to know if right now I can do with serial communication or not.

You can send anything you like through the serial port. It is just 8-bit raw data. The onus is on you, however, to implement a suitable high level protocol with which to transfer the data.
One important thing to bear in mind though: JPEG is a highly compressed complex image format. I am not aware that anyone has ever managed to squeeze JPEG decompression into a lowly Arduino. Instead you will need to use a decompressed image format such as BMP, or do the decompression on the computer before-hand and send the raw RGB image data over the serial instead.

As an addendum to this: I wrote a crude JPEG decompresser for chipKIT boards. It requires about 100KB of RAM to operate, so no chance of it ever working on an Arduino.

Of course you can, but as stated in the comments and in the other answer JPEG use a complex algorithm to compress the images, and most computers have a dedicated hardware to perform the cosens discrete transform. Anyway the answer to your question is yes, and it's not hard.
You just have to split the image into bytes, send them through the serial port and make Arduino read and save them into an array. To avoid errors create a protocol that can decode what are you doing.
For example:
0b1111000 for 3 times = Start sending
0b00011000 = new line
and so on..
The first thing that come in my mind is to use the pySerial library, that can automate the process. Python is perfect for prototyping: open the image (maybe using the numpy library instead of using lists) and with a for loop send every byte over the serial port in according to the protocol you created.
On the Arduino just code the protocol to understand every bite and save the image in an array.