text:
SOLVED -- Switch PIN, Also Trigger Other Pin in Arduino
I would like to know.
I have Pin 6, 7, 8 and 9 as INPUT_PULLUP. I have switch to each other pin. Why when I press switch at PIN 6. SOMETIMES PIN 7 also getting input. Other case, also when I press switch at 7, other pin also trigger. Why?
This case is random. Sometimes everything is ok when I press 10 times, but after that other pin also trigger. Another case only 4-5 times press, then other pin also trigger.
I use switch on/off not temporary switch.
How to fix this? Is it common problem with arduino?
UPDATE
Program. (Simple Program)
int led1 = 1;
int led2 = 2;
int led3 = 3;
int led4 = 5;

int switch1 = 6;
int switch2 = 7;
int switch3 = 8;
int switch4 = 9;

int led = 13;

//int counter = 0;

void setup()
{
  // put your setup code here, to run once
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(switch1, INPUT_PULLUP);
      pinMode(switch2, INPUT_PULLUP);
      pinMode(switch3, INPUT_PULLUP);
      pinMode(switch4, INPUT_PULLUP);
      pinMode(led, OUTPUT);
}
void loop()
{

if (digitalRead(switch1) == 0){
  digitalWrite(led1, HIGH);
  }

 if (digitalRead(switch1) == 1){
  digitalWrite(led1, LOW);
  }

if (digitalRead(switch2) == 0){
  digitalWrite(led2, HIGH);
  }

 if (digitalRead(switch2) == 1){
  digitalWrite(led2, LOW);
  }

if (digitalRead(switch3) == 0){
  digitalWrite(led3, HIGH);
  }

 if (digitalRead(switch3) == 1){
  digitalWrite(led3, LOW);
  }

if (digitalRead(switch4) == 0){
  digitalWrite(led4, HIGH);
  }

 if (digitalRead(switch4) == 1){
  digitalWrite(led4, LOW);
  }

digitalWrite(led, HIGH);

delay(1000);

digitalWrite(led, LOW);

}

Schematic

My Circuit is simple as like that for the input. For the output only to led, resistor and ground.
I found similar case http://www.instructables.com/id/Arduino-Push-Switch-Debouncing-Interrupts/

On the website, He said, "The problem with this setup was when the
  button was pressed the interrupt was being called multiple times and
  even toggling other buttons. Why was this happening? It is caused from
  a switch bouncing feedback."

Is there any solution without modifying the hardware?
SOLVE
The problem is the wire.
My wire for switch is jumper cable, and each other closer (touch) to each other cable. I try to separate, and works. There is no other pin will be trigger.

Can you post a schematic or a simple diagram of your circuit?

Is what a common problem? With no schematic, and no code, your question doesn't make any real sense. Please read How do I ask a good question?

@Nateowami, I have been updated my question with code and schematic. Do you have any experience with this? Because I think it should be something wrong with the Arduino.

@NickGammon I have been updated my question with code and schematic. Do you have any experience with this? Because I think it should be something wrong with the Arduino.

Have you checked your wires to make sure the wires for led2 and led3 don't touch? If they're touching that could make them sometimes light the wrong one. Also, check the wires for switch2 and switch3. What kind of switch are you using?

@Nateowami I checking the switch2 and switch3 with multimeter and it doesn't connected. I use lamp switch (on/off) not temporary switch. Simple question: It should be perfectly work, right? I also has different behavior, When I switch on, other lamp also on, less than 1 sec. Check my video https://www.youtube.com/watch?v=s6CxPuQya0g

Lose the delay(1000)

@Majenko what do you mean? I didnt understand. Sorry.

I mean delay is always a bad idea regardless of what you are doing - especially when you are reading switches and expecting them to respond in a normal fashion.

I would suggest reading this article https://hackaday.com/2015/12/10/embed-with-elliot-debounce-your-noisy-buttons-part-ii/ (and also part one). Elliot covers all about switches, switching noise and how to solve the problem (debouncing) in software.

Your question says you have “Pin 2 and 3 as INPUT_PULLUP” but in the code pins 2 and 3 are used as outputs to LED2 and LED3.  Please edit the question and remove the inconsistency. Also remove “interrupt” from the question title because it appears the question has nothing to do with   interrupts.

Why when I press switch at PIN 2. SOMETIMES PIN 3 also getting input. - you have LEDs on Pin 2 and Pin 3, not switches. Thus your question doesn't make any sense. Please edit the code, and the schematic, so at least there is some internal consistency.

@NickGammon I changed my post already.

You may be getting switching noise between the button wires, which is low-level and brief, but with no debouncing, it could be just enough to cause the effect you're seeing.
I'd suggest 1) writing a short function that debounces and reads any button; and 2) using if/else statements instead of testing each button twice.
A quick test is to hold one pair of wires closer together or farther apart from each other while you press one of those two buttons, and see whether the distance apart changes the effect. If it does, you've found the cause.


text:
Using millis() to time the start / stop of a DC motor
I'm trying to use a DC motor with pinion engaged to a rack gear, and have that motor move a distance, save the distance, delay, reverse, and travel back the same distance from where it started, delay, do it again. I want to start/stop the initial save with a button push, then from those saves, loop the motor movement.
I have considered using a Hall effect sensor or reed switch to count, but it seems a software interrupt or timing is easier using millis(). I researched and found that millis() cannot be reset, so I'm wondering if this is possible.
I haven't started a sketch, but I got this idea from the BlinkWithoutDelay example sketch included with the Arduino IDE. Like, have the motor positioned at "home" position, button push, start the timer, motor travels to end of work piece, stop the timer, save that forward distance traveled into a variable, reverse the motor, (at this point the timer would be at 0 again for the reverse travel) travel back to "home" save that reversed distance traveled into another variable with a button push, and then use these start/stop values in a loop. So I would save the values with a button pushes, then just loop that.
Or I'm thinking about putting an if or while button push outside the loop with a nested counter++, eyeballing the motor travel, once it gets to where I want it, save those counts in variables, then using them in the loop to analogWrite() to the motor.

Comments are not for extended discussion; this conversation has been moved to chat.

Comments under a question are for clarifying the question, and for the OP to respond to such requests for clarification. For example "what type of Arduino do you have?". They are not for extended debugging of the issue. This is not a forum. If you (Jim) want to clarify your question please edit the question to do so.

You can't reset the millis() function, but you can count the amount of milliseconds and stop when necessary: beware though, the positioning might not be as precise as you wish and you have to consider the error will accumulate on the long run.
Nonetheless here is the code:
uint16_t duration;
bool direction = true;
void loop() {
  if (duration != 0 and !buttonPressed()) {
    // running back and forth if setup and no "finish" button detect
    uint16_t start = millis(); // reset the timer
    startMotor(direction);
    while (millis() - start < duration && !buttonPressed()) {
      ; // keep going
    }
    direction = !direction; // reverse direction
  } else if (duration == 0) {
    // your motor positioning setup
    while (!buttonPressed()) {
      ; // wait for button to start positioning
    }
    uint16_t start = millis(); // ask for time
    startMotor(true); // run the motor cw
    while (!buttonPressed()) {
      ; wait for button to end positioning
    }
    duration = millis() - start; // store duration
    direction = false; // reverse motor direction
    // next time loop() is executed the motor will go back to home
  }
}
bool buttonPressed() {} // define this to determine if the button has been pressed, safer if you use an interrupt
void startMotor(bool cw) {} // define this to run your motor clockwise or counterclockwise

Comments are not for extended discussion; this conversation has been moved to chat.

This is a great answer; I don't see the fault and it should be accepted. The first thing the answer does is point out the misunderstanding about millis() not being reset-able, and the second benefit is an example of using millis() properly.

source: Stack Exchange

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

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

sort: votes


text:
Arduino analogWrite source code explanation
The source code for the analogWrite function looks like this:
void analogWrite(uint8_t pin, int val) {
    ...
    sbi(TCCRnA, COM0x);
    OCRnx = val;
    ...
}

Where n is which timer (0, 1, 2...) and x is which pin is controlled by that timer (A, B).
This doesn't make sense to me, because the ATmega328P datasheet says that the bits TCCRnA.WGM0[1:0], and TCCRnB.WGM0 need to be set up as well.
Datasheet
Obviously the above code works, but how, with the missing bit settings?

Look in init().  All that stuff gets set up ahead of time.  All they're doing here is setting the one COM bit to enable the pwm on that pin.

Thanks. I suspected that, but I couldn't find where it was set up. If you want to write that as an answer I will accept it.

Your statement “the Compare Match Interrupt for the pin [...] is required for the Waveform Generator to function” is incorrect.

@EdgarBonet You're right. I edited the question.

Look at the init() function in wiring.c.  All of the timers get set up there depending on which chip is selected.  I don't know if some might also be done by initVariant().  But all it leaves for analogWrite to do is set the bit in the COM register to enable the PWM.

because the ATmega328P datasheet says that the bits TCCRnA.WGM0[1:0], TCCRnB.WGM02, and TIMSKn.OCIEx all need to be set as well.

they use different meanings for the word "set".

the datasheet is saying that you need to SET UP those bits for the appropriate mode. "SET" here means both set or clear, as appropriate.
the code, poorly written actually, sets those bits that need to be set, and let the rest is in their default / reset state, presumably cleared. a more robust way would have been to explicitly clear those bits.

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


text:
How can I make this button toggle the position of a servo?
I am trying to make something so when I press the button it sets the position of the servo to 50 and then when I press it again, it sets it to 150. The button is momentary not a toggle switch. This is what I have come up with so far. I would also like to account for button bounce. Hope someone can help. Thanks in advance!
#include <Servo.h>

Servo myservo;  // create servo object to control a servo

// variables will change:
int pos = 0; // variable to store the servo position
int buttonState = 0; // variable for reading the pushbutton status
int button_mode = 1; // Variable for the button's current state.
// button_mode = 1 when the button is up, and 0 when the button is pressed.
// This variable is 'static' and persists because it is declared outside a function.

void setup() {
  myservo.attach(8); // attaches the servo on pin 9 to the servo object
  Serial.begin(9600); // Initialize the Serial port at 9600 baud.
  pinMode(9,INPUT); // Set Digital pin 9 to an input so it can monitor the button.
}

void loop() {
  buttonState = digitalRead(9);
  if ((digitalRead(9) == LOW) && (button_mode == 1)) {
    // Check Digital pin 9 to see if it's pressed.
    pos = 150; //set servo position variable to 150
    myservo.write(pos); //set servo postion to 'pos'
    delay(1000); // wait 1 second
    button_mode = 0; // Button was up before, but is pressed now. Set the button to pressed
    Serial.println("Button has been pressed."); // and report that to the serial monitor.
  } else if ((digitalRead(9) == HIGH) && (button_mode == 0)) {
    pos = 50;
    myservo.write(pos);
    delay(1000);
    button_mode = 1; // Button was down before, but is released now. Set the button to
    Serial.println("Button has been released"); // released and report that to the serial monitor.
  }
  delay(100); //small delay to account for button bounce
}

The code is not well structured. Here is what I would do:
if (button_pressed()) { //test to see if button is pressed
  button_state +=1; //increment button
  if (button_stat & 0x01) {//if lsb set
    myservo.write(SERVO_POS1); //set servo position 1
  } else {
    myservo.write(SERVO_POS2); //set servo position 2
  }
}

You can debounce if you wish in button_pressed().

Do something like this:
int angles[2] = {0,180}
bool state = 0;

then:
if(button == PRESSED)
  state = !state;

finnally, to control the servo:
Servo.write(angles[state]);


text:
Control the "TV remote"
My idea is to use Arduino to control the TV remote. Not make the Arduino become a TV remote, I want to make an Arduino that can touch button of a remote control.
Any ideas?

A few more details? Physically touch the buttons? Electrically close them? Which remote?

Please read How do I ask a good question? - people are likely to vote to close this as too broad. Asking if anyone has "any ideas" is a rather broad question. Try to narrow it down to something more answerable.

Sending the signals directly will be a far better idea.

I agree with Chris, if you've got a (unconventional) design choice or limitation, you may want to expand on it and explain why. There may be other options which fit your limitations. In order to solve a problem, we'll first need to know what problem (and why).

My rather fancy solution would be to make a 3 axis device with x and y controlled by stepper motors and z a simple solenoid to press the buttons.
For extra marks you could add a camera and try to recognise the buttons in software so any remote would work.
How do you plan to control the arduino?  Perhaps with a remote controller?

Nice answer. Using a remote to control the Arduino that controls the remote certainly is an interesting idea.


text:
NodeMCU run sensor code while listening for wifi input?
Is it possible to have code running while also listening for local inputs via ip address? I thought it would go in the 'while' portion but I presume that only responses when the ip is loaded.
void loop() {

  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  while (!client.available()) {
    delay(1);
  }
  String query = client.readStringUntil('\r');
  client.flush();

  if (query.indexOf("/open") != -1)  {
    open_fast();
  } else if (query.indexOf("/close") != -1)  {
    close_fast();
  }

  sensor = analogRead(A0);
  sensor = map(sensor, 0, 1023, 0, full);

  Serial.print(sensor);
  Serial.print("  ");
  Serial.println(pos);

  if (sensor > pos) {
    open_slow();
    delay(1000);
  } else if (sensor < pos) {
    close_slow();
    delay(1000);
  }
  delay(100);

}

instead ofif (!client) {     return;   } use if (client) { /* handle client */ }?

@Juraj What does that do?

take a coding course

The problem is that at
while (!client.available()) {
  delay(1);
}
// your wifi code

you wait for a wifi event and in that time you obviously can't read the sensor. Just poll for incoming requests by doing it like
if (client.available()) {
  // your wifi code
}

This way your loop skips the wifi-routine if there is nothing to do and proceeds with reading the sensor.
As mikrocontrollers usually don't run a OS, you don't have multitasking which you have to implement yourself.
Generally you have to avoid using delay loops when you want several tasks being executed "parallely".

The difference between "if" and "while" in this situation, does it negatively effect the wifi or mcu by polling the internet in any different way or are they basically the same?

client.available() just checks if there are any requests in the esp's input buffer, the actual communication has allready taken place at that time and is handled by the esp's hardware. But there is a fundamental difference between if and while: if is only a single test for wifi activity, while delays your loop until wifi activity and is not what you want.

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


text:
ESP32 CAM failed to get frame in time
So I think the title says it all. I recently purchased an ESP32 CAM in India for a pretty cheap price.
It looks like an AI Thinker but doesn’t have the tag on the chip itself. Nonetheless, to get it setup before my use case I decided to test the camera. I loaded up the CameraWebServer example and set my camera type to AI thinker.
The code uploads successfully and runs successfully. I can open up the IP address and it shows the page. However whenever I try to get a still or start a stream, it gives this error:
[E][camera.c:1344] esp_camera_fb_get(): Failed to get the frame on time!
Camera capture failed

It’s pretty annoying and this happens in both 5V power and 3V power. The camera does physically get a bit hot after loading the website. Oh yeah, I have an OV 2460 Camera attached to the ESP.
Any advice is appreciated. Thanks!

I just bought 2 esp32-cam-mb, one is working fine, the other gave error 1483, I swaped the cam with a spare one I had, and it is working.
Titi

esp_camera_fb_return(fb);
add this to your code

Solution for if this occurs on a known working ESP-32-cam with PSRAM (i.e. example sketch with face recognition works ok).
If you're using anything other than PIX_FORMAT_JPEG, try reducing xclk_freq_hz.
In my case, it suddenly worked fine with PIX_FORMAT_RGB888, FRAMESIZE_VGA and xclk_freq_hz = 5000000 (4x lower).
( @Vraj P, this might not apply directly to what you found your problem was, but this post gets seen by many searching for this problem. Thanks!).

For me, reducing the XCLK frequency from 20 MHz to 10 MHz worked.

Over here, it was trying to compile with esp-idf idf.py with VSCode. Instead, compile esp32cam code with arduino-ide. Or use the arduino-cli compiler with VSCode for intellisense and a better editing experience. For some reason, the code compiled with idf is runnable but creates this error of not being able to get the frame on time, no matter what settings are used. xclk_freq_hz et. al.

I had tried and tried to get the camera working. However, I decided to concede to the part of me that thought it was a hardware error. I purchased a new OV2640 module and instantly it worked.
I think I learned my lesson in purchasing cheap components. I inspected the old one further. Turns out there was a faulty ribbon cable. Anyways, I hope you aren’t in this situation. Seems like the only solution is to purchase new hardware, and the current issue is faulty hardware.

THIS is not a solution.

I have one ESP32 CAM unit out of a dozen that randomly fails to get the picture. I tried all kinds of settings, and swapped the OV2640 a couple of times. Eventually I figured the  placement outside of the house was the issue. The wifi is solid no matter where the device is placed, but on one spot the camera fails every time. It has to be some kind of electromagnetic interference. If I move the camera a few feet left or right, it never fails. The shielding within the ESP32 cam board has to be defective as it just affects this one unit. All my other devices work fine wherever they are placed.

This stung me too. I found increasing the frame buffer count helped.
camera_config_t config;
config.fb_count = 10;  // Or some other number

One possible cause is given here (scroll down to find this specific issue)
https://randomnerdtutorials.com/esp32-cam-troubleshooting-guide/
There appear to be two sets of ESP-32-CAMs, one with and one without the PSRAM.

This is something that I did come across, but like I said, using a new camera module worked instantly. This probably meant that in my case it was a simple hardware error.

Look I've just had that problem for a month and if you're using esp32- ov2640 look the camera reference because the one I've had was TY 0V2640-V2.0 and what I've saw it's like a cheap copy of the normal camera, so be careful. I had to buy a new one because everything looked like a broken image, although all the config worked fine. Even changing the PIX_FORMAT and xclk_freq_hz didn't work. The camera was the problem.


text:
Can Arduinos keep a 500mu timer?
I need to output a serial message on a 500 microsecond interval (10 bytes), can be a little slower but no more than 1 milisecond between messages.
Can it be done with an Arduino? I know there is a delayMicro(), but not sure if it has the resolution.

Assuming serial data transfer to PC, it takes ~700 microseconds to send 10 bytes (i.e. 80 bits) at 115200 baud.  Check your numbers!  If you want faster data transfer, try SPI or ethernet.

It's not related to the delayMicro, but to the max speed of the Serial/UART driver, which is not documented, but according to some people it can reach 500 kbps.
However, 10 bytes, each 500 us (2000 Hz) means 10 * 11 (including some stop/start bit) * 2000 = 220.000 bits, so you have some headroom left. Maybe there is also some timing overhead.
Anyway, probably the only way to go is using an interrupt, and expect the Uno is not able to do anything else.
A better option might be to send less or send smarter (i.e. not 10 bytes, but maybe some compressed/binary form if not already thought about).

"but according to some people it can reach 500 kbps."  You can do better than that.  Per the datasheet, 2 megabits/second can be reached.  Table 24-7. Examples of UBRRn Settings for Commonly Used Oscillator Frequencies, shows 2 Mbps as the max rate achievable with 16 MHz clock.  The IDE only goes to 115,200 so you'll need to use a different serial program to see that data.  The fastest I've tested with is Serial.begin(250000);


text:
Connecting arduino with MATLAB
I installed Octave support package for Arduino and it is listed in the packages installed when pkg list command is run.But when the command  "a= arduino('COM8')";
is run,"error: serial: Error opening the interface: No such file or directory" is shown.Please respond.

Are you able to connect with the Arduino on COM8 through the Arduino IDE?

So in the Windows device manager, what COM ports do you see?

Using clear command on Octave before executing a=arduino('COM8') will remove this problem.
Use it like this:
clear
a=arduino('COM8')


text:
Using XBEE from my laptop, I want to assign multiple values in the Arduino
I'm trying to control motors by Arduino, from my laptop. I'm using MATLAB to send over packets of data, i.e. 'x=100,y=150,z=200' My scheme was to send this packet to Arduino, and have Arduino extract the numerical values from the string, since the positions of the numbers will always be consistent. I found a code from Arduino forum, written by PaulS, but I can't figure out why it wouldn't move into 'if (xbee.available())' portion of the code. The code is attached below:

#include <SoftwareSerial.h>
#define SOP '<'
#define EOP '>'

SoftwareSerial XBee(2, 3); // RX, TX
int test = 0;
bool started = false;
bool ended = false;

char inData[20];
byte index;
char inChar;

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

void loop()
{
  // Read all serial data available, as fast as possible
  while(Serial.available() > 0)
  {
    if (XBee.available())
    {
      char inChar = XBee.read();
     }
    if(inChar == SOP)
    {
       index = 0;
       inData[index] = '\0';
       Serial.print(inData);
       started = true;
       ended = false;
    }
    else if(inChar == EOP)
    {
       Serial.print(inChar);
       ended = true;
       break;
    }
    else
    {
      if(index < 19)
      {
        inData[index] = inChar;
        Serial.print(inData);
        index++;
        inData[index] = '\0';
      }
    }
  }

  // We are here either because all pending serial
  // data has been read OR because an end of
  // packet marker arrived. Which is it?
  if(started && ended)
  {
    // The end of packet marker arrived. Process the packet
    Serial.println(inData);
    // Reset for the next packet
    started = false;
    ended = false;
    index = 0;
    inData[index] = '\0';
  }
}

what are your connection? This script use Serial AND Xbee, how did you connected them?


text:
Add -D option via boards.txt
I'm trying to find a way to set a -D compiler option from within the boards.txt file. Basically set a #define for use in code. There are already some special ones like board.vid but is there a generic way to do it?
Somehow the Teensy add-on adds a little magic that allows the IDE to recognize options like:
.board.define0=-DHELLOWORLD
.board.option0=-DHELLOWORLD
In other words, add the -DHELLOWORD (#define HELLOWORLD) to the command line for GCC.
BUT, I can't get this to work without the Teensy add-on installed.
Is there a way to do this with the stock IDE?

Yes, it is possible in the 1.5.+ IDE. while not possible in the 1.0.+ and earlier.
Hardware-specification refers to both the boards.txt and platform.txt files.
in short the boards.txt file specifies...
uno.build.f_cpu=16000000L

and the platform.txt uses in the compile commands such as ...
 -DF_CPU={build.f_cpu}

You can your own. There is already a "build.extra_flags=" that some of the USB devices use to add their own FLAGs conditionally on the board type.

Ahh, cool. Teensy must modify the IDE somehow to support those things in 1.0.x
Now I just wish I could remember why I didn't want to upgrade to the beta... know there was a reason :P


text:
Understanding the compilation/linking/upload process (so I don't have to use the IDE)
I have started to play with and arduino UNO quite recently (without any prior experience with micro-controllers). I would like to use emacs instead of the IDE, and I'd also like to know what the IDE does under the hood, in order to be able to write my own makefile. The tutorials I've found are either outdated, or are presented as a series of steps without any explanation. I'd appreciate it if someone could explain to me how the whole compliation/linking/upload process works using gcc-avr and avr-dude, and how it is used by the IDE.

You can take a look under the hood by "Show verbose output during: ☑ compilation ☑ upload" Under File → Preferences.

Almost duplicate: Compiling code via terminal. See the links to arduino-builder and Sudar Muthu' Makefile in my answer to that question.

You can use Emacs in combination with PlatformIO. See also my answer to a related question. I'm using --ide vim when initialization the project in my example, but that command also support emacs.

If you want an exact duplication of what the IDE does but want it driven from the command line, that's what Ino is for. The full Arduino build process involves copying a lot of files from a lot of places, and is generally not trivial to duplicate.
If you're ready to let go of .ino files and the Arduino libraries, you get a much simpler toolset. avr-gcc compiles, avrdude uploads, and you're done. Here's one of my makefiles from a simple project:
CC=avr-gcc
CXX=avr-c++
CXXFLAGS=-Wall -Wextra -mmcu=atmega1284p -Os
CFLAGS=$(CXXFLAGS)
BINARY=ledmatrix
OBJECTS=

all: $(BINARY)
↹@avr-size $<

$(BINARY): $(OBJECTS)

clean:
↹@rm -f $(BINARY) $(BINARY).hex $(OBJECTS)

upload: $(BINARY).hex
↹@avrdude -c usbasp -p m1284p -U flash:w:$<:i

%.hex: %
↹@avr-objcopy -j .text -j .data -O ihex $< $@

.PHONY: all clean upload

If copying-and-pasting, be sure to replace all "↹" with tab characters.
EDIT:
I have created a repository with my buildsystem on Github.

Thanks, your makefile is pretty much what i was trying to come up with. But i guess getting rid of the libraries means that i wont be able to use functions such as digitalWrite()? In that case, where should i look to learn their plain C equivalents?

The Arduino libraries would contain their equivalents, but they can be a bit erudite to read. I recommend finding a low-level AVR tutorial to work through that will explain to you the various registers and peripherals. Oh, and the datasheet. Always get the datasheet.

Here is a high-level overview of Arduino's compilation process, for folks like me who found this post while hunting for one:
The compilation process
The arduino code is actually just plain old c without all the header part (the includes and all). when you press the 'compile' button, the IDE saves the current file as arduino.c in the 'lib/build' directory then it calls a makefile contained in the 'lib' directory.
This makefile copies arduino.c as prog.c into 'lib/tmp' adding 'wiringlite.inc' as the beginning of it. this operation makes the arduino/wiring code into a proper c file (called prog.c).
After this, it copies all the files in the 'core' directory into 'lib/tmp'. these files are the implementation of the various arduino/wiring commands adding to these files adds commands to the language
The core files are supported by pascal stang's procyon avr-lib that is contained in the 'lib/avrlib' directory
At this point the code contained in lib/tmp is ready to be compiled with the c compiler contained in 'tools'. If the make operation is succesfull then you'll have prog.hex ready to be downloaded into the processor.
https://www.arduino.cc/en/Main/Documentation


text:
Intermittent wifi/hotspot connection
I have an Arduino Mega 2560 with a cc3000 Wifi shield that is sending messages to dweet.io. Here is the relevant portion of my code:

// Post data to dweetio
    char data[125];
    sprintf(data, "?t1=%i&t2=%i&t3=%i&t4=%i&t5=%i&t6=%i&t7=%i&t8=%i&t9=%i&t10=%i&t11=%i&t12=%i&t13=%i&p=%i",
            (int)(t1*10.),(int)(t2*10.),(int)(t3*10.),(int)(t4*10.),(int)(t5*10.),
            (int)(t6*10.),(int)(t7*10.),(int)(t8*10.),(int)(t9*10.),(int)(t10*10.),
            (int)(t11*10.),(int)(t12*10.),(int)(t13*10.)),(int)(0);
    Adafruit_CC3000_Client client = cc3000.connectTCP(dweetioIp, 80);
    if (client.connected()) {
      client.fastrprint(F("GET "));
      client.fastrprint(F("/dweet/for/blahblah"));
      client.fastrprint(data);
      client.fastrprint(F(" HTTP/1.1\r\n"));
      client.fastrprint(F("Host: https://www.dweet.io\r\n"));
      client.fastrprint(F("\r\n\r\n"));
      // client.println();
      // Serial.println(F("Sent dweet\n"));
    } else {
      Serial.println(F("Sending dweet failed"));
      return;
    }

/* Read data until either the connection is closed, or the idle timeout is reached. */
long lastRead = millis();
while (client.connected() && (millis() - lastRead < 1000)) {
  while (client.available()) {
    char c = client.read();
    Serial.print(c);
    lastRead = millis();
  }
}

client.close();
// Serial.println("Connection to dweet.io closed");

In addition to this code, the loop does about two seconds of data collection and setting outputs.
This works most of the time when I connect to a typical wireless router. However, I want to deploy it away from my wifi source so I got a T-Mobile hotspot. When I use the identical code with the hotspot, it only successfully sends the message about one out of ten tries (sporadically though, not on even intervals).
The code doesn't report any errors. Anyone have any suggestions on how to debug this?

Have you been able to verify that the hotspot is reliable in the location with a laptop or something?  The other thing that would be worth trying is bumping your timeout to 5000 or so.  Cellular data connections can be kind of slow, resulting in longer timeouts.

@Butters I checked the connection speed. My router does 15ms ping, 4.7Mbps download, 8.2Mbps upload and the hotspot does 35ms ping, 4.2 download, 2.2 upload. I don't have a good reference- is that a big enough difference to cause the problem? As for the timeout, I only really care about the upload so that timeout shouldn't be a big deal, right?

Ya, you're probably correct, and your speeds should be fine.  So you don't get any errors at all in the code, or you don't get any compile errors?  Do you see the Sending dweet failed in your serial monitor?

Code-wise, it appears to run fine. It reports that it sent the information.

Interesting.  You might have to run Wireshark to inspect the traffic on the network and see what is actually going on.  Good luck!


text:
ESP8266 too many argument to function
My project uses ESP8226 to allow:
    1) user to set an alarm.
    2) after 20 sec of the alarm ringing, it will notify to phone via blynk app using motion sensor.
    3) after 40 sec it will turn off sensor and will not send notification
       again.
There are two problems that I have:

Got error with coding (digitalRead(nilai_sensor, LOW);) "too many arguments to function 'int digitalRead(uint8_t)"
I need help with coding for turn off the sensor and
will not nofify again.

Below is my Arduino code:
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <TimeLib.h>
#include <WidgetRTC.h>
BlynkTimer timer;
WidgetRTC rtc;
WidgetLED led1(V10);
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "a7d4522186464dd297870f2ab8e53250";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "NabiL";
char pass[] = "limaringgitlimapuluhsen";
int flag = 0;
int buzzer = 12;
int motor = 13;
int sensor = 4;

int saat;
int on_delay;
int off_delay;
int ok_delay;

int get1 = 0;
int get2 = 0;
int nilai_sensor = 0;

void blinkLedWidget()
{
  if (led1.getValue()) {
    led1.off();
    Serial.println("LED on V1: off");
  } else {
    led1.on();
    Serial.println("LED on V1: on");
  }
}

void clockDisplay()
{
  // You can call hour(), minute(), ... at any time
  // Please see Time library examples for details

  String currentTime = String(hour()) + ":" + minute() + ":" + second();
  String currentDate = String(day()) + "/" + month() + "/" + year();
  Serial.print("Current time: ");
  Serial.print(currentTime);
  Serial.print("Current Time: ");
  Serial.print(currentDate);
  Serial.println();

  // Send time to the App
  Blynk.virtualWrite(V1, currentTime);
  // Send date to the App
  Blynk.virtualWrite(V2, currentDate);
}

BLYNK_CONNECTED() {
  // Synchronize time on connection
  rtc.begin();
}
BLYNK_WRITE(V5) // Timer
{
  Serial.println(param.asStr());

  if (param.asInt())
  {
    on_delay = saat + 20;  //20Saat
    off_delay = saat + 10;  //10Saat
    ok_delay = saat + 40;  //40Saat

    digitalWrite(buzzer, HIGH);
    digitalWrite(motor, HIGH);
  }
}
BLYNK_WRITE(V6) // Timer
{
  Serial.println(param.asStr());

  if (param.asInt())
  {
    on_delay = saat + 20;  //20Saat
    off_delay = saat + 10;  //10Saat
    ok_delay = saat + 40;  //40Saat

    digitalWrite(buzzer, HIGH);
    digitalWrite(motor, HIGH);
  }
}
BLYNK_WRITE(V0){
  Serial.println(param.asStr());

  if (param.asInt())
  {

    digitalWrite(buzzer, HIGH);
    digitalWrite(motor, HIGH);

  }
  else

  {
    digitalWrite(buzzer, LOW);
    digitalWrite(motor, LOW);

  }
}
BLYNK_WRITE(V12){
  Serial.println(param.asStr());

  if (param.asInt())
  {

    digitalWrite(buzzer, HIGH);
  }
  else

  {
    digitalWrite(buzzer, LOW);
  }
}
BLYNK_WRITE(V13){
  Serial.println(param.asStr());

  if (param.asInt())
  {

    digitalWrite(motor, HIGH);
  }
  else

  {

    digitalWrite(motor, LOW);
  }
}
void setup()
{
  // Debug console
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  setSyncInterval(10 * 60); // Sync interval in seconds (10 minutes)

  // Display digital clock every 1 seconds
  timer.setInterval(1000L, clockDisplay);
timer.setInterval(1000L, blinkLedWidget);
  // Setup notification button on pin D1

  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(4, INPUT);

}
void loop()
{
  saat = millis() / 1000;

  if(saat == off_delay)
  {
    digitalWrite(buzzer, LOW);
    digitalWrite(motor, LOW);
  }

   if(saat == on_delay)
  {
    Serial.println("Time Up");
    get1 = 1;
  }

     if(get1 == 1)
    {
     Serial.println("Program Sensor");

   nilai_sensor = digitalRead(sensor);

    if(nilai_sensor == HIGH)
    {
      Serial.println("Still sleeping");
     Blynk.notify("Still sleeping");

    //delay(5000);
   }
  }

if(saat == ok_delay)
  {
    Serial.println("Shut Down Sensor");
    get2 = 1;
  }
 if(get2 == 1)
  {
    Serial.println("turn off Sensor");
    nilai_sensor = digitalRead(sensor);
   digitalRead(nilai_sensor, LOW);

  }

  Blynk.run();
  timer.run(); // Initiates BlynkTimer

}

how do you want to turn off a sensor over the pin you use to read it? simply don't read it

The function digitalRead() has only one argument: the digital pin that you want to know the state (high or low).
You must change the use of this function, to something like this:
int state = digitalRead(nilai_sensor)

if (state == low) {
    //do something here
}

Hope you can find helpfull :D


text:
Elapsedtime variable not resetting
I am new to Arduino programming. Let me describe the application I am working on. I am pressing a button for a certain period of time (30 sec). I can not hold it in a pressed position for all the time. I want to avoid accidental transition from button state going from logic HIGH to LOW. I am trying to drive a solenoid valve only at the end of the event.
The algorithm I am using is if once the system detects a HIGH from the sensor it goes in a loop and looks for transition to LOW. It checks if there is continuous LOW for more than 5 sec. If NO then it resets to start checking LOW again. If YES that means end of event and drives the solenoid valve.
The problem I am facing with the code is although the transition to LOW and remaining in LOW is less than 5 sec, the system is sending pulse to drive the solenoid valve. I have incorporated Serial.print() function to observe the value of the sensor input state and elapsed-time. The elapsed-time variable does not reset and keep increasing even though the button state reverts from LOW to HIGH.
I am incorporating part of the code here which is related to the algorithm. I will greatly appreciate if you kindly take a look at the code and the output file and help me detect the bug.
Thanks again!
Niloy.
void loop() {

      buttonstate = digitalRead(button);   // read the state of the microswitch value: HIGH "on" or LOW "off"

      if (buttonstate == HIGH ){
          countstart = 1;

          while(countstart == 1) {
          buttonstate = digitalRead(button);   // read the state of the microswitch value: HIGH "on" or LOW "off"

          if ( ( buttonstate == LOW ) && ( startFlag == 0 ) ) { //start new time sequence
                  startFlag = 1;
                  startTime = millis();
            }
          if ( ( buttonstate == LOW ) && startFlag == 1 ){
                  endTime = millis();
                  elapsedTime = endTime - startTime;
          }

          if ( ( buttonstate == HIGH ) && startFlag == 1 ){
                  startFlag == 0;
                  endTime = startTime =0;
                  elapsedTime = endTime - startTime;
                  countstart = 0;
          }

          Serial.print(buttonstate);
          Serial.print("\n");       // Print tab space
          Serial.print(elapsedTime);
          Serial.print("\n");       // Print tab space

      if ( elapsedTime >= 5000)
      {
          delay(2000);  //2 sec delay
          solenoid->run(FORWARD);
          delay(40);
          solenoid->run(RELEASE);

          delay(500);

          solenoid->run(BACKWARD);
          delay(40);
          solenoid->run(RELEASE);

          countstart = 0;
          endTime = startTime =0;
          elapsedTime = endTime - startTime;
          buttonstate = LOW;
          delay(15000); //wait for 15 sec

      }
     }

    }
}

Why don't you use a debounce library?

@Edgar, Can you please elaborate?

Your problem looks very similar to button bounce, albeit with longer time scales. The are ready made libraries meant to solve this problem reliably.

@Edgar, thank you so much for explaining. I am happy to learn about debounce. Let me take a look at that. Happy holidays!

startFlag variable never goes to zero because there is a bug in this part of code:
 if ( ( buttonstate == HIGH ) && startFlag == 1 ){
          **startFlag = 0;**
          endTime = startTime =0;
          elapsedTime = endTime - startTime;
          countstart = 0;
  }

4 parens on second IF, 3 on third, 3 on fourth.

@leoc7, yes that was the bug which restrained elapsed-time from resetting. I misplaced an extra equal sign. Thanks a lot for pointing it out. The system is working as expected now! Happy holidays a thanks again!

@user141512 you’re welcome!


text:
How to concatenate a part of a string and convert then to a int?
Lets say I have
String myString="AR0236";

I wish to extract the number 236 and assign it to an int. How can this be done?
P.S: I'me new to programming and I tried searching the forums for similar problems but surprising none of them worked for me!

note: concatenate means join.... it is opposite of what you are trying to do, which is split

see https://stackoverflow.com/questions/40538792/remove-first-few-characters-from-a-string?

There's multiple ways.
The String class (which TBH you should avoid) has some useful methods:

substring - extract part of a string as a new string
toInt - convert a string to an integer

So you can join them together:
int val = myString.substring(3).toInt();

That's the easy way.  Grab the string content from the 4th character (it's zero-based, so 3 is the 4th character) onwards, and convert it to an integer.
If you are avoiding String, as you should, then you are working with pointers.  For instance:
char myString[10]; // This is where your data gets stored
strcpy(myString, "AR0236"); // Let's put in some dummy data

int val = atoi(myString + 3);

myString + 3 gives you a new string pointer to a location that is 3 bytes further up in memory from myString - which equates to where the start of your number is.  Then convert that portion of the string to an integer.
The "easy" way consumes and makes a mess of your heap, since it's having to make a new String object and copy data into it. The "better" (second) way uses no more memory. It just converts a subset of the existing string directly.

Thank you for your response. The first method works although with a bit of a delay. I wish to use the second and more efficient method but doesnt work if i pass a variable in the second argument of the strcpy. The string I want to convert is from the serial so I the the string is unknown. How would you get around this?

Start by reading the serial properly. Start here: https://majenko.co.uk/blog/reading-serial-arduino

Thank you! Your link was really useful and my circuit works as intended to :)


text:
Gsm Sim800l Module
I am using below code for send sms but SMS Sent sucessfully but save in SIM memory & not able to see message text :
serialSIM800.write(“AT+CMGF=1\r”); //sending SMS in text mode
delay(1000);
serialSIM800.write(“AT+CMGS=“9827927887”\r”);
delay(1000);
serialSIM800.write(“Emergency at IIST\r”); // message
delay(1000);
serialSIM800.write(0x1A);
delay(1000);
Serial.println(“SMS sent successfully”);

Please help.

Set SMS Text Mode Parameters AT+CSMP to AT+CSMP=17,167,0,0
This setting  is resolve your issue.

Could you edit your answer and add an explanation as to why this solution works?

After few minutes of using Google, I found a library that contains everything you need to send/receive SMS and phone call. Here's the code I made in two minutes.
Currently I don't have SIM800L module, so I can't test it. Be sure you type a valid number format. For Croatia it's +385 XX XXX XXXX. +385 is an "international dialling code" for Croatia. Don't forget to put + before IDC.
serialSIM800.write("AT+CMGF=1\r");
serialSIM800.write("AT+CMGS=\"");
serialSIM800.write("PHONE_NUMBER");
serialSIM800.write("\"\r");
serialSIM800.write("Emergency at IIST");
serialSIM800.write("\r0x1A");

Thank you for the reply but my actual problem is i am from india and in my sim800l module the same network operator different sim card some are able to send proper message and i am able to receive it but some of them are not able to send the message and are sending the blank message to sim memory.


text:
Arduino Leonardo isn't detected by Linux Mint on serial port /dev/ttyACM0
I'm working on Linux Mint 18 Sarah (earlier Ubuntu 16.04 LTS) system. I've installed Arduino IDE using command sudo apt-get install arduino and I've added me dialout group using sudo usermod -aG dialout $(whoami). This is results of executing groups command:
hubert@hubert-SATELLITE-C660D ~ $ groups
dialout adm cdrom sudo dip plugdev lpadmin sambashare hubert

When I try upload following code to Arduino Leonardo:

/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  This example code is in the public domain.
 */

// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(500);               // wait for a second
}

orange LED marked with L letter on my board blinks and next I get following error:
Wielkość binarna szkicu: 4 736 bajtów (maksymalnie: 28 672 bajtów)
processing.app.debug.RunnerException: Couldn’t find a Leonardo on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.
    at processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:153)
    at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)
    at processing.app.Sketch.upload(Sketch.java:1671)
    at processing.app.Sketch.exportApplet(Sketch.java:1627)
    at processing.app.Sketch.exportApplet(Sketch.java:1599)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)
    at java.lang.Thread.run(Thread.java:745)

On my IDE Arduino shows on /dev/ttyACM0 serial port. When I try running this IDE on root privileges, I get the same error. On root privileges serial port is changing from /dev/ttyACM0 to /dev/ttyACM1, from /dev/ttyACM1 to /dev/ttyACM2 etc. I tried different USB cabels and reset Arduino but these ways nothing help. On Windows 7 my Arduino works and Arduino IDE uploads code without problems. Can anybody help me?

Read this: https://hackingmajenkoblog.wordpress.com/2016/08/24/diagnosing-arduino-problems-in-linux/

FWIW my money is on ModemManager.

Are you create ModemManager app?

No. "my money is on..." is a British idiom meaning "If I were a gambling man and I placed a bet on the cause, I would bet on it being ModemManager".

What exactly is ModemManager?

It's explained in the link I posted above.

Let us continue this discussion in chat.

Have you read that article? Have you tried the things in it? Until you do I cannot help you further.

Yes, I executed these instructions.

I've one more question. Did you write this guide for only Linux Mint distribution?

That guide is generic for most Linux distros, but I use Debian which is what Ubuntu is based on, which in turn is what Mint is based on.

So what was the outcome of disabling / removing ModemManager?


text:
Coding for Seeed Arduino motor shield
I acquired a Seeed studio Arduino motor shield V.2 and wanted to start using it. The problem is that there is like no good example code. The library for the shield on the seeed website has one example and doesn't really explain anything. Does anybody know where I could get a good guide for this thing?


text:
Will a .ino Arduino Sketch compile directly on GCC-AVR?
Okay, we all have seen those questions all over the web such as Arduino v.s. C++, or other similar questions. And a vast majority of the answers do not even touch compilation differences other than through abstracted information.
My question aims to solve the actual differences (not preferences) in how a .ino file renamed to a .cpp file or other similar file extension for c++ would compile using GCC-AVR. I know that at a minimum you have to include the Arduino header file, but beyond that, what would cause a compilation error if compiling said .ino to .cpp file using, say, for instance GCC-AVR. For simplicity's sake, lets use the classic blink example to explain what the differences are. Or if you have a better code snippet to use, please by all means, include the snippet in your answer and explain the differences thoroughly.
Please no opinions as to which is a better way or tool to use.
FYI. I use Platformio for development and I notice a conversion process happening behind the scenes during compilation. I am tryng to understand what is actually happening there, so when I code in Arduino, I understand the "pure" C++ version as well.
Thanks for your thoughtful answers to my question in advance.

Are you asking specifically about gcc on your desktop, or the GCC for AVR compiler avr-gcc? there is a much bigger difference there than there is between a .ino and a .cpp file.

@BrettAM The GCC-AVR toolkit as the Arduino UNO is the target board and uses a Atmel AVR chip, as I am sure you know. Thanks for the call out to ambiguity in my question. And yes I know that there is a much bigger difference. That is why I am asking this question. To learn what those differences are!

See my answer here: Classes and objects: how many and which file types do I actually need to use them? - specifically: How the IDE organizes things.

I know that at a minimum you have to include the Arduino header file

Yes you would need to do that.

but beyond that, what would cause a compilation error if compiling said .ino to .cpp file using, say, for instance GCC-AVR.

The IDE generates function prototypes for you. Code in a .ino file may or may not need this (it probably will unless the author is disciplined enough to code in the usual C++ way and do them themselves).

If the "sketch" contains other files (eg. other .ino, .c or .cpp files) then these would need to be incorporated in the compile process as I describe in my answer mentioned above.
Also you would need to (compile and) link in any libraries used by the sketch.

You haven't asked about the linking side of things, but naturally the various files, as compiled, need to be linked together, and then turned into a .elf and .hex file for uploading purposes. See below.

Example makefile
Based on the IDE output I made a simple makefile a while back:
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

In that particular case, the .ino file compiled without any problems after renaming it to Blink.cpp and adding this line:
#include <Arduino.h>

Thank you Nick for your concise answer, I am nowhere near the level you are, and didn't even think about a make file. So basically the syntax is there same, it is just all about linking objects, right? Thank you for sharing your make file for me to dissect. I am sure there will be more questions arising from that! Thanks again!

My file above worked when I posted it, but I believe may need tweaking for the later IDEs (because they move around or rename library files). Still, doing a verbose compile shows what the IDE is currently generating, which should get you started.

I would just like to add a few points to Nick Gammon's answer:

You do not need to rename a .ino file in order to compile it: if you
explicitly tell the compiler it's C++ (option -x c++), it will
ignore the unusual file extension and compile it as C++.
You do not need to add #include <Arduino.h> in the .ino file: you
can tell the compiler to do that for you (-include Arduino.h).

Using those tricks, I can compile Blink.ino with no modification, just
by invoking avr-g++ with the proper command-line options:
avr-g++ -mmcu=atmega328p -DARDUINO=105 -DF_CPU=16000000L \
    -I/usr/share/arduino/hardware/arduino/cores/arduino \
    -I/usr/share/arduino/hardware/arduino/variants/standard \
    -Os -fno-exceptions -ffunction-sections -fdata-sections \
    -Wl,--gc-sections -g -Wall -Wextra \
    -x c++ -include Arduino.h \
    /usr/share/arduino/examples/01.Basics/Blink/Blink.ino \
    -x none /usr/local/lib/arduino/uno/libcore.a -lm \
    -o Blink.elf

A few notes on the above command-line:

/usr/local/lib/arduino/uno/libcore.a is where I saved the compiled
Arduino core. I hate recompiling over and over again the same stuff.
-x none is needed to tell the compiler to mind the file extensions
again. Without it, it would assume libcore.a is a C++ file.

I learned those tricks from Sudar Muthu's
Arduino-Makefile. This is a
very general Makefile that works with many boards and with libraries.
The only thing missing relative to the Arduino IDE is the forward
declarations.

Very nice, Edgar! My solution basically mimics what the IDE does, yours solves the actual problem to hand in a much neater way. Of course you would have to make the libcore.a file in advance. I suppose that the lines in my answer which build core.a could be done in advance, so they don't have to be part of each build. Experience has shown that more complex sketches (eg. using Wire or SPI) need more files to be added to core.a.

@NickGammon: That's right, Muthu's Makefile (and, I assume, the Arduino IDE) tends to put whatever libraries you use in libcore.a. I do not really like this approach, as it makes the supposedly “core library” dependent on the particular program you compile. For single-file libraries, like Wire or SPI, I prefer to just put the library C++ file in the same compile command as the main program. That command line gets easily quite long, so I use a Makefile.

One of the things I like about the IDE is that you don't have to muck around. For simple projects anyway, it "just works".

Hi! I'm trying to figure out how to save some space in a large Arduino sketch, and would like to inspect the generated object file. I'm not sure I understand all this business about pre-compiling libcore.a, however. Is there an ELI5 for obtaining/inspecting the compiled code in a form similar to that which the Arduino IDE would generate?

@MRule: Disassemble the final .elf with avr-objdump. There are a few answers here explaining how.

Brilliant! This worked; Looks like the generated instructions are pretty disappointing in some cases. I wonder if there is any way to get the compiler to use the SBRC/SBRS (skip if bit in register clear / set) instructions.


text:
My Arduino Nano clone doesn't show in the serial this simple code. Why?
Here is the code:
void setup() {
  Serial.print("hi");
}
void loop() {
}

The product is in here.
I also installed the drivers.

You haven't "started" the serial interface.  Before you use the serial you need to tell it to initialize the hardware and how fast you want to communicate.
You need to add, for instance,
Serial.begin(9600);

to your setup() function before you do your Serial.print().

What does the command do exactly? Why 9600?

Still can't see nothing in the serial

It makes it work. At the moment you have sat in your car and and are pressing the accelerator - but you forgot to start the engine. You need to make sure that you are communicating at the same speed as you have specified in the begin() function call. Also you may see more if you change your print to a println and place it in loop instead of setup so it sends it over and over again.

still nothing in the serial monitor

Are you sure you are programming the board? Try using the Blink example to make sure you are actually programming it. Then try the AnalogInOutSerial example.

Even the blink example doesn't work in fact, because it doesn't change the blinking on the board.
Here's the proof I'm programming it?
Sketch uses 1,788 bytes (5%) of program storage space. Maximum is 30,720 bytes.
Global variables use 204 bytes (9%) of dynamic memory, leaving 1,844 bytes for local variables. Maximum is 2,048 bytes.

Houston, same message if I disconnect the board. Now what?

Ohhh I made the verify before the Upload. Now it works


text:
Supplying power to arduino by 5V and 2A adapter
Can I power my Arduino using a 5V/2A adapter by connecting it through the USB port?
More precisely, I have to run a module requiring 200mA but the aim is to make the laptop independent.

Amps are not "forced" through a circuit like volts are. A closed circuit draws as much power (in amps) as it needs, so the only problem you could ever have is having too little current and not too much. Seeing as your module draws 200ma 2 amps to power it is plenty.

I'm not quite sure what the second half of your question is saying, but:

can i power my Arduino by 5 volt 2 amp adapter by connecting it through the usb port

Yes, you can.


text:
How can I connect mysql with Arduino using GSMshield
How can I include mysql.h library in IDE of Arduino to connect Arduino to mysql database by using GSM shield?

You add the line: #include <mysql.h> ? Your question isn't clear. I'm going to close this question. Feel free to edit it with new information. Thanks for your understanding and cooperation!

You can't. Arduino is too small to run libmysqlclient directly. There are few other solutions:

You can expose your database using REST API and call that.
Change hardware platform to Raspberry Pi - it runs full Linux system
Run your app on PC and call Arduino using some RPC library

You can turn on GPRS data connection on your GSM shield and perform HTTP GET or POST request to the web page script (for example PHP script), which in turn will access the MySQL database (write or read DB records). It is easier than implementing REST API.


text:
I want to begin with arduino programming
I want to start programming with the Arduino Uno, but I don't know where to start or what a good start is. I can program a bit in c#, but I red that you have to program in c++.
Any idea's where to start?
Thanks!

welcome to Arduino Stack Exchange. You should do some basic research before you ask a question. This question is a duplicate and a question that can be resolved with a quick Google on: "Arduino get started".

Also, you might pick up a book and/or starter kit, they'll get you started very fast!

Yes, you are right @Paul, but i wanted to know the opinion of other programmers.

Good point, it would be better to ask in chat then (I believe you can't use chat yet though) or look at the duplicate questions: http://arduino.stackexchange.com/questions/18206/how-to-get-started. You also should've stated that you were looking for opinions ;) Just take a little time to check out http://stackoverflow.com/help/how-to-ask

Sure, thanks for your tip! I will have a look at it.

The other suggestions are great.
If you want to make a more "academic" approach, I can recommend two courses on Coursera:

The Arduino Platform and C Programming
Interfacing with the Arduino

I've followed and completed these 2 courses, and I think they were great fun. They give a light-weight introducton to the Arduino, with only a little time consumption needed.

You can purchase some great starter kits too:
They're easy to search for, here's a few that popped up right away:
http://www.arduino.cc/en/Main/ArduinoStarterKit
http://www.amazon.com/Kuman-Project-Complete-Starter-breadboard/dp/B016D5KUHS/
And here's one that I own, and I've recommended to other people:
http://www.microcenter.com/product/458578/Arduino_Compatible_Maker_Kit_with_LCD_Display
If you have a microcenter or radio shack or Fry's in your area, they all stock a variety of different starter kits.

I would like to add that you should go with one of the kits that has a book/guide with projects along with it. With a heap of components, it can be very difficult to get started. If there are some fun projects included, it will really motivate better.

Welcome to the world of Arduino. You can start by going directly to the Arduino Site -> Learning & tutorials. Also the internet full of 100's, if not 1000's of information and tutorials.

Do you have an example of a good tutorial, one that you think is good

Google Arduino Blink Tutorial -> https://www.google.com/search?q=Arduino+Blink+Tutorial&ie=utf-8&oe=utf-8

@Safwan If i answered your question, please mark the answer as ANSWERED. Thanks


text:
Connecting ethernet shield to computer
What configuration settings do I need to change on my computer to use the ethernet shield mounted on my Arduino UNO as I don't want to connect the ethernet shield to the router?

That depends entirely on the settings you have on the Arduino. Also note a special cross-over cable may be required.

What ethernet library do you use one the Arduino? And what is your network configuration? And what is the type of your Ethernet Shield?

Why wouldn't you want to connect it to the router? It's not directly accessible from the internet by doing so.

And what operating system are you using? (Windows/Linux/MacOS)

First off you need a basic understanding of TCP/IP networking. One you have that you need to:

Allocate yourself a new subnet - one that's not your normal local network (say 192.168.1.0/24)
Assign an IP in that subnet to your Arduino (say 192.168.1.1)
Assign a different IP in that subnet to your PC (say 192.168.1.2)
Configure your Arduino's sketch with it's IP address and netmask
Configure the PC's Ethernet interface with it's IP address and netmask
Connect the two together with a suitable cable.  If the PC's Ethernet port doesn't have auto-direction sensing you will require a special cross-over cable where TX+/TX- and RX+/RX- are swapped over.

You can try the easy way
This always works for me :D

Connect the shield to the Arduino and plug in the cables to the
PC(RJ45/Ethernet).
Go to network communication center.
Go to change adapter settings.
Select Ethernet(Arduino) and wireless(Wifi) /(internet source) and
right click.
Click bridge connections.
Wait for a few seconds.
Enjoy.


text:
How can I use my old cellphones camera on my arduino robot?
The pins are so small I dont know which pin needs to go to the which pin socket and if t's compatible or not. I have the selfie camera of Xperia Z phone and a Arduino Uno r3.

If you need a camera, chances are that an "arduino" is the wrong tool for your job, or at least that part of it.   Consider a more serious "computer" for high levels tasks, and potentially an Arduino-type device as a motion control delegate if that can't handle such things itself.

How can i use my old cellphones camera on my arduino robot?

No! Even if you got all the details on the camera there are too many limitations with the Arduino for any serious application. You will need more memory and processing power.

Camera modules usually talk a protocol called CSI-2 or CSI-3. That's the Camera Serial Interface protocol.
It transfers very large amounts of data very fast. More data than a little Arduino can cope with.  For instance, a current typical mobile phone camera is measured in multiples of megapixels. Each pixel takes 3 bytes to represent at 24-bit, so say you have a 2 megapixel camera that would be in excess of 6 megabytes of data per image.  To put that into perspective the Arduino Uno has 2kB of RAM.
So no there is no way you will be able to directly interface a mobile phone camera to any of the microcontroller based Arduinos. That's not to say that something might not be able to be hacked on to one of the new-fangled things they try and pass off as Arduinos these days but are actually some strange SoC made by Intel. You're very much on your own with those though...
There are camera modules available aimed at the Arduino, but they are not directly readable by the Arduino due to lack of memory. They do, though, generally have a UART interface for controlling the camera, and then a separate streaming interface (often with a FIFO buffer to access the data slowly) for grabbing a snapped picture. The Arduino can't really do much with that data other than save it to an SD card or pass it on to a computer through USB, so they're pretty pointless really.


text:
RF24L01+ VER01 with 10 pins
How can I connect this little ship to my Arduino? I can find alot of tutorials how to do it so, but all I find is 8 pins, mine includes 10 pins, and from what I could of understand from searching me myself, that there is 2 pins of VCC and 2 GRN pins.
So I would like to know how to connect this? Not necesserly Arduino, but can someone help me with the pins names at least so I can identify them.
Thanks.

This is also not correct for boards with original chip on it. This one is for WaveShare board :

There are some 10pin adapter boards floating around. See e.g.
nrf24l01 (8pin) + adapter board (10pin) oops?
Their pinout looks to be the following.


text:
Nrf24L01 with Arduino
When I wanted to test my Nrf24L01 I wanted to be sure of it working fine, so I used this code for an Arduino Uno:
#include <SPI.h>
#include <RF24.h>
#include "printf.h"
#define RF_CS 9
#define RF_CSN 7
RF24 radio(RF_CS, RF_CSN);
void setup() {
  Serial.begin(9600);
  printf_begin();
  radio.begin();
  radio.printDetails();
}
void loop() {
  radio.printDetails();
  delay(5000);

}

The thing is when I opened my Serial, I got this each 5 second:
STATUS       = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
RX_ADDR_P0-1     = 0x0000000000 0x0000000000
RX_ADDR_P2-5     = 0xff 0xff 0x00 0x00
TX_ADDR      = 0x0000000000
RX_PW_P0-6   = 0xff 0x00 0x00 0xff 0xff 0x00
EN_AA        = 0xff
EN_RXADDR    = 0xff
RF_CH        = 0xff
RF_SETUP     = 0xff
CONFIG       = 0xff
DYNPD/FEATURE    = 0xff 0x00
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = 16 bits
PA Power     = PA_MAX

Which apparently means that there must be something wrong with the connection, as far as I know .
noting that i have this Nrf24L01 with 10 pins, so i tried to attach it just like the following picture shows :

So I tried to plug it in with the Arduino just like this:

What was the mistake?

Voting to close as unanswerable, as the poster has admitted that the circuit does not match what is depicted but has failed to provide any information on what circuit they actually do have.  Questions abandoned in a form where they can neither be answered nor inform any similar problems merely clutter the site without being of use to anyone.

What is it that you are asking? I can't see a clear question.

I think problem lies in your Arduino sketch, specifically in this line:
#define RF_CSN 7

Now, you have set RF_CSN pin to pin#7 while actually, its connected to pin#9
To get this to working you, try changing above lines of code to:
#define RF_CSN 10

Hope it helps.

yes, true, that but I   just discovered that the pins aren't even like the https://i.sstatic.net/5epm9.jpg image shows, but indeed it's a whole different setup, so i managed to solve my problem, thnx for your help

@Medmalik - You should post your answer


text:
Arduino sketch won't run until I open up GUI in processing
I am trying to make a human detection robot using D6T omron thermal sensor. However, I am facing some problem here. My Arduino Uno didn't run the sketches until I open up my GUI in processing. The tx/rx pin did not light up when I remove my USB serial cable from my PC and put in an external power supply to my arduino uno board. The tx/rx pin will only light up when I open my GUI in processing and everything works just fine.
I am trying to move my robot away from my PC. Therefore, it is a must for me to provide my board an external power supply but it just does not work. I am confused here. Fyi, it will be interfacing with my PC thru Xbee in the near future.
Ps: this is my final year project. Your effort will be much appreciated and credits will goes to you. Thanks guys!
Attached below is my code (Arduino sketch):
#define E_right 10
#define E_left 11

int RightMotorForward = 9; // Pin 10 has Left Motor connected on Arduino boards.
int RightMotorReverse = 8; // Pin 9 has Left Motor connected on Arduino boards.

int LeftMotorForward = 12; // Pin 12 has Right Motor connected on Arduino boards.
int LeftMotorReverse = 13; // Pin 13 has Right Motor connected on Arduino boards.

float top_sum, bottom_sum, left_sum, right_sum, center_row_sum;

#include <Wire.h>
#include <WireExt.h>

#define D6T_addr 0x0A
#define D6T_cmd 0x4C

int rbuf[35];
float tdata[16];
float t_PTAT;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  Serial.flush();
  pinMode(E_right, OUTPUT);
  pinMode(E_left, OUTPUT);
  pinMode(LeftMotorForward, OUTPUT);  // initialize the  pin as an output.
  pinMode(RightMotorForward, OUTPUT);  // initialize the  pin as an output.
  pinMode(LeftMotorReverse, OUTPUT);  // initialize the  pin as an output.
  pinMode(RightMotorReverse, OUTPUT);  // initialize the  pin as an output.
}
//-----------------------------------------------------------------------------

// The following Loop is to make the Robot move towards heat source.
void loop()
{
int i;

  if (Serial.available() > 0) {
    int inByte = Serial.read();
    if (inByte == 0x0001) {

      Wire.beginTransmission(D6T_addr);
      Wire.write(D6T_cmd);
      Wire.endTransmission();

      if (WireExt.beginReception(D6T_addr) >= 0) {
        i = 0;
        for (i = 0; i < 35; i++) {
          rbuf[i] = WireExt.get_byte();
        }
        WireExt.endReception();

        t_PTAT = (rbuf[0]+(rbuf[1]<<8))*0.1;
        for (i = 0; i < 16; i++) {
          tdata[i]=(rbuf[(i*2+2)]+(rbuf[(i*2+3)]<<8))*0.1;
        }

      }
    }
  }

top_sum= tdata[0] + tdata[1] + tdata[2] + tdata[3];
bottom_sum= tdata[12] + tdata[13] + tdata[14] + tdata[15];
right_sum= tdata[0]+ tdata[4] + tdata[8] + tdata[12];
left_sum= tdata[3] + tdata[7] + tdata[11] + tdata[15];
center_row_sum= tdata[1] + tdata[2] + tdata[5] + tdata[6] + tdata[9] + tdata[10] + tdata[13] + tdata[14];

if ((left_sum>center_sum)&& (center_sum>right_sum))
{
   analogWrite(E_right, 230);
   analogWrite(E_left, 205);

   digitalWrite(RightMotorForward, HIGH);   // turn the Right Motor ON
   digitalWrite(LeftMotorForward, LOW);   // turn the Left Motor OFF
                  // wait for  0.5 seconds
   delay(500);
   //turn left
}

else if ((right_sum>center_sum)&&(center_sum>left_sum))
{
   analogWrite(E_right, 230);
   analogWrite(E_left, 205);

   digitalWrite(RightMotorForward, LOW);   // turn the Right Motor OFF
   digitalWrite(LeftMotorForward, HIGH);   // turn the Left Motor ON
   // wait for  0.5 seconds
   delay(500);
   //turn right
}
else if ((center_row_sum>right_sum)&&(center_row_sum>left_sum))
{

   analogWrite(E_right, 230);
   analogWrite(E_left, 205);

   digitalWrite(RightMotorForward, HIGH);   // turn the Right Motor ON
   digitalWrite(LeftMotorForward, HIGH);   // turn the Left Motor ON
   delay(500); //forward

}

}

Attached below is my code in processing:
import processing.serial.*;

float[] tdata = new float[17];
float tptat; // PTAT
String portName;
//int serialport = 0;

String buf;
float colourGreen; //change green in relation to temperature

int lbTemp = 25; //lowest relative temperature
int hbTemp = 35; //highest relative temperature
Serial myPort;  // Create object from Serial class

void setup() {
  size(640,640);
  //println(Serial.list());
  //portName = Serial.list()[serialport];
  myPort = new Serial(this, "COM7", 9600);
  myPort.clear();

}
void draw() {
  myPort.write(0x01);
  delay(100);
  while (myPort.available() > 0) {
    delay(300);
    buf = myPort.readString();
    myPort.clear();
    tdata = float(split(buf, ','));
    for (int i = 0; i <16; i++) {
      colourGreen = map(tdata[i],lbTemp,hbTemp,255,0);
fill (255,colourGreen,0);

      if (i == 0)
    { rect(480,0,160,160);}
      else if (i == 1)
    { rect(320,0,160,160);}
      else if (i == 2)
    { rect(160,0,160,160);}
      else if (i == 3)
    { rect(0,0,160,160);}
      else if (i == 4)
    { rect(480,160,160,160);}
      else if (i == 5)
    { rect(320,160,160,160);}
      else if (i == 6)
    { rect(160,160,160,160);}
      else if (i == 7)
    { rect(0,160,160,160);}
      else if (i == 8)
    { rect(480,320,160,160);}
      else if (i == 9)
    { rect(320,320,160,160);}
      else if (i == 10)
    { rect(160,320,160,160);}
      else if (i == 11)
    { rect(0,320,160,160);}
      else if (i == 12)
    { rect(480,480,160,160);}
      else if (i == 13)
    { rect(320,480,160,160);}
      else if (i == 14)
    { rect(160,480,160,160);}
      else
    { rect(0,480,160,160); }

    if (tdata[i]<5) {fill(255);} else {fill(0);}
      if (i ==0)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),560, 80);}
      else if (i == 1)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),400, 80);
      }
      else if (i == 2)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 80);
      }
      else if (i == 3)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),80, 80);
      }
      else if (i == 4)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 560, 240);
      }
      else if (i == 5)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 400, 240);
      }
      else if (i == 6)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 240);
      }
      else if (i == 7)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 80, 240);
      }
      else if (i == 8)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 560, 400);
      }
      else if (i == 9)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 400, 400);
      }
      else if (i == 10)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 400);
      }
      else if (i == 11)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 80, 400);
      }
      else if (i == 12)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 560, 560);
      }
      else if (i == 13)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 400, 560);
      }
      else if (i == 14)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 560);
      }
      else
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 80, 560);
      }
    }
    delay(800);
  }
}

My Arduino Uno didn't run the sketches until I open up my GUI in processing.

How do you know?

The tx/rx pin did not light up when I remove my USB serial cable from my PC and put in an external power supply to my arduino uno board.

That is because the TX/RX LEDs are linked to the USB interface chip. With no USB connection there can be no lights.

The tx/rx pin will only light up when I open my GUI in processing and everything works just fine.

That is because there is USB communication.
Your sketch is running fine. However your sketch looks to be wrong.  Major portions of it (i.e., the portion that does any detection at all) relies on serial data coming in.  How can you have it working, in that case, if you disconnect the serial interface so that no data ever comes in?

OHHHH! I see. Thank you so much for pointing out the mistakes. Do you hv any suggestion on how to improve my sketch? Sorry because I am new to these. Thanks a lot Majenko!

You don't appear to actually be doing anything with serial in your sketch. Just delete all references to it.

Okayyy! I will try it out and update you later. Thanks again Majenko! =D

It works! Thanks for pointing out my silly mistakes! Credits goes to you, Majenko~ Thanks!!


text:
Conflict between SD card shield and accelerometer
I'm trying to get the SD card (Adafruit microshield SD card) and an MPU6050 accelerometer to work at the same time. When I connect the SD card to the Arduino (without the accelerometer), it's ok; When I connect the accelerometer to the Arduino (without the SD card), it's also ok. The codes for the accelerometer and SD card work fine separately. But when I connect the shield to the Arduino, and then connect the accelerometer, and try to run a combined code, it's problematic. I've included the code I'm currently working on below.  I would really appreciate if you could help me find where the problem lies, and how to solve it.
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
//#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
//    #include "Wire.h"
//#endif

// A simple data logger for the Arduino analog pins

// how many milliseconds between grabbing data and logging it. 1000 ms is once a second
#define LOG_INTERVAL  1000 // mills between entries (reduce to take more/faster data)

// how many milliseconds before writing the logged data permanently to disk
// set it to the LOG_INTERVAL to write each time (safest)
// set it to 10*LOG_INTERVAL to write all data every 10 datareads, you could lose up to
// the last 10 reads if power is lost but it uses less power and is much faster!
#define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
uint32_t syncTime = 0; // time of last sync()

#define ECHO_TO_SERIAL   1 // echo data to serial port
#define WAIT_TO_START    0 // Wait for serial input in setup()

// the digital pins that connect to the LEDs
#define redLEDpin 4
#define greenLEDpin 3

// The analog pins that connect to the sensors
//(not sure which pins on the accelerometer are the analog pins that connect to the sensor. Insert here!!)

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;
#define OUTPUT_READABLE_YAWPITCHROLL
//#define OUTPUT_READABLE_QUATERNION
//#define OUTPUT_READABLE_EULER
//#define OUTPUT_READABLE_REALACCEL
//#define OUTPUT_READABLE_WORLDACCEL

RTC_DS1307 RTC; // define the Real Time Clock object

// for the data logging shield, we use digital pin 10 for the SD cs line
const int chipSelect = HIGH;

// the logging file
File logfile;

void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);

  // red LED indicates error
  digitalWrite(redLEDpin, HIGH);

  while(1);
}

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

  // use debugging LEDs
  pinMode(redLEDpin, OUTPUT);
  pinMode(greenLEDpin, OUTPUT);

#if WAIT_TO_START
  Serial.println("Type any character to start");
  while (!Serial.available());
#endif //WAIT_TO_START

  // initialize the SD card
  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(10, OUTPUT);

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    error("Card failed, or not present");
  }
  Serial.println("card initialized.");

  // create a new file
  char filename[] = "LOGGER00.CSV";
  for (uint8_t i = 0; i < 100; i++) {
    filename[6] = i/10 + '0';
    filename[7] = i%10 + '0';
    if (! SD.exists(filename)) {
      // only open a new file if it doesn't exist
      logfile = SD.open(filename, FILE_WRITE);
      break;  // leave the loop!
    }
  }

  if (! logfile) {
    error("couldnt create file");
  }

  Serial.print("Logging to: ");
  Serial.println(filename);

  // connect to RTC
  Wire.begin();
  if (!RTC.begin()) {
    logfile.println("RTC failed");
#if ECHO_TO_SERIAL
    Serial.println("RTC failed");
#endif  //ECHO_TO_SERIAL
  }

  logfile.println("Hello,World,!!!");
#if ECHO_TO_SERIAL
  Serial.println("Hello,World,!!!");
#endif //ECHO_TO_SERIAL

  // If you want to set the aref to something other than 5v
  analogReference(EXTERNAL);
}

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}
 #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    Serial.begin(9600);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately
 // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
        Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
        Serial.println(F(")..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

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

void loop(void){

 if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        if (mpuInterrupt && fifoCount < packetSize) {
          // try to get out of the infinite loop
          fifoCount = mpu.getFIFOCount();
        }

  DateTime now;

  // delay for the amount of time we want between readings
  delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));

  digitalWrite(greenLEDpin, HIGH);

  // log milliseconds since starting
  uint32_t m = millis();
  logfile.print(m);           // milliseconds since start
  logfile.print(", ");
#if ECHO_TO_SERIAL
  Serial.print(m);         // milliseconds since start
  Serial.print(", ");
#endif

  // fetch the time
  now = RTC.now();
  // log time
  logfile.print(now.unixtime()); // seconds since 1/1/1970
  logfile.print(", ");
  logfile.print('"');
  logfile.print(now.year(), DEC);
  logfile.print("/");
  logfile.print(now.month(), DEC);
  logfile.print("/");
  logfile.print(now.day(), DEC);
  logfile.print(" ");
  logfile.print(now.hour(), DEC);
  logfile.print(":");
  logfile.print(now.minute(), DEC);
  logfile.print(":");
  logfile.print(now.second(), DEC);
  logfile.print('"');
#if ECHO_TO_SERIAL
  Serial.print(now.unixtime()); // seconds since 1/1/1970
  Serial.print(", ");
  Serial.print('"');
  Serial.print(now.year(), DEC);
  Serial.print("/");
  Serial.print(now.month(), DEC);
  Serial.print("/");
  Serial.print(now.day(), DEC);
  Serial.print(" ");
  Serial.print(now.hour(), DEC);
  Serial.print(":");
  Serial.print(now.minute(), DEC);
  Serial.print(":");
  Serial.print(now.second(), DEC);
  Serial.print('"');
#endif //ECHO_TO_SERIAL

  analogRead(photocellPin);
  delay(10);
  int photocellReading = analogRead(photocellPin);

  analogRead(tempPin);
  delay(10);
  int tempReading = analogRead(tempPin);

  logfile.print(", ");
  logfile.print(photocellReading);
  logfile.print(", ");
  logfile.print(temperatureF);
#if ECHO_TO_SERIAL
  Serial.print(", ");
  Serial.print(photocellReading);
  Serial.print(", ");
  Serial.print(temperatureF);
#endif //ECHO_TO_SERIAL

}

// reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        fifoCount = mpu.getFIFOCount();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT)) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

  logfile.println();
#if ECHO_TO_SERIAL
  Serial.println();
#endif // ECHO_TO_SERIAL

  digitalWrite(greenLEDpin, LOW);

  // Now we write data to disk! Don't sync too often - requires 2048 bytes of I/O to SD card
  // which uses a bunch of power and takes time
  if ((millis() - syncTime) < SYNC_INTERVAL) return;
  syncTime = millis();

  // blink LED to show we are syncing data to the card & updating FAT!
  digitalWrite(redLEDpin, HIGH);
  logfile.flush();
  digitalWrite(redLEDpin, LOW);

}

const int chipSelect = HIGH; HIGH is 1. you can't use pin 1 for this

you have not fully described what is happening ..... what happens if you connect both the modules and run the two separate codes?

Are both devices connecting via the SPI bus?

Based on the information that you've provided, it's quite likely that your problem  lies with how your SD card and accelerometer connect via the SPI bus.
The problem is that a lot of Serial Peripheral Interface (SPI) devices, particularly the cheaper ones, don't properly put the MISO pin into high-impedance when SS is pulled high.  The 'datasheet'/tutorial for the Micro SD Card Breakout Board (which is the device that I assume you mean when you say Adafruit microshield SD card), has the following schematic:

Which doesn't appear to include a tri-state buffer.
I had almost exactly this situation with one of my projects. I eventually resolved it by placing a tri-state buffer (in that case, I used a 74HC125 4-channel tri-state buffer) in the MISO line for each of the SPI devices.

This page on Better SPI Bus Design in 3 steps is what finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).


text:
Upload data to MAX 7219
I have the following code to write data on MAX7219 for light up a 8x8 LED Matrix:
for (i = 0; i < 8; i++)
{
    CLK = LOW;
    DIN = temp & MSBIT >> i;
    CLK = HIGH;
}

The thing is, sadly, I just know that the code line (DIN = temp & MSBIT >> i;), must be exactly like that, otherwise the LED´s won't show the expected, but I don't understand how it works...
Please, I really need explanation because I'm stuck....
Note: variable "temp" is always a hexadecimal number like 0x20, and "MSBIT" = 0x80.

Please, post complete code.

You have to send 16 bits to load data.  The first 8 are the register the data goes into, 0 to 15, the next 8 are the data to be displayed. Registers 1-8 are the data that gets displayed, the others are used to set up: intensity, display test, normal/shutdow, decode/no decode mode, and number of digits/columns connected (such as 4 digits, or 8 for an 8x8 matrix).
In Arduino, I use hardware SPI to send data to MAX7219 - SCK, MOSI, and SS.
digitalWrite (ssPin, LOW);
SPI.transfer(addressRegister); // 0 to 15
SPI.transfer(dataToLoad);
digitalWrite (ssPin, HIGH);

Do that for each register. The control registers only need to be written once. In Arduino, that is usually in setup().  Intensity might be changed later for brightness (0 to 15 as valid data).
In loop(), use the above to update your display for the 8 display data registers (1-8).

SPI default speeds of 4 MHz, MSBFIRST, SPI Mode 0 do not need to be changed.


text:
nodemcu esp8266 does not boot up when 5V pin is connected as a VIN source
Whenever I boot up the esp8266 or flash code via usb ,I have to remove vin pin otherwise it does not boot up.
If I remove vin pin then flash and boot up happens and then i am able connect vin with 5 V relay.(using VIN to power up relay) .
I dont understand what it has to do with VIN pin.please suggest.
I am using below pins for eight devices
//relay pin setup for funct
int relayOne = 5;
int relayTwo = 4;
int relayThree = 0;
int relayFour = 2;
int relayFive = 14;
int relaySix = 12;
int relaySeven = 13;
int relayEight = 15;

the relay board might be passing 5v to a 3.3v pin via a pullup, i've seen that before on active-low relay modules. Some ESPs might not like 5v. use an n-chan to pull down the relay based on 3.3v from the GPIO

Thanks for the input.Anyway I removed gpio 0 2 15 as it creates problem in boot up.now it’s working fine

IO pins 0, 2 and 15 are boot configuration pins. 15 must be LOW at boot, 2 must not be LOW at boot and 0 determines the flashing mode. For normal run pin 0 must be HIGH. The NodeMcu board has necessary pull-up and pull-down circuits.
You can connect to pins 0, 2 and 15 only devices which don't change the boot state.

Thanks much.
but I don’t understand that why it is working when vin is not connected to relay vcc.it is not booting up only when vin is connected to relay.
Second if I remove device from these 3 pin.which other pins I can use.i have total eight devices to control.
Thanks in advance

it changes if the relay signal pin pulls up or down a pin

Thanks for the support.I removed gpio 0 2 15 and used some other pins.its working fine.

Okay I will do it.i am new to stackexchange .not sure where to do it


text:
Switch two or more digital outputs of ESP8266 at the same time
I'd like to control some digital ICs with a ESP8266-12.

How can I switch 2 pins to HIGH in the same moment?
How can I switch one to LOW and the other to HIGH in the same moment?
Is it possible with every port or only with grouped ports and how are the groups?

Maybe have a look in this direction

See the datasheet: esp8266-technical_reference_en
Paragraph 2.2.2 shows how to use the output registers.
With the registers GPIO_OUT, GPIO_OUT_W1TS and GPIO_OUT_W1TC you can set or clear multiple GPIOs.