text:
Sending serial bits in arduino
I am a newbie in Arduino and serial communication. I am working on a project that use Arduino to send data bits to an actuator using RS232 communication protocol. In order to control the actuator, an instruction consists of 6 bytes must be sent with 9600 baud, no hand shaking, 8N1 format.
Here are the instructions:
Byte 1 - Device, Byte 2 - Command, Byte 3 - Data(LSB), Byte 4 - Data, Byte 5 - Data, Byte 6 - Data(MSB)
For example to send 1, 20, 1, 1, 0, 0 (Move the actuator to absolute position of 257 microsteps)

This is my draft code. How can I send start and stop bit? I am confused on sending start and stop bit. The Serial.write() is sending binary data as a byte. Does it mean that I write Serial.write(20), the compiler will send the data in 00010100 binary format? I am quite frustrated with serial communication.

The Serial.write is working on a level of bytes and byte arrays, not bits. You don't need to implement the lower level stuff when using it. Anyway, looks like a major misunderstanding of things.

The start and stop bits are rolled into the protocol automatically. You do not have to worry about them. Try http://www.eapbg.com/single-post/2016/05/26/eapbg-15-Introduction-to-UART maybe it will help.

Please don't post code as screenshots.  Please post code as text instead.  Text is indexable and searchable, screenshot's aren't.

The start and stop bit are already included as part of the UART protocol. When you send a byte it first sends the start bit, then the byte, then the stop bit. You don't need to do anything to make those bits send.
20 is actually sent as 0001010001
So your code will just be a series of Serial.write() calls for each byte you want to send.
Serial.write(1);
Serial.write(20);
Serial.write(1);
Serial.write(1);
Serial.write(0);
Serial.write(0);

Or as an array:
uint8_t data[6] = {1, 20, 1, 1, 0, 0};
Serial.write(data, 6);

Thanks for the comment, I will try using your suggestion :)

20 is sent as 0001010001: least significant bit first.

Yeah, I just blindly copied his example without checking.

Read the language reference: https://www.arduino.cc/en/Reference/Serial
..and for write(): https://www.arduino.cc/en/Serial/Write
....notice that it "writes" the bytes or buffers you define. You have already defined the baud rate and started the serial channel, then all you need to do is pass the characters or strings you want to send to the write function.
In your application it may be best to build a 6 character command string and send it all at once as a string. You must then remember that With "write" you are responsible for "writing" the cr and lf which is probably needed as a command terminator in your receiving device.
For your kind of application it may also be possible to use "println" which appends a cr/lf automatically for you. It depends on your protocol.

You certainly don't want to use println() with a binary protocol.

@EdgarBonet. If it' is a truly binary level serial protocol that's true. However I did qualify it, it's unusual to see simple protocols like this not be easily keyboard creatable strings.

You failed to read (or understand) the second paragraph of the original question.

Not at all, I assumed given the grade of question that the OP may not have described the problem completely.  I completely covered his question accurately in my first paragraph. I simply gave an option if that was suitable. I have altered the answer....hope it meets your niggle.


text:
'setup' does not name a type?
Was trying to work some code that I found online to suit my needs and it continues to show the same error 'setup' does not name a type. I have tried setting it to void, Void as well as rewriting the code but still the same issue arises and I was wondering how to fix this issue.
This program will at some point compile data from 3 different sensors and do its various calculations within these separate loops and print to serial in a table that can then be saved or exported. The only sensor attached at the moment is a ultrasonic sensor that measures the distance it is from a surface. (last 2 groups of code have a basic print function just so the loop is occupied)
Here is the code:
#include <CapacitiveSensor.h>

long timeCounter; // milliseconds counter
long timePassed; // The actual milliseconds time
int trigPin = 2;
int echoPin = 3;

long delay1 = 10;    // ms for cycle of event 1
long delay2 = 5;     // ms for cycle of event 2
long delay3 = 25;    // ms for cycle of event 3
long delay4 = 10;

// Counters for the number of triggered events before the
// corresponding event starts
int countEvent1, countEvent2, countEvent3, countEvent4;

int TRIGGER = 5; // ms to trigger the milliseconds timer

int MAX1 = 2; // Number or triggered milliseconds to start event1
int MAX2 = 1; // Number or triggered milliseconds to start event2
int MAX3 = 5; // Number or triggered milliseconds to start event3
int MAX4 = 2;

// Initialisation
setup {
     timeCounter = millis(); // read the actual internal time
     timePassed = 0; // we start with no time passed

     countEvent1 = 0;
     countEvent2 = 0;
     countEvent3 = 0;
     countEvent4 = 0;
}

// Infinite cycle
loop() {

     // Read the actual time
     timePassed = millis() - timeCounter;
     // The smallest unit of time that should trigger an event is for event 2 (5 ms)
     // so our trigger should count this smaller unit

     // Check if the time passed after last reading is the trigger time
     if(timePassed >= TRIGGER) {
          if(++countEvent1 == MAX1){
               // Reset the trigger and start the event
               event1();
               countEvent1 = 0;
          } // Event 1

          // It's time to manage the events
          if(++countEvent2 == MAX2){
               // Reset the trigger and start the event
               event2();
               countEvent2 = 0;
          } // Event2

          // It's time to manage the events
          if(++countEvent3 == MAX3){
               // Reset the trigger and start the event
               event3();
               countEvent3 = 0;
          } // Event3

          if(++countEvent4 == MAX4){
               // Reset the trigger and start the event
               event4();
               countEvent4 = 0;
          } // Event4

     } // Trigger

} // LOOP

// ============ Event functions ==============

event1() {
  long duration, distance;
  digitalWrite(trigPin,HIGH);
  delay(100);
  digitalWrite(trigPin, LOW);
  duration=pulseIn(echoPin, HIGH);
  distance =(duration/2)/29.1;
}

event2() {
Serial.print("work")
}

event3() {
Serial.print("work")
}

I am very new to coding so there will be stupid mistakes hidden amongst this I can guarantee it.

You're just forgetting the smooth brackets after void setup. It should be void setup () {

You should learn the basics of a language's syntax before writing programs in it...

All your functions (including setup and loop) need a type as part of the declaration. This for example:
event2() {
Serial.print("work")
}

Should be:
void event2() {
  Serial.print("work");
  }

Note also the semicolon after the Serial.print function call.
I have a page that explains the basics.
On that page is a diagram that breaks down what a function declaration looks like:

You have a problem with function definition. Let me explain with an example.
int kPinLed = 8; // LED - Pin 8

void setup()
{
  pinMode(kPinLed, OUTPUT); // LED as output
}

void loop()
{
  ledFun(); //Create LED Function
}

//Now write function's code with type, here "void"

void ledFun()
{
  digitalWrite(kPinLed, HIGH); //LED ON
  delay(1000);
  digitalWrite(kPinLed, LOW);  //LED OFF
  delay(1000);
}

Same things you have to do with your code. Just write properly function's type. I hope this will help you.

Function declarations start with a type:
void setup() {

}

void loop() {

}

void means the function doesn't return a value.

Yeah you never defined setup or loop which need the void before them.
void setup(){

}

void loop(){

}

error 'setup' does not name a type. I have tried setting it to void

the correct typing of it is this:
void setup(void) {
...
}

void loop(void) {
...
}

source: Stack Exchange

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

sort: votes


text:
Chromebook/chromebox IDE/compiler option?
My daughter has a chromebox she uses for all her email/homework/etc.  We've started to get into making ADABOX projects and I was looking for best options for chromebook users.  I saw that codebender was shutting down.  And Chromeduino looks like it might have problems with libraries.  Currently I am looking to just set her up with a Raspberry Pi she can connect to with her chromebox and use it to connect to the Arduinos/Feathers, since I know she will need libraries and things from adafruit.  But I was hoping there might be newer options I haven't found yet.

Arduino Create?

@Majenko from what I can tell it does not have a way to connect USB to Chromebook like codebender.

Ah well. Maybe the pi is the best way. She'll learn Linux too then.

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


text:
Swapping 5V and GND for a 2 wire motor
I have a 2-wire brushed DC motor in a servo housing which either pushes left or right (and "center" when unplugged).
To push to one side I connect a wire to 5V and the other to GND, to push to the other side I just need to swap the wires.
How can I achieve this with the arduino without any physical rewiring?

I think you need arduino motor shield.

Click Here
Just click on above link, you find a good tutorial about arduino motor shield. I hope it might be helpful.

The pictured L293-based shield is obsolete by at least a decade, look for something with a more modern solution like a TB6612FNG to get decent performance, especially if using batteries.

Thanks! I was able to try the Arduino Motor Shield R3 and it works as intended.

What you want is called a H-bridge, and it is what a standard Arduino motor shield does.


text:
How can I split a string into multiple parts?
I currently gather a string via bluetooth to my arduino and the string only has 5 different letters. "HELLO". I now wish to store these individual letters in a string on their own. Right now i have this code:
First I create a single string:
String readString;

Then I read my BTLEserial which is where I get the value that is being sent to the arduino and i store it in my string:
char c = BTLEserial.read();
readString += c;

readString now has the value "HELLO". Now i want to split it and what I have tried is to do it like this:
String stringOne = readString.substring (0,1); //H
String stringTwo = readString.substring (1,2); //E
String stringThree = readString.substring (2,3); //L
String stringFour = readString.substring (3,4); //L
String stringFive = readString.substring (4,5); //O

But with this i do not get the correct values in each string.
Appreciate every help I can get! :)

An array is 0 indexed, which means that number 5 is out of index. "Hello" should be index valued 0-4 and not 0-5.
Here is a better code to try out:
void setup() {
    Serial.begin(9600);
}

void loop() {

String recivedMessage = "";

// Read
while (Serial.available())
{
    recivedMessage += Serial.read();
}

// Print debug
Serial.print("recivedMessage: ");
Serial.println(recivedMessage);

//// Uncomment the row under if you are not sure that the splitting is working
// recivedMessage = "Hello";

// Split
char first  = recivedMessage.substring(0, 1)[0];    // H
char second = recivedMessage.substring(1, 2)[0];    // E
char third  = recivedMessage.substring(2, 3)[0];    // L
char forth  = recivedMessage.substring(3, 4)[0];    // L
char fifth  = recivedMessage.substring(4)[0];       // 0

// Print debug
Serial.print("Cut message: ");
Serial.println(first);
Serial.println(second);
Serial.println(third);
Serial.println(forth);
Serial.println(fifth);

}

Yea i changed that but it is not working very good. I think I need to create another solution without strings and use char instead. Do you have any example? Would appreciate it a lot

Just change Serial.available() and Serial.Read() to whatever channel(Bluetooth) you are listning to. I have tried this code and its working. If this doesn't work for you then you have a problem with the library or something else. This code is = true; =)

I just tried it with my BLE and if i use the same type of code i only get numbers and not letters when I try this solution.

You are getting/reading bytes, thats how serial communication works, or is it binary? Anyway you need to translate it from byte to char and then concat to string. If you lookup that number on a ACSII table you will see every number correlate to that char ex. 80 is A

Found an easy solution. Just put char before the read, it will cast it as char. Ex.  (char)Serial.Read()

Seems to work well! I get out the different letters now consistently on their own. However i now face a different issue of course haha. The word i send first starts with a "H" and that prints out to the serial monitor just fine. However 5 seconds later that first letter changes to a "B" but the serial monitor still prints out "H" even though it should change to "B".

Hey are you Polling as they recommend in library? " It's important to constantly call pollACI if you want to efficiently handle data over BLE. Be sure to include this function at the top of your 'loop' function in your sketch. And as often as possible  "

What board are you using, Uno, mega, nano?

I am using a Uno! I fixed it now though. The problem was that the value kept adding onto the result. So i just added a simple function to remove the first 5 letters everytime a new result come in with 5 new letters.

Awesome! Yeah you are right. I thought it would reset itself every cycle. With Variable = "";  Anyway nicely done!

Yeah exactly i thought so to that it should reset everytime with the "" of the variable. Anyway thanks a ton for your awesome help! :)

String are the not the recommended way to use with Arduino although try using single parameter instead of two like substring(1) and let me know
char data[5];
for(int i=0;i <5 ;i++)
{
 data[i]=Serial.read();
}
char data1=data[0];
char data2=data[1];

so on and so forth ..

Yeah I guess I will need to create a solution without a string. Do you have quick examples I could see codewise? Would appreciate it a ton

You can simply declare a character array

ok and how do i get each character in the char? data[0] for the first letter ("H")? data [1] for the second  ("E") etc?

which Bluetooth library you are using by the way ?

i am using a adafruit BLE and here is the codeexample: https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/nrf-uart-in-detail

try the above code and let me know also you can take character array in place of character pointers whichever you consider  better.

That solution will not be optimal though because i only use "HELLO" as an example and sometimes the text will change to something else. The amount of numbers in the text (5) will always be the same though

would this work for you i can't understand what do you want exactly ??

will try it! one second

alright try it and let me know if further help needed

I get the correct value the first time in the monitor! But once it keeps gathering the data over n over the letter instead turns to this symbol: �
Any idea why?

your baud value might be wrong which baud value you are using also try to keep you serial monitor close sometimes serial monitor creates problems

9600 baud rate in serial monitor and Serial.begin(9600);

ok try closing serial monitor and verify values by some other ways like lighting up the leds

yea could try that but i do not currently have leds at home. if i send numbers instead of letters, would that change anything you think? so instead of 5 letters i send 5 different numbers that i store in 5 different int's?

Actually, serial monitor create conflicts between the serial connection and produces jibberish characters so you have to find a way to somehow verify it some other way if you don't have led's try some other components

yeah i do not know how to go at it because my current logic/setup is this: I send values from a phone to my arduino and the value is one word containing 5 different letters. When I recieve this word to the arduino i create "if-statements" and run certain commands if a letter is something. So for example, if the first letter in the 5 letter word i send is "H". I have an if-statement that says if (data[0] == "H") run a certain command. But as the data[0] produces jibberish characters after the first time this option will not work

you have to understand the moment you open your serial monitor the same moment you will start receiving the jibberish character so instead of using the serial monitor why don't you simply execute the commands.

I think it would be easier if you used a char array. Here's some sample code.
char recievedData[100]
int numChars = 0
//Now we are in the receiving loop
recievedData[numChars] = BLTEserial.read()
numChars++

Now that you have a character array with all of the members, you can simply use the numChars variable to figure out how much you got from the serial buffer (for example, using it as the upper limit for a for loop).

And to get the first letter out It gets stored here? recievedData[0]? I think I am missing the last part

Yes, it starts from index 0 and it will go to the counter - 1.

Also, you need to go out and learn the basics. Everything I just told you is within the material that you would learn in the first month of an intro to programming class.

it is weird because if i write it out like this: Serial.println (recievedData[0]); and check the serial monitor i see no letter but only blank space that gets recieved. I should get a "H" from that

What about when you print index 1?

Also blank space

Now i suddently get a "?" sign in a black square triangle

Is your baud rate correct?

I have it on 9600 baud in my serial monitor and in my void setupi have it on 9600 also looking like this: Serial.begin (9600); and   BTLEserial.begin();

Here is my BLE documentation and a code example that i use also: https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/nrf-uart-in-detail


text:
Using an Arduino and multiplexer for writing to multiple outputs
I'm attempting to use the multiplexer setup in this article with my Arduino Uno to control the output of LED's, as a way to fully understand the principles of multiplexing.
I'm working to modify the code in the article to switch from reading potentiometer values to writing voltage values to the LED's.
Below is the modified sketch; the biggest modified change is the loop in the writeMux function:
//Mux control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux in "SIG" pin
int SIG_pin = 3;

//Voltage value to write to the LEDs
int testValue = 255;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
}

void loop(){
  for(int i = 0; i < 9 ; i ++){
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[10][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
//    {0,1,0,1}, //channel 10
//    {1,1,0,1}, //channel 11
//    {0,0,1,1}, //channel 12
//    {1,0,1,1}, //channel 13
//    {0,1,1,1}, //channel 14
//    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  analogWrite(testValue, SIG_pin);

  //return the value
  return 0;
}

Below is a photo of my circuit:
However, none of the LED's light up.
I'm fairly certain that this is more of a problem with the code rather than the circuit...any advice is appreciated!

According to the analogWrite() documentation, apparently the trouble are that you have swapped the args.
The syntax are analogWrite(pin, value), so, the piece
//read the value at the SIG pin
analogWrite(testValue, SIG_pin);

may work if you simply change to
//read the value at the SIG pin
analogWrite(SIG_pin, testValue);

That with respect to code, and i hope it helps you. At the other hand, the circuit, may be a bit dangerous (and can damage the Arduino or the mux) to use LEDs without a current limiter series resistor (330 - 1K Ohm would be nice values, 1/4 W). At least, by a light sight in a datasheet of the CD74HC4067, shows max currents of +/- 25 mA per pin. Similar currents can be driven by the Arduino (Atmega 328P).
So, all depends on the internal construction of the 4067, if are a transparent mux, maybe just with a single resistance in the SIG_pin in that range of resistances, would be fine.
Edit - Some Circuit Troubleshooting
There are some other little tests that you can do after that change in code:

Open the wire that goes from the Arduino to the common of the mux, then place at the output of the same Arduino pin, a LED-resistor series. Then change in program only the value of testvalue at the beginning of the code and check if the led changes their intensity according to that. That would be an Ok for that pin of the Arduino.
Reply the previous step to each of the channel pins. According to the code, you should see an increasing 1 Hz, 4 bits counter (rather, a BCD counter) in thet formed 4 led array. That would be an OK for the channel selection pins.
Remove the leds and connect back the opened lines.

Any fail in steps 1 or 2 may indicate that the pin are damaged but you can use another analog pin and other pins for the channels respectively. But if at step 3 it doesn't works, may be a damaged 4067 or a little hidden bad connection...


text:
Help Led matix isn't lighting up correctly Is it a Hardware or software issue?
I am trying to reverse engineer the project from this video: https://youtu.be/zc1zbwheyE0?t=50s.
From the video a visible 10 wires are going from the LEDs to the Arduino mega, i am assuming that they are wired in a 5x5 matrix (5 rows, 5 columns) given that there are 25 keys on the Midi controller so there most be 25 LEDs.
I reconstructed the project the best a could from observing the video, but my issue is when i press 3 keys 5 LEDs light up unlike in the original video where 3 keys are pressed and 3 LEDs light up(as seen @ 0:50 of the video).
This is the issue i am having : https://i.stack.imgur.com/ppLJn.jpg.
I am thinking the issue is related to how i have my LEDs wired, but my LEDs are wired exactly the same as in the video. isn't it ? is there something i might have missed? How is the project in the video able to light up 3 LEDs without having an issue with extra LEDs lighting up in their matrix? how can i fix my circuit to replicate the video?
Here is some of my coed for turning on an LED when a key is pressed:
<include MIDI.h>

MIDI_CREATE_DEFAULT_INSTANCE();

byte anodes[5] = {30, 32, 34, 36,38};

byte cathodes[5] = {31, 33, 35, 37,39};

byte data1 = 0;

void setPinTo5V(byte pin) //set a pin given to this function to a 5V voltage source

{
    pinMode(pin, OUTPUT);
    digitalWrite(pin, HIGH);
}

void setPinToGND(byte pin) //set a pin given to this function to a GROUND (GND pin)
{
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
}

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

void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
    data1 = MIDI.getData1();

    if (data1==48){//C3
        setPinTo5V(anodes[0]);//set pin 30 to 5V
        setPinToGND(cathodes[0]);//set pin 31 to GND

        delay(1); //do nothing for 1 ms
    } //this is done for all 25 keys

}

any help would be appreciated Thanks.

duplicate of http://electronics.stackexchange.com/questions/294435/help-led-matix-isnt-lighting-up-correctly-is-it-a-hardware-or-software-issue

Please edit your question, formatting your code and adding your circuit diagram. Thanks.

Also, break the problem down into parts: if you add some trace (serial.print(...);) into your MyHandleNoteOn() function, you'll be able to tell whether you're detecting too many keys, or lighting too many LEDs.

This was what i was able to come up with, once a notes is press the blink function turns the LED on and off really fast. i am now have trouble getting the led to turn off once the notes is being pressed am not sure if the code is exiting from the while loop.
include
MIDI_CREATE_DEFAULT_INSTANCE();
define LedR 3   //
define LedC 4 //pin for each led
byte data1 = 0;
unsigned long previousMillisR[2]; //[x] = number of leds
unsigned long previousMillisC[2]; //[x] = number of leds
int Status [25];
void setup() {
MIDI.begin(MIDI_CHANNEL_OMNI);
MIDI.setHandleNoteOn(MyHandleNoteOn);
MIDI.setHandleNoteOff(MyHandleNoteOff);
pinMode(LedR, OUTPUT);
pinMode(LedC, OUTPUT);
}
void loop() {
MIDI.read();
//BlinkLedR(LedR,2000, 0);   //BlinkLed( which led, interval, one of the
stored prevMillis
//BlinkLedC(LedC, 10, 0);  //last parameters must be different for each
led
}
void BlinkLedR (int led, int interval, int array){
//(long) can be omitted if you dont plan to blink led for very long time I think
if (((long)millis() - previousMillisR[array]) >= interval){
previousMillisR[array]= millis(); //stores the millis value in the

selected array
digitalWrite(led, !digitalRead(led)); //changes led state
}
}
void BlinkLedC (int led, int interval, int array){
//(long) can be omitted if you dont plan to blink led for very long
time I think
if (((long)millis() - previousMillisC[array]) >= interval){
previousMillisC[array]= millis(); //stores the millis value in the

selected array
digitalWrite(led, !digitalRead(led)); //changes led state

}
}
void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
data1 = MIDI.getData1();
if (data1==48){//C3
Status[0]=1;
while(Status[0]==1) {
BlinkLedR(LedR, 10, 0);   //BlinkLed( which led, interval, one of the
stored prevMillis
BlinkLedC(LedC, 1, 0);  //last parameters must be different for each led
if (Status==!1){
break;
}
}
}
}
void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
data1 = MIDI.getData1();
if (data1==48){//C3
Status[0]=0;
}
}

Your code is incomplete, so it's impossible to be sure, but I suspect your problem is with the way you are lighting the LEDs in the matrix.
Think about it conceptually: your LEDs are on the junctions of rows (anodes) and columns (cathodes).  To light an LED you make the row high and the column low.
Let's call the rows R1, R2, R3, R4 and R5, and the columsn C1...C5.
Let's say the first LED you want to light is at the junction of R1 and C1.  You make R1 high and C1 low.
Now you want to light an LED on the junction of R3 and C3.  You make R3 high and C3 low.
What happens?  Four lights light up.  Why?  You have R1 and R3 high, and C1 and C3 low.  The circuit doesn't "know" that you want only two LEDs lit: it will light R1C1, R1C3, R3C1 and R3C3.
What is the solution?  Remember which LEDs you want lit.  Cycle through the matrix and deal with one row at a time: light all the LEDs you want lit in that row.  Then move to the next row and repeat.  Do this very fast.  Your LEDs will be flashing, but if you write your code properly they'll do it so fast you won't be able to see it.

This was what i was able to come up with, once a notes is press the blink function turns the LED on and off really fast. i am now have trouble getting the led to turn off once the notes is being pressed am not sure if the code is exiting from the while loop.


text:
Is there any good working MODBUS TCP master library available for Arduino?
I would like to connect with Fronius solar inverter through MODBUS TCP with Arduino to READ and WRITE register values only. I want to set the Arduino as master and the Inverter as slave. I want to use only two functions "Read Holding Registers" and "Write Single Holding Register" function code '3' and function code '6' respectively. Is there any good and working library available for these? And also an example.

Check out the library Modbus-TCP on Github. It has the facility for all the function codes as asked. It has provision for Wiznet W5100 and ENC28J60 Ethernet IC. All tested with Arduino Mega. See the well documented example code for the Wiznet module in the library.
For detailed knowledge about the library, read the index.html inside the doc folder of the library.
Here is an example code explaining a few function codes for the Arduino Mega and a W5100 module.
/*
  This is Modbus test code to demonstrate all the Modbus functions with
  with Ethernet IC WIZNET W5100

  ModbusTCP is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  ModbusTCP is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with ModbusTCP.  If not, see <http://www.gnu.org/licenses/>.

  Adopted from ModbusMaster for RTU over RS-485 by Doc Walker
  Modified by Narendra Dehury for TCP.
  copyright @ phoenixrobotix.com

*/
#define WIZNET_W5100 1

unsigned int param_value_int[7];
#include <Ethernet.h>

IPAddress ModbusDeviceIP(10, 10, 108, 211);  // Put IP Address of PLC here
IPAddress moduleIPAddress(10, 10, 108, 23);  // Assign Anything other than the PLC IP Address

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xE1 };

#include <ModbusTCP.h>

ModbusTCP node(1);                            // Unit Identifier.

void setup()
{

  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);                      // To disable slave select for SD card; depricated.

  Serial.begin(9600);
  delay(1000);
  Ethernet.begin(mac, moduleIPAddress);
  node.setServerIPAddress(ModbusDeviceIP);
  delay(6000);                                // To provide sufficient time to initialize.

}

void loop()
{
  uint8_t result;

  node.setTransactionID(random(100));           // Not necessary; but good to distinguish each frame individually.
  result = node.readHoldingRegisters(1, 12);    // Read Holding Registers

  Serial.println(result, HEX);
  if(result != 0)
  {
    Serial.println("TimeOut");

    delay(6000);
  }

  int len = node.getResponseBufferLength();
  Serial.println("Response Length: " + String(len));// See the length of data packet received.
  for (byte j = 0; j < len; j++)
  {
    Serial.print(node.getResponseBuffer(j));       // Inspect the data.
    Serial.print(" ");
  }
  Serial.println();
  node.clearResponseBuffer();
  delay(100);

  node.writeSingleRegister(5, 3);                  // Write single register
  Serial.println(result, HEX);
  delay(500);

  for (byte i = 0; i < 5; i++)
  {
    node.setTransmitBuffer(i, (i+100));
  }
  node.writeMultipleRegisters(2, 5);               // Write multiple register
  Serial.println(result, HEX);
  delay(500);

  node.writeSingleCoil(20, 1);                     // Write Single coil
  delay(500);

  node.setTransmitBuffer(0, 0b1010101001010101);

  node.writeMultipleCoils(20, 16);                 // Write multiple coils
  delay(500);
  result = node.readCoils(20, 18);
  len = node.getResponseBufferLength();
  Serial.println("Response Length: " + String(len));
  Serial.println(node.getResponseBuffer(0), BIN);

  node.clearResponseBuffer();
  delay(5000);
}

Could you explain why you think it is useful, as well as giving a summary of the link? As it stands if it a link only answer. Should the link die, at some point in the future, your answer would not be very useful.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - From Review

I have updated the post. Please share your concern for downvotes. I will try to help you.

Few days back I was facing the same situation, I could not find a suitable library for Modbus TCP where Arduino will act as a client. So I decided to make one. And that link is the link to the library. You should encourage such activity rather than asking for deletion.

Your answer had been paced in the review queue on account of its brevity, and I was merely going through the reviews... you have been on SE for over a year, and as such you should know how SE works and that link only answers are frowned upon, and an additional explanation is generally required. I didn't down vote it, btw. Your expanded answer is much better, thanks (although I'm not sure about the now suit yourself, as that could be taken the wrong way) :-)

I am sorry for all the show. Thank you for the guide. :)

hello goddland_16  this code gives some error when I compile it on Arduino IDE

@Prayuktibid accept it if it is working.

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


text:
Programming other Atmel chips(excluding Atmega 328 and 168)
How can we program any other chips of Atmel using Arduino Nano as a Arduino ISP ? Excluding the Atmega 328 and 168.

Most AVRs can be programmed using the ISP protocol. Your Nano can do the job: just follow the Arduino ISP tutorial.

For AVR's and perhaps a few others you can use avrdude with various chip-specific parameters.  Going beyond those, the question gets too broad.

Since you say:

Excluding the Atmega 328 and 168.

I'm going to assume that you already understand the general process for using your Nano as an ISP.
The Arduino IDE includes the Arduino AVR Boards hardware package which provides hardware definitions for specific configurations of:

ATmega328P
ATmega168
ATmega2560
ATmega1280
ATmega32U4
ATmega8

If your hardware matches the configuration of one of the Arduino AVR Boards then you only need to select that board from the Tools > Board menu.
It is also possible to program many other Atmel microcontrollers or alternative configurations of the microcontrollers included with the Arduino AVR Boards hardware package with your Nano but you will first need to install the 3rd party hardware package that contains the definitions for the part you want to program. You can find a fairly comprehensive list of these hardware packages here:
https://github.com/arduino/Arduino/wiki/Unofficial-list-of-3rd-party-boards-support-urls
Once you have found the hardware package that contains the necessary definitions you will need to install it. For this you have two options:
Boards Manager
The easiest installation option Boards Manager. Most Arduino hardware packages allow this type of installation (and certainly all of them on the above list):

Copy the Boards Manager package index URL.
File > Preferences > Additional Boards Manager URLs > paste URL > OK
Tools > Board > Boards Manager
Wait for downloads to complete.
Scroll down until you see the entry for the hardware package you want to install. Click on it.
Click "Install".
Wait for installation to finish.
Click "Close"

Manual Installation
Another option is to manually install the hardware package. For a simple package this would involve:

Download the hardware package
Copy the contents of the downloaded file to {sketchbook folder}/hardware. You can find the location of your sketchbook folder at File > Preferences > Sketchbook location.
Restart the Arduino IDE if it's running

After installation you will only need to select the correct board from the Tools > Boards menu. In some cases selecting a board may also add custom menu items to the Tools menu that can be used to adjust the configuration of the board (part, clock, BOD, etc.).

using Arduino Nano as a Arduino ISP

Note that the correct term is Arduino as ISP. There is a programmer named ArduinoISP that is completely different from the Arduino as ISP. The confusion is increased by the sketch used on the Arduino as ISP being named ArduinoISP.


text:
State change in Arduino Using Adafruit display
if(menustate == 1310){menustate ++;Serial.println("Execution:");Serial.println(menustate);}
             if(menustate == 1311){menustate ++;if (hr==0) menustate ++;else{aCount++;gpArray[aCount]=hr;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1312){menustate ++;if (minu==0) menustate ++;else{aCount++;gpArray[aCount]=minu;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1313){menustate ++;if (seco==0) menustate ++;else{aCount++;gpArray[aCount]=seco;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1314){menustate ++;if (dates==0) menustate ++;else{aCount++;gpArray[aCount]=dates;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1315){menustate ++;if (months==0) menustate ++;else{aCount++;gpArray[aCount]=years;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1316){menustate ++;if (years==0) menustate ++;else{aCount++;gpArray[aCount]=years;}}
             if(menustate == 1320){menustate ++;}

I am trying to get different time inputs from users by using the menustate value , but here in this code the menustate starts from 1311 and without pressing anything the state goes directly to 1320 .and i cant get to the inbetween states

You should use a switch statement ... than after the switch statement you get the in between states:
// conditional loop
{

    // prepare for switch (if something is needed)

    switch (menustate)
    {
        case 1310:
            menustate ++;
            Serial.println("Execution:");Serial.println(menustate);
            break;
        case 1311:
            menustate ++;
            if (hr==0)
                 menustate ++;
            else
            {
                aCount++;
                gpArray[aCount]=hr;
            }
            Serial.println("Execution GP:");Serial.println(menustate);
        break;

        case 1312:
            // ...

        default:
            // You can do here things with all other values
    }

    // Here you have the in between states available
}

You should put this switch statement in some conditional loop (like until an end state is reached.


text:
Connect Arduino + WiFi Shield to Raspberry Pi
I want to send collected data (temperature sensor) from my Arduino via the WiFi shield to my Raspberry Pi. Can I do that with the WiFi library that exists in Arduino IDE ?

Yes.  You could do something like run a simple TCP server on the pi, or perhaps something more complex like an MQTT-based setup, either with the pi itself as the broker or through a traditional broker either on the local network or the cloud.  At present your question lacks specifics, perhaps you should look at existing examples first.  Also keep in mind that an ESP8266 by itself may be preferable to an ATmega - based Arduino plus a shield.

I would just want it as simple as possible. Collect temperature from my balcony and send it via the local network to my Pi while I execute a python script on my Pi which waits to receive data from a local port (say 8088) and print out the data it received. To be more specific I would like to send the collected data from my Arduino to the IP address of my Pi.

Good, a web search should readily find you plenty of examples.  Questions should generally be asked after you search and find something specifically confusing or that does not work as expected, not as a substitute for research.

Yes, all right. I also searched but haven't found until now exactly what I wanted and I want to be sure before I buy certain things. However, hank you for your time and help!

Do you have power on the balcony? Cause if you have to run of batteries, using wifi isn't very energy efficient.

@Gerben Yes, I have power at the balcony!


text:
NEO 6M doenst provide coordinates
I do a school project (CanSat) it's an international project. But my problem is my GPS. I tried 2 different codes. Both they say the GPS is connected. They GPS led doesn't provide any light.
wiring:
UBlox Neo 6M
Arduino leonardo
Rx (GPS) to port 8
Tx (GPS) to port 9
Vcc to Vcc
Gnd to Gnd
Btw I sit near the window.
First code:
The gps.encode(c) is always false/0 I don't know why this one doesn't work.
#include <SoftwareSerial.h>
#include <TinyGPS.h>

SoftwareSerial mySerial(9, 8);
TinyGPS gps;

void gpsdump(TinyGPS &gps);
void printFloat(double f, int digits = 2);

void setup()
{
  // Oploen serial communications and wait for port to open:
  Serial.begin(9600);
  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  delay(1000);
  Serial.println("uBlox Neo 6M");
  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
  Serial.println("by Mikal Hart");
  Serial.println();
  Serial.print("Sizeof(gpsobject) = ");
  Serial.println(sizeof(TinyGPS));
  Serial.println();
}

void loop() // run over and over
{
  bool newdata = false;
  unsigned long start = millis();
  // Every 5 seconds we print an update
  while (millis() - start < 5000)
  {
    if (mySerial.available()){
      char c = mySerial.read();
     // Serial.println(c);  // uncomment to see raw GPS data
      if (gps.encode(c)){
        newdata = true;
        break;  // uncomment to print new data immediately!
      }
    }
  }

  if (newdata)
  {
    Serial.println("Acquired Data");
    Serial.println("-------------");
    gpsdump(gps);
    Serial.println("-------------");
    Serial.println();
  }

}

void gpsdump(TinyGPS &gps)
{
  long lat, lon;
  float flat, flon;
  unsigned long age, date, time, chars;
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned short sentences, failed;

  gps.get_position(&lat, &lon, &age);
  Serial.print("Lat/Long(10^-5 deg): "); Serial.print(lat); Serial.print(", "); Serial.print(lon);
  Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");

  // On Arduino, GPS characters may be lost during lengthy Serial.print()
  // On Teensy, Serial prints to USB, which has large output buffering and
  //   runs very fast, so it's not necessary to worry about missing 4800
  //   baud GPS characters.

  gps.f_get_position(&flat, &flon, &age);
  Serial.print("Lat/Long(float): "); printFloat(flat, 5); Serial.print(", "); printFloat(flon, 5);
    Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");

  gps.get_datetime(&date, &time, &age);
  Serial.print("Date(ddmmyy): "); Serial.print(date); Serial.print(" Time(hhmmsscc): ");
    Serial.print(time);
  Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");

  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  Serial.print("Date: "); Serial.print(static_cast<int>(month)); Serial.print("/");
    Serial.print(static_cast<int>(day)); Serial.print("/"); Serial.print(year);
  Serial.print("  Time: "); Serial.print(static_cast<int>(hour+8));  Serial.print(":"); //Serial.print("UTC +08:00 Malaysia");
    Serial.print(static_cast<int>(minute)); Serial.print(":"); Serial.print(static_cast<int>(second));
    Serial.print("."); Serial.print(static_cast<int>(hundredths)); Serial.print(" UTC +08:00 Malaysia");
  Serial.print("  Fix age: ");  Serial.print(age); Serial.println("ms.");

  Serial.print("Alt(cm): "); Serial.print(gps.altitude()); Serial.print(" Course(10^-2 deg): ");
    Serial.print(gps.course()); Serial.print(" Speed(10^-2 knots): "); Serial.println(gps.speed());
  Serial.print("Alt(float): "); printFloat(gps.f_altitude()); Serial.print(" Course(float): ");
    printFloat(gps.f_course()); Serial.println();
  Serial.print("Speed(knots): "); printFloat(gps.f_speed_knots()); Serial.print(" (mph): ");
    printFloat(gps.f_speed_mph());
  Serial.print(" (mps): "); printFloat(gps.f_speed_mps()); Serial.print(" (kmph): ");
    printFloat(gps.f_speed_kmph()); Serial.println();

  gps.stats(&chars, &sentences, &failed);
  Serial.print("Stats: characters: "); Serial.print(chars); Serial.print(" sentences: ");
    Serial.print(sentences); Serial.print(" failed checksum: "); Serial.println(failed);
}

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

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

  number += rounding;

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

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

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

Second code:
Location is invailed but i will get the time with an 1 hour and some minuts diffrence.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 9, TXPin = 8;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

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

  Serial.println(F("DeviceExample.ino"));
  Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
  Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
}

void loop()
{
  // This sketch displays information every time a new sentence is correctly encoded.
  while (ss.available() > 0)
    if (gps.encode(ss.read()))
      displayInfo();

  if (millis() > 5000 && gps.charsProcessed() < 10)
  {
    Serial.println(F("No GPS detected: check wiring."));
    while(true);
  }
}

void displayInfo()
{
  Serial.print(F("Location: "));
  if (gps.location.isValid())
  {
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.print(gps.location.lng(), 6);
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Date/Time: "));
  if (gps.date.isValid())
  {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid())
  {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.println();
}

another small weird thing is, that if I upload the code to the Arduino the Serial monitor says normally COM6(Arduino leonardo), but when it is just finished it goes to COM6 only but the program still works.
I will appreciate all the help I can get :)

Why use software serial if you have hardware serial available?

I don't know really the diffrence between Software serial and hardware serial if you can explain the diffrence when to use the one insteed of the otherone than would that be nice. But besides that it aren't my codes. I found the codes and I saw in the comments of that side that the codes worked.
the first code the gps.encode(c) is false, if I want the raw gps data I do Serial.println(c); where I get the raw gps date but it wouldn't encode so the code can proceed. So my question is there something wrong with the code or could there made an improving.

How about outside with clear sky?  Does the "They GPS led doesn't provide any light" indicate that the module isn't getting a fix?

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


text:
Arduino board with built-in Bluetooth
I would like to find an Arduino with built-in Bluetooth.
I know about the HC-06, the shields and the other Bluetooth modules, but i would like to have built in Bluetooth for eliminating the risk for miscommunication on the serial port.
The official Arduino foundation did produce an board but it's retired now.

Wow! Look what I found on GOOGLE! :)

By the way, how could miscommunication on a Bluetooth shield be any different from miscommunication on an integrated Bluetooth for a board?

Yeah i know what google is. Why it would be better? Less moving parts, well tested board. If you think its an dumb question dont answer then. There are plenty of other post waiting for your knowledge.

I'm not being sarcastic, but have you thought this through?  I appreciate that there might be an issue with serial comms, but I would have thought most of that would be programming errors rather than a 'hardware' issue.  If I'm not right say!  Having a separate board would give you the advantage of being able to spare it or upgrade it to support BT5, BT6 or even BT 921!  Also a separate board means you have more options over what the Arduino board can be.  Maybe looking at why you have serial problems would be a good point to focus on?

@Sigma - If a board becomes a moving part, you need to check your soldering :D

Yeah you are probable right. But when the application iworks 98% of the time. It makes it hard to understand or debugg what the 2% failures are because of. I need to be 100% sure it is programmatic and not hardware.

@Sigma Well I don't think it's a dumb question. Perfectly reasonable to ask something that you're not sure of. I was just curious on why you weren't looking for a shield instead but that's good reason :)

As far as officially Arduino boards with Bluetooth, I can't think of any on the top of my head. Then again, I'm not entirely sure if Adafruit (for an example) would consider themselves to be an official Arduino brand, though I doubt it.

Adafruit could be a good place to look. Thanks! Have seen that there has been some kickstarter boards, but they are not mass produced.

What about using an ESP32 with integrated BT?

@CodeGorilla Yeah that could be a solution.

Arduino has just released a MKR WIFI 1010 board that includes an ESP32 module that allows Bluetooth connectivity. It's mainly an internet of things board but it supports:

Bluetooth low energy, BLE
Wifi

Yes Im using that one, great board.

There is this board called Bluno
Its an Arduino UNO Based board with built in Bluetooth 4.0
Bluno - An Arduino Bluetooth 4.0 (BLE) Board

This is my currently favourite Arduino compatible board:
https://wiki.wemos.cc/products:d32:d32

ESP32 is great: offers both wi-fi, Bluetooth and BLE connection as well as lots of GPIO.
9 GPIO's can be used as capacitive touch sensors (it has 10, but only 9 are available).

This is also a great option.


text:
Sketch Memory in Pro
    void storedata(File filename ,int type , String data)
{
    if(type == 1){
      Serial.println("Group Creation");
    }
    //Storing Data into file
    pinMode(10, OUTPUT);
    if (!SD.begin(SD_CS_PIN)) {
    Serial.println("initialization failed!");
    return;
  }
    Serial.println("initialization done.");
    filename = SD.open("filename.txt", FILE_WRITE);
    if (filename) {
    Serial.print("Writing to filename.txt...");
    SdFile file("sdfile.txt", O_WRITE | O_CREAT);
    if (!file.isOpen()) {
    Serial.println("filename.txt");
   }
    sdfile.println(data);
    //close the file:
    filename.close();
    Serial.println("done.");
    }else{
    // if the file didn't open, print an error:
    Serial.println("error opening filename.txt");
  }}

Im using this function to write on the Sd card , before calling this function the sketch memory is 28802 bytes ie ) 93% , simply just by calling this function from setup increased the sketch memory to 102% and iam unable to compile is there any unusual memory usage in this code ?

Try shortening the text inside the serial.printf statements. That should already shave off a few bytes, though that's probably not enough.

@Gerben  What i dont Understand is Just this simple Function taking 10 % of memory,Im using functions all over my program , ill still try to reduce the code and optimize it what puzzles me is how could only this function could raise the memory from 93% to 103%?

You're forgetting that you are also calling some functions from the SD library. Those functions also contain a lot of code.

The good thing is that flash memory is instantly to be checked (you get the result after a (succesfull) compilation.
Refactoring you can do to reduce space:

prevent duplicate code; try to make a function from duplicated code and call it whenever needed; this also makes the program much more easy to maintain (bugs in those part have to be solved only once, and changed only adapted once).
If the code is almost the same but not an exact duplicate, use parameters in the function for the differences.
Remove code that does not have a function but still is called. The compiler can automatically delete UNUSED code, but USED code that has no function you have to do yourself.
Normally PROGMEM and F() is used to store arrays/strings in FLASH instead of SRAM, since mostly SRAM is more scarce, in your case you should not use this.
Try to optimize code using less lines. This does not mean you have to remove spaces or make big oneliners; that will not help. But changing code structurally without changing the functionality will reduce flash memory.
Remove unused libraries (although these are probably optimized out by the compiler)
Global variables/structs/arrays and lots of const variables will cost memory to. For const values it might be useful to use #defines, however this will reduce maintainability/type checking.
Remove debugging code (printf's for debugging functionality); I never tried but I think it should be feasible to make unit tests separately from the sketch code.
A tricky way that could help is to optimize the libraries and reducing code there when needed. It is not useful to throw away functions that will not be called though. And debugging information should not be present, but maybe you can remove some conditions or code fragments that will never occur.

If you have a function that isn't called the compiler will just delete it (optimise it out). It also deletes any functions that the function calls that aren't used anywhere else.
By then calling that function the compiler keeps it, along with any other functions it relies on.
That includes the SDFat library code, much of which will have been removed before.
To make it now fit you will have to optimise your program. Look for blocks of code that do the same thing and replace them with calls to a function. Look for parts that could be replaced by a loop and an array instead of discrete calls to the same function(s) over and over again. Things like that.
Either that or use a board that has enough flash for your project.

Im not using SD library , im using Sdfat library since it uses less memory.

It still needs that 512 byte buffer though - there's no getting away from that.

The problem is too little flash memory, not RAM.

Ah. Well, optimise your program then. Get rid of repeated blocks of code by using functions. Either that or use a board with more flash.

I have changed my answer in the light of this new infor,ation.

Actually There is a way to Reduce the Memory Occupancy to a Considerable level ie) upto 10 % . Replace all the if and if else Loops with Switch case , By this we can reduce the memory usage .Or atleast it did in my case in which i have used lots of if and if else Loops @Majenko


text:
Arduino car parking program help

Here is a program and circuit diagram of an Arduino-based car parking (copy pasted from http://www.arduining.com/2012/10/13/arduino-parking-lot-filled/ ) I want to replace the Exit and End switch with IR sensor or ultrasonic sensor.
/*ParkingL02.pde
  Arduining.com 08 JUL 2012
  Code used in the production of the Youtube material.
*/
#include <Servo.h>
Servo myservo; // create servo object to control a servo
#define ServoM 12 //Connected to the servo motor.
#define Bright 11 //servo library disable PWM on pins 9 and 10.
#define Exit 9 //Pin connected to the EXIT button.
#define In 8 //Pin connected to the IN button.
#define BarLow 177 //Low position of the barrier.
#define BarUp 95 //Up position of the barrier.
#define CAPACITY 8 //Capacity of the parking lot.
#define INTEN 80 //Display intensity %
//Pins conections to segments (cathodes).
#define segA 0
#define segB 1
#define segC 2
#define segD 3
#define segE 4
#define segF 5
#define segG 6

int SensorIn(void);     // declare the sensor function for entering autos

//Array with the segments to represent the decimal numbers (0-9).
byte segments[10] = {
  // pgfedcba <--- segments
  B00111111, // number 0
  B00000110, // number 1
  B01011011, // number 2
  B01001111, // number 3
  B01100110, // number 4
  B01101101, // number 5
  B01111101, // number 6
  B00000111, // number 7
  B01111111, // number 8
  B01101111 // number 9
};

void setup() {
  myservo.attach(ServoM); // attaches the servo.

  pinMode(Exit, INPUT); // set "EXIT" button pin to input
  pinMode(In, INPUT); // set "IN" button pin to input

  digitalWrite(Exit, HIGH); // Connect Pull-Up resistor.
  digitalWrite(In, HIGH); // Connect Pull-Up resistor.

  pinMode(segA, OUTPUT);
  pinMode(segB, OUTPUT);
  pinMode(segC, OUTPUT);
  pinMode(segD, OUTPUT);
  pinMode(segE, OUTPUT);
  pinMode(segF, OUTPUT);
  pinMode(segG, OUTPUT);
  pinMode(Bright, OUTPUT);

  analogWrite(Bright, 255 * INTEN / 100);
  myservo.write(BarLow); //Barrier in the low position
  // delay(1000);
}

int Available = 9; // Number of places available.

void loop() {
  Display(Available);
  if ( SensorIn() == 0 )
  {
    if (Available != 0) {
      Available--;
      myservo.write(BarUp);
      delay(3000);
      myservo.write(BarLow);
    }
  }
  if (digitalRead(Exit) == 0)
  {
    if (Available != CAPACITY) {
      Available++;
      myservo.write(BarUp);
      delay(3000);
      myservo.write(BarLow);
    }
  }
}

/*-------------------------------------------------------------------
  Put the segments according to the number.
  --------------------------------------------------------------------*/
void Display(int number) {
  byte segs = ~segments[number]; //"~" is used for commom anode.
  digitalWrite(segA, bitRead(segs, 0) );
  digitalWrite(segB, bitRead(segs, 1) );
  digitalWrite(segC, bitRead(segs, 2) );
  digitalWrite(segD, bitRead(segs, 3) );
  digitalWrite(segE, bitRead(segs, 4) );
  digitalWrite(segF, bitRead(segs, 5) );
  digitalWrite(segG, bitRead(segs, 6) );
}

// We've moved the "sensor code" for entering autos to this function
// For now, the "In-sensor" is just a push-button.
int SensorIn(void) {
  return ( digitalRead(In) );
}

It might help if you format your code.

Theoretically, an IR sensor could/would work exactly the same as an button (code wise).

I want circuit with connection of IR Sensor

i need this code but i have and lcd i'm doing the same project with two IR sensors so please if anyone have done it with lcd i will be thankfull i have to show it next week please help

If it were me, I'd approach it this way:

Move each button read (digitalRead(xxx)) into its own routine.
Get everything to work, still using the buttons.
Write a separate sketch for whatever sensor or sensors you're going to use. All it needs to do is light an LED so you can be sure when it is detecting and when it isn't.
Now replace the contents of each of the new button routines (from step 1) with the sensor code you just wrote. Your routines should return the same values for sensor detection that they returned for button detection. You shouldn't need to change any other part of your original code.
Fix any bugs you made in the step above, and you're done.

Update:
I've just indented your code (above) and made one of the changes I suggested. You'll see that I made a new function called SensorIn() and put the code to read the "In" button there. Do the same thing for the "Exit" button.
Then, using a new sketch, learn to write code for whatever kind of sensor you want to use for entering autos. When that works, copy it into this sketches 'SensorIn()' function, replacing the line that reads the push button. Get this much working.
Then do the same thing, write a new sketch for the exit sensor until you can make that work reliably, too. Of course, if you choose to use the same kind of sensor for Exit as you used for In, you can just re-use the same code. Get this sketch working again.
Now you should have a sketch, just like your pushbutton sketch, but one that uses two real sensors instead of buttons.

Can u rewrite the code for me ..  and paste for me plzz... I'm kinda nooob..N  I'm getting confused... Writing separate code for ultrasonic sensor.. and calling in place of button .  Causing more error

@ManlamKonyakArolim If you don't know how to do that ...

The coding and project is completed ..its an old question :) thank you anyway


text:
Which motors to choose?
I don't know if this is the right place to ask, but I'm an arduino newbie and I'm seeking some suggestions.
For my Robotics subject at University, I'm going to build a robot that should be able to move some objects (dragging them on the ground, not lifting them) from one place to another. I was looking around the web for the necessary components when I stumbled on a doubt: are 3-6V motors powerful enough for the wheels? Or do I need something more powerful like the 12V motors?
I'm not sure of what to choose between step motors or servo motors either, what do you suggest?
Oh and last thing, I opted for a L293D bridge driver for the motors, is this a good idea?
Thanks in advance!

Robotics Stackexchange would be better for this question.  I suggest deleting it here and adding it there.

A 12 volt DC motor is good for dragging items, but then again it depends on the items weight. Stepper is used for millimeter precision, like 3D printing. Servo is an DC motor with precision for 180 degree movement, like robot arms. If the moving object is over 1kg you should look into geared DC motors or even the stronger brushed motors, or geared brushed motors. Whats the max weight?

We still don't know yet, the professor did not give the full specifications yet. They should be simple balls of about 7/10 cm diameter, so they will be definetly under 1kg weight

You need to size your motors correctly depending on how much load they are expected to overcome. You first consideration should be how much maximum force would your robot need to exert at any given time....
For a robot just starting to drag a load (assuming the surface is flat) behind it, the robot would have to at least apply a force just greater than...
Maximum Static Frictional Force due to Robot's own weight on its wheels + Maximum Static Frictional Force due to object being dragged.
Maximum Frictional Force = Normal Force (weight) * coeff of Friction for the two surfaces
So for example, the coeff of friction between a brick (load) and ice (surface) would be lesser than between a brick (load) and asphalt (surface).
You need to do these calculations first.
If the speed limitations of your robot are inconsequential, then you only need to choose your wheel size and then determine how much torque your motor needs to be able to generate.
You do this like so.....Motor Torque needed = Force to generate / (radius of wheel * number of motors you want to install). So for instance, the torque needed per motor in a 4WD robot would be half that needed for an equivalent robot with only 2 powered wheels.
Once you have the motor torque you need, you can choose a motor and then choose a suitable power source for this motor.
Now repeat ALL the steps above this time accounting for the weight of the motors and the battery.


text:
Programming Chinese Arduinos
I have an authentic Arduino UNO, but I didn't want to pay full price for a new one to build semi perminate projects, so I bought a few ATMEGA328P-PU chips off of AliExpress:
https://www.aliexpress.com/item/1pcs-lot-ATMEGA328P-PU-CHIP-ATMEGA328-Microcontroller-MCU-AVR-32K-20MHz-FLASH-DIP-28/32346944696.html
But when I try to use Arduino IDE to upload the sketch to the new chips, I get these errors:

avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

It happens 10 times and quits.
It works fine when I put the original chip back in.
If anyone has any experience with this I'd be very grateful!
EDIT:
Trying the burn bootloader steps, and I'm getting a new error.
Steps I took:
I'm doing the 8MHz option, and so I downloaded the breadboard-1-6-x.zip file. (I'm using Arduino IDE 1.6.5 on Mac).
I uploaded the ArduinoISP example to my working chip, then wired it up to the breadboard as per the picture.
I switched the programmer to Arduino as ISP and set the board to ATMEGA328 on breadboard (8MHz clock)
I went to tools>burn bootloader, and got this error:

Arduino: 1.6.5 (Mac OS X), Board: "ATmega328 on a breadboard (8 MHz
  internal clock)"
/Users/andy/Desktop/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude
  -C/Users/andy/Desktop/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf
  -v -patmega328p -cstk500v1 -P/dev/cu.usbmodem411 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0x05:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xE2:m
avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25
           Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
           Copyright (c) 2007-2009 Joerg Wunsch
     System wide configuration file is "/Users/andy/Desktop/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
     User configuration file is "/Users/andy/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : /dev/cu.usbmodem411
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200 avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x15
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14
avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x02
avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
           Hardware Version: -1543397124
           Firmware Version: 2165568.-1543397124
           Topcard         : STK502
           Vtarget         : 1.8 V
           Varef           : 0.0 V
           Oscillator      : Off
           SCK period      : 0.1 us
avrdude: stk500_initialize(): (b) protocol error, expect=0x10,
  resp=0x01 avrdude: initialization failed, rc=-1
           Double check connections and try again, or use -F to override
           this check.
avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x10
avrdude done.  Thank you.
Problem uploading to board.  See
  http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Making a little progress at least...
Solution:
I was using this layout:

Since that was failing I decided to try using the nano that I got at the same time, and after a lot of research I found this video:
https://www.youtube.com/watch?v=94KCYqS3--A
I jumpered the pins shown at the 1:30 mark to the ICSP port, and tried burning the bootloader twice per chip, and on the second try it worked! Don't know why it had to be tried twice.
I may go back to trying the breadboard method, just to see if it works if I try burning it twice.

Part of an authentic Arduino is a preexisting bootloader on the chip.

You need a Chinese programmer as well, since the Chinese chips don't understand our language. I've had luck with the avr USB/ASP or USB/isp series. http://r.ebay.com/lALcjc

^ True solution, but not right explanation, Ben Heck covers the difference very well in the beginning of this: "make an avr development board" video (https://youtu.be/ncobWc61wL4)

How is it connected? And you can add -F to the avrdude command?

It's because these are unprogrammed chips, meaning they haven't had a bootloader programmed into them yet. Here is a tutorial for using your Arduino board to program a bootloader into them (there are many such tutorials available).
It only needs to be done once per chip so it will be worth your while to program all of them, once you have set up to do one. This is a very economical way to build "home-brew-duinos".

I don't have the crystal, so I'll have to order some I suppose... I did see in this Instructible that you can run at least some of them without the crystal. However, I also got an Arduino Nano that works... Could I put the 328P-PU into the UNO, and then program it with the Nano?

@AndyD273: Sure, just use the ISP connection near the main MCU, not the ISP connection near the USB connector.

you can run them at 8mhz w/o a crystal, 16 with one.

Ok, I got it wired up using the internal 8mhz clock as in your link, but I'm getting a new error. I posted it above.


text:
How to detect lipo battery % charge left?
I am currently working with a few robotic projects where i use lipo batteries. Currently I am working with a 1500 mah 3s lipo.
With my current setup I am using a arduino uno and a power distribution board. I put my lipo charger in my power distribution board which has two connections where I put two cables that goes to the VLN and GND.
(If needed I can make a quick schematic to explain it better!)
How can I now see the current battery percentage of the lipo?
I came across a project that uses this codesnippet:
long previousMillis = 0;

long interval = 1000;

int sensorValue = analogRead(A0);
float voltage = sensorValue * (5.0 / 1023.0);

unsigned long currentMillis = millis();

if (currentMillis - previousMillis > interval) {
  previousMillis = currentMillis;
 if (voltage <= 3.5)
      Serial.println("Low Battery");
     else
      Serial.println(voltage, DEC);
}

This snippet works with the A0 and I do not have anything connected there so I assume not.
Appreciate every help! :)

Typically LIPOs have 3.7v at full charge. This code monitors the LIPO voltage and flags the battery as "low" if the voltage drops below 3.5v.

@Mazaryk 3.7V is the nominal voltage for regular lithium batteries. 4.20-4.35 Volt when fully charged. However  lithium-iron-phosphate batteries do have a full charge at around 3.7 V.

@Gerben, You are right. I meant to say "discharge". :)

LiPo batteries do not work well for percentage of charge remaining when using voltage as a reference. Lithium chemistry batteries hold a voltage quite close to level up to the point of near-exhaustion. That is to say, you can deplete such a battery by 80%, leaving only 20% capacity and have a few tenths of a volt reduction, depending on the configuration of your battery pack.
Unfortunately, should you continue to deplete the battery, damage may result. Some will say that damage WILL result.
The only certain way to determine a battery capacity is to use a smart charger and/or a smart discharger (often combined into one) to profile a battery.
For example, I have a 2000 mAh battery. After a few conditioning runs, either in use or on the smart dis/charger, the battery shows as having 1600 mAh capacity to 80% discharge.
Using a device to monitor the discharge rate, one can determine that if one uses 1550 mAh of the capacity, one is quite close to the risky cut-off point.
To continue discharging, there is risk involved in the lifespan of the battery.
LiPo batteries will have greater than 4 volts reading immediately off the charger and will "flatten" to optimum voltage in a short time and hold very close to that level, depending on the current load, until it virtually vanishes at the cut-off point.
One can approximate a safe voltage for the cut-off point, but one risks the chance of an inaccurate volt meter. Collecting ampere-hours as a reference for cut-off is the most accurate method and also allows more capacity with less chance of damage.

Characterize a few such batteries by putting them through a charge / discharge cycles so you can link their voltage with remaining capacity.

The data sheet for the battery might already contain a nice discharge curve.


text:
arduino + mpu6050 + nrf24l01 >>>>>>>>>>>>nrf24l01 + arduino ( Not running fluently)
this is my setup: I have an arduino uno + mpu-6050 + nrf24l01 all attached together and am transmitting data from that mpu-6050 to another arduino with an nrf24l01 attached to it. I got the arduinos to communicate with each other and transmit data ( ypr) wirelessly but it's still laggy and jumpy. Before I was getting FIFO overfull messages but I managed to somewhat fix that. Yet the data being transferred is still not running to stable nor smoothly. PLEASE HELP ME find the problem why these arduinos aren't transferring data fluently and smoothly. I posted the Receiver and transmitter codes down below. Also, I am illustrating the code on Processing 3.2.3, hence the teapot parts. THANK YOU
**************************RECEIVER*****************************************
{
    #include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

// format used for the InvenSense teapot demo
#define OUTPUT_TEAPOT

RF24 radio(7, 8);//pin assignment
unsigned long t0;
unsigned long t1;
float ypr[3];
uint8_t teapotPacket[14] = { };

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

  while (!Serial);
  Serial.begin(115200);

  radio.begin();
  radio.openReadingPipe(1, 0xF0F0F0F0A1LL);
  radio.openReadingPipe(2, 0xF0F0F0F0A2LL);

  radio.startListening();
  t0=0;
}
byte pipeNum=0; //variable to hold which reading pipe sent data
void loop()
{
  t1=millis();
  /*digitalWrite(13,HIGH);
  delay(500);
  digitalWrite(13,LOW);
  delay(500);
  */
  if (t1-t0>100){
  if (radio.available(&pipeNum))
  {

    typedef struct YPR_RX {
      int y;
      int p;
      int r;
    } YPR_RX;
    YPR_RX ypr_rx;

    //radio.read(&ypr_rx, sizeof(ypr_rx));
   // teapotPacket = new uint8_t teapoPacket(radio.getPayload)

    radio.read(&teapotPacket, sizeof(teapotPacket));
   // radio.read(&teapotPacket, sizeof(radio.getPayloadSize()));
//    radio.SetDatarate();
    uint8_t newTeapot[14] = {'$', 0x02, teapotPacket[2],teapotPacket[3],teapotPacket[4],teapotPacket[5],teapotPacket[6],
                                        teapotPacket[7],teapotPacket[8],teapotPacket[9], 0x00, 0x00, '\r', '\n' };
    Serial.write(newTeapot, 14);
    newTeapot[11]++;

            Serial.print(newTeapot[2]);
            Serial.print("\t");
            Serial.print(newTeapot[3]);
            Serial.print("\t");
            Serial.print(newTeapot[4]);
            Serial.print("\t");
            Serial.print(newTeapot[5]);
            Serial.print("\t");
            Serial.print(newTeapot[6]);
            Serial.print("\t");
            Serial.print(newTeapot[7]);
            Serial.print("\t");
            Serial.print(newTeapot[8]);
            Serial.print("\t");
            Serial.println(newTeapot[9]);

/*
    Serial.print(ypr_rx.y);
    Serial.print("\t");
    Serial.print(ypr_rx.p);
    Serial.print("\t");
    Serial.print(ypr_rx.r);
    Serial.print("\t");
    Serial.println();
    */

    t0=t1;

    //Serial.println("X-acceleration");
    //int number=atol(text);
    //Serial.println(number);
    //Serial.println((int)text);
    //Serial.println(value);
    //delay(100);

  }
  }

}
}

*********************************TRANSMITTER************************************
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

// format used for the InvenSense teapot demo
#define OUTPUT_TEAPOT

RF24 radio(7, 8);//pin assignment
unsigned long t0;
unsigned long t1;
float ypr[3];
uint8_t teapotPacket[14] = { };

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

  while (!Serial);
  Serial.begin(115200);

  radio.begin();
  radio.openReadingPipe(1, 0xF0F0F0F0A1LL);
  radio.openReadingPipe(2, 0xF0F0F0F0A2LL);

  radio.startListening();
  t0=0;
}
byte pipeNum=0; //variable to hold which reading pipe sent data
void loop()
{
  t1=millis();
  /*digitalWrite(13,HIGH);
  delay(500);
  digitalWrite(13,LOW);
  delay(500);
  */
  if (t1-t0>100){
  if (radio.available(&pipeNum))
  {

    typedef struct YPR_RX {
      int y;
      int p;
      int r;
    } YPR_RX;
    YPR_RX ypr_rx;

    //radio.read(&ypr_rx, sizeof(ypr_rx));
   // teapotPacket = new uint8_t teapoPacket(radio.getPayload)

    radio.read(&teapotPacket, sizeof(teapotPacket));
   // radio.read(&teapotPacket, sizeof(radio.getPayloadSize()));
//    radio.SetDatarate();
    uint8_t newTeapot[14] = {'$', 0x02, teapotPacket[2],teapotPacket[3],teapotPacket[4],teapotPacket[5],teapotPacket[6],
                                        teapotPacket[7],teapotPacket[8],teapotPacket[9], 0x00, 0x00, '\r', '\n' };
    Serial.write(newTeapot, 14);
    newTeapot[11]++;

            Serial.print(newTeapot[2]);
            Serial.print("\t");
            Serial.print(newTeapot[3]);
            Serial.print("\t");
            Serial.print(newTeapot[4]);
            Serial.print("\t");
            Serial.print(newTeapot[5]);
            Serial.print("\t");
            Serial.print(newTeapot[6]);
            Serial.print("\t");
            Serial.print(newTeapot[7]);
            Serial.print("\t");
            Serial.print(newTeapot[8]);
            Serial.print("\t");
            Serial.println(newTeapot[9]);

/*
    Serial.print(ypr_rx.y);
    Serial.print("\t");
    Serial.print(ypr_rx.p);
    Serial.print("\t");
    Serial.print(ypr_rx.r);
    Serial.print("\t");
    Serial.println();
    */

    t0=t1;

    //Serial.println("X-acceleration");
    //int number=atol(text);
    //Serial.println(number);
    //Serial.println((int)text);
    //Serial.println(value);
    //delay(100);

  }
  }

}

Could you please describe a bit more, what's the exact issue you have? As "not stable and smooth" is rather generic.

Why does the receiver do a 100 ms wait?

@avamander The problem it doesn't have regular readings. Like when I have the mpu-6050 plugged directly into my computer the readings run smoothly and dont lag. When I make wirelessly, the information lags some and its all skippy along with some lag. Especially when I put it on Processing for visuals, it lags and randomly skips readings. I'm just not sure what the problem is, maybe something with the buffer?

As always with nRF24L01+, attach a 1000uF electrolytic capacitor to the GND and 3.3V on the module itself.

The possible problem could be with the hardware setup? Could it not be something with the code itself?


text:
Sending NEC IR signals makes LED strip blink
I'm trying to make my ESP8266 (running NodeMCU meaning Arduino code gets compiled on it). I followed a guide and now I can read the IR codes from my remote using my Arduino UNO, and then send them to the LED strip. So far sending it actually works, but it blinks REALLY fast.
Some part of me tells me it's trying to send it twice or the radio frequency is wrong. For TVs and so on, it doesn't really matter, as you can't turn on and off a TV instantly. You can with this LED strip though. This is how I send my NEC signal to the strip:
irsend.sendNEC(0xFF02FD, 433);

433 is the frequency (433 kHz), as I read that's the most common frequency these LED strips work at. The entire code I used can be found here. Do you think I have a frequency issue? I have tried a lot of different frequencies and they all seem to do the same thing.
Also, when I try to send the exact same NEC signal to my receiver, I get two different results. It is only being sent one time as well. Here is what I receive:
Using the actual receiver:
Decoded NEC(1): Value:FF02FD (32 bits)
Raw samples(68): Gap:51848
  Head: m8750  s4550
0:m450 s650 1:m450 s650      2:m450 s650    3:m450 s650
4:m500 s650 5:m450 s650      6:m450 s650    7:m450 s650
8:m450 s1750    9:m500 s1750         10:m450 s1750  11:m450 s1750
12:m500 s1750   13:m450 s1750        14:m450 s1750  15:m500 s1750

16:m450 s650    17:m450 s650         18:m450 s650   19:m450 s650
20:m500 s600    21:m500 s650         22:m450 s1750  23:m450 s650
24:m450 s1750   25:m500 s1700        26:m500 s1750  27:m450 s1750
28:m500 s1700   29:m500 s1750        30:m450 s650   31:m450 s1750

32:m450
Extent=66900
Mark  min:450    max:500
Space min:600    max:1750

Using irsend.sendNEC(0xFF02FD, 433)
Decoded Unknown(0): Value:0 (0 bits)
Raw samples(38): Gap:18088
  Head: m8850  s4550
0:m500 s1750    1:m500 s650      2:m450 s650    3:m500 s650
4:m500 s650 5:m450 s650      6:m500 s650    7:m450 s1800
8:m450 s700 9:m450 s1800         10:m450 s1800  11:m450 s1800
12:m450 s1800   13:m450 s1800        14:m450 s1800  15:m450 s650

16:m500 s1750   17:m500
Extent=43200
Mark  min:450    max:500
Space min:650    max:1800

EDIT: I forgot to mention: 0xFF02FD is the signal power/on/off button. If I change the 0xFF02FD to anything else (like 0xFF18E7 to make it yellow), the LED strip will just blink.

Huh, are you controlling a ledstrip or a TV (by ir)?

@Paul LED strip :) But as you can see below, I managed to fix this.

Ah wait, you've got an ledstripcontroller with IR? Or are you actually blinking a whole strip in IR signals? xd

38kHz is the most common for IR. For RF remotes it's 433MHz. So I think that where you got that number from.

32 kHz seems to be the winner. Now all my codes work! Damn, if I only had read that ONE SITE that showed it haha.


text:
How do I Continuity Test/Troubleshoot a Linksprite RS232 V2 Shield?
I have a Linksprite RS232 v2 adapter (which uses a MAX232 chip), as per this image. I have soldered on the headers and tested the pins to make sure there are no solder bridges. I have set the jumpers so that D2 is set to TX and D3 to RX. However, I can't establish comms through the device using the Software Serial library, regardless of how I set the jumpers. (Real Term doesn't show me anything when a USB-to-Serial adapter is connected. However, if I change the baud rate to 9600, I get about 5 bytes of 0x00, then nothing.)
If I disconnect the shield from the Arduino board then supply 5V to pin 2 or 3 (from an Arduino) and connect pin 5 of the DB/E9 to the Arduino's GND, I get output from both pins 2 and 3 (RX/TX) on the DB/E9 (regardless of which pin on the board is powered). The voltage between pins 2 and 3 on the connector differs by ~0.1V. Is this normal or is my circuit faulty? How do I test the continuity of the board/connector and diagnose and fix the fault?
In case it's of any relevance, I'm using an Uno with an SMD chip.

Do you have an oscilloscope, or logic analyzer, or more than one Arduino?  If you only have a DVM, with jumpers off run a sketch that toggles different digital pins at about .5 Hz, and verify that that shows up ok on pins of J2 on the shield.

I don't have an oscilloscope or logic analyser (or know how to use one). I do have a DT830B multimeter and multiple boards (Uno R3, Leonardo R3, Mega 2560 R3).

It turns out that the ATMega328P-PU chip on the Uno I was using is damaged. I will try again with a different board and see if the problem persists.

@JamesWaldby-jwpat7 Thank you for the suggestion. I managed to get access to an oscilloscope and test the shield with a different board. It helped me diagnose that the RS232 shield is non-functional.


text:
Arduino UNO R3 as flight control plus brushless motor driver
I am trying to build an RC plane using an arduino UNO as the flight control board.
I found a code on the arduino forum for driving a 3 phase AC motor with an arduino.
http://forum.arduino.cc/index.php?topic=8642.0
I believe it will also work for brushless motors commonly used in RC airplanes.This will eliminate the need for an ESC (Electronic Speed Controller) which are pretty expensive.
Now I plan to use a single arduino board to communicate with the nrf2l01 rf receiver , control the servos as well as drive the brushless motor(mentioned above).
In each cycle of the code the arduino will be fetching data from the receiver,sending a pwm signal to the servos and setting which two phases of the brushless motor will be high and which one will be low.
Since so many things are being done in each cycle the phase change of the brushless motor might not be fast enough and this might hamper the motor speed? Or is the arduino  fast enough to handle all this and it won't affect the speed noticeably.

Since so many things are being done in each cycle the phase change of the brushless motor might not be fast enough and this might hamper the motor speed? Or is the arduino fast enough to handle all this and it won't affect the speed noticeably.

This is very much an engineering question. How would one go about answering this?
One method is do a worst-case execution time measurement. Another method is to use control theory and estimate the minimum control frequency for the system (or sub-systems).
Let us assume (for this argument) that the required update frequency is 50 Hz (20 ms cycle time). That gives approx. 320.000 instructions (AVR @ 16 Hz) per control cycle.
The algorithm sketch above in your question is basically dominated by the time to receive the message. This depends on a number of factors; PLL start up, write message from AVR to NRF, transmission frequency, coding, etc, but also message loss and retransmission/acknowledgement. With 2Mbps and 5 byte address, 32 byte payload, and 2 byte checksum the transmission time is at least 300-400 us plus approx 100-200 us for the AVR/SPI to NRF communication. A total of 400-600 us which is well under the 20 ms.
What other design considerations are there? Motor interference on the communication, antenna design, range, protocol design, etc.
Cheers!

Awesome, your answer gave me the insight I was missing. So i  did some calculations to find the maximum time available for each phase change ( If i run a 1000kv motor at 11v, worst case ) which turns out to be ~1818 uS. Thank You.


text:
Adding Library to my sketchbook
Hey so basically I have my Arduino uno r3 setup with my RFID-RC522. I am looking to add this library to so I can use the examples alongside the ones I already have.
https://github.com/BoolLi/RC522_RFID_NFC_Utilities
I haven't been able to add them correctly and hope someone can help me out doing this. I currently have these ones already added and working correctly:
https://github.com/miguelbalboa/rfid

https://www.arduino.cc/en/Guide/Libraries

@Majenko I am not able to do these. I have been fiddling around with them through various ones of these methods. For example the add library from zip throws this error:Arduino: 1.8.0 (Linux), Board: "Arduino/Genuino Uno"
Specified folder/zip file does not contain a valid library

Well, it doesn't help that the author of that library doesn't know the first thing about formatting a library...

Have a look at a good library and see what is wrong with this one.  Usually its the structure or the textfile, or the name.

Download https://github.com/BoolLi/RC522_RFID_NFC_Utilities/archive/master.zip
Copy the folder RC522_RFID_Utilities from the downloaded file to {sketchbook folder}/libraries. You can find the location of your sketchbook folder in the Arduino IDE at File > Preferences > Sketchbook location.
If you're using Arduino IDE 1.6.5-r5 or older restart the Arduino IDE. If using a newer version no restart is necessary.

The other three folders in the downloaded file are example sketches, not libraries. After installing the RC522_RFID_NFC_Utilities library following the instructions above you will be able to use them. You can store those folders anywhere you like but you should not put them directly under the libraries folder as this will cause warning messages about invalid libraries on every compilation. If you do want to bundle them with the RC522_RFID_NFC_Utilities library, as is customary, you can do this:

Create a folder named examples in {sketchbook folder}/libraries/RC522_RFID_NFC_Utilities
Copy the example sketch folders (NDEFFormattingExample, etc) from the downloaded file to the examples folder you created.
Restart the Arduino IDE if it's running.

The example sketches will now be accessible via File > Examples > RC522_RFID_NFC_Utilities.

Thanks this was helpful. My issue was I never knew to take the Utilities folder and put it into the library and then have the examples within it. They are showing up fine for me now. Now just to try and sort the compiling error :)


text:
What kind of control method in my code will allow me to control multiple servos with phase shifts
I am building a quadruped robot, and I need to keep all four legs moving continuously and out of phase with respect to each other to produce a smooth gait and to prevent falling over. I wish to achieve this with 4 sets of 2 motors. Each set will move in the same way but not in sync. I have an Adafruit 16-Channel 12-bit PWM/Servo Driver - I2C interface - PCA9685 for this application. I have considered several implementations; delay () would be a poor choice because of the obvious delay between the current and next step in the gait cycle. I am also considering using ISR that will trigger when a certain time period passes, an estimated time to reach the desired position for example, but the interrupt method would not be much better than delay (). Another idea I have is to create a class that will receive the next position to move to for each leg and will continuously send the signal to the PWM driver. However, timing this would require some trial and error. Is there a conmon well-known method to send control signals with phase shifts?

One way could be to use PID controllers and a state machine.


text:
SPI or A0/A1: what is the best solution for pin allocation on an Arduino shield?
When you design an Arduino shield you want to make it compatible with a maximum number of shields that may be stacked with it on an Arduino (UNO). Considering the following two possible tradeoffs, which one would you consider the best:

Option A: A shield that uses pins A0 and A1, where no other stacked shield can use those pins.
Option B: A shield that uses SPI, where other stacked shields can only use pins 11, 12 and 13 in SPI mode.

Note: I'm asking this question for a project I'm designing called Omzlo one. It's an Arduino compatible board with builtin CAN bus networking. I'm hesitating between two prototype designs.

Why not support both options with a set of switches (or jumpers) on the shield? The your Arduino library would have an input argument to indicate which option to use.

I would guess that a shield wanting to use SPI is more likely to do so as a slave...

@Edgar Bonet - I incorrectly said "SPI master mode"in the question. Corrected that.

it probably depends on the shield, and what other shields you expect it to combine with.


text:
Execute function until called again?
I am building a simple security system with my Arduino Uno. I have an alarm() function:
void alarm() {
  tone(8, 3300, 200);
  delay(200);
  tone(8, 3000, 200);
  delay(200);
}

When I call it in the loop() function like so:
void loop() {
  alarm();
}

the alarm sounds fine. I just want to be able to stop it. What I mean is, I want it to start the alarm (if it is off) when I call the alarm() function, then stop it when I call the alarm() function again. How can I do this?
P.S. Can someone with over 150 reputation please make the tone tag? I can't believe it's not here!
Edit: I tried the following code, but the alarm just kept going:
bool alarmOn;
void setup() {
  pinMode(8, OUTPUT);
  alarm(true);
  delay(5000);
  alarm(false);
}

void loop() {
}

void alarm(boolean call) {
  if (call) {
    alarmOn = true;
  } else {
    alarmOn = false;
  }
  while (alarmOn) {
    tone(8, 3300, 200);
    delay(200);
    tone(8, 3000, 200);
    delay(200);
  }
}

There is nothing in the while (alarmOn) loop that can unset alarmOn: if alarmOn is initially true you have an infinite loop.

You can just have a variable that remembers whether the alarm is
supposed to be on or off. Let's call it alarm_on. Then:
bool alarm_on;
static void start_alarm() { alarm_on = true; }
static void  stop_alarm() { noTone(); alarm_on = false; }

void loop()
{
    if (alarm_on) alarm();
    if (some_condition()) start_alarm();
    if (some_other_condition()) stop_alarm();
}

For a better approach that allows you to sound the alarm without
blocking the whole program, see the Blink Without Delay Arduino
tutorial.
Edit: I just wrote (but did not test) a non-blocking version of this
alarm, based on a state machine and the timing technique from the Blink
Without Delay tutorial. Here it is, as a class:
class TwoToneAlarm {
public:
    static const uint16_t HIGH_FREQ = 3300;
    static const uint16_t LOW_FREQ  = 3000;
    static const uint16_t TONE_DURATION = 200;

    TwoToneAlarm(uint8_t output_pin)
    : state(OFF), pin(output_pin) {}

    // Start the alarm.
    void start()
    {
        tone(pin, HIGH_FREQ);
        state = HIGH_TONE;
        last_tone_change = millis();
    }

    // Stop the alarm.
    void stop()
    {
        noTone(pin);
        state = OFF;
    }

    // Call this periodically to handle the tone changes.
    void update()
    {
        if (state == OFF) return;
        if (millis() - last_tone_change >= TONE_DURATION) {
            switch (state) {
                case HIGH_TONE:
                    tone(pin, LOW_FREQ);
                    state = LOW_TONE;
                    break;
                case LOW_TONE:
                    tone(pin, HIGH_FREQ);
                    state = HIGH_TONE;
                    break;
                default:
                    break;
            }
            last_tone_change += TONE_DURATION;
        }
    }

private:
    enum { OFF, HIGH_TONE, LOW_TONE } state;
    uint16_t last_tone_change;
    uint8_t pin;
};

It could be used like this:
TwoToneAlarm alarm(8);

void loop()
{
    if (some_scary_condition()) alarm.start();
    if (some_other_condition()) alarm.stop();
    alarm.update();
}

Note that the whole program must be non-blocking (delay()-free),
otherwise the tone changes will not be done on time.
Edit: more about being non-blocking.
There is normally no reason for you to use delay() at all in your
program. The only reason for this function to exist is to help complete
beginners write their first blink-the-LED program. As soon as you start
writing anything non trivial, you should ban it from your vocabulary.
The Blink Without Delay tutorial is here precisely to teach you how to
get rid of delay() by using millis().
In this particular case, however, the drawback of delay() may not be
too severe: if the alarm is sounding and you delay a tone change, you
may hear it as a glitch that breaks the rhythm of the sound. If the
delay is short enough, maybe up to 10 ms or so, you are unlikely to
notice it. Longer delays will be noticeable, and it's up to you to
decide whether you find them annoying or not.
It is possible to ensure a very steady rhythm despite the delays by
using interrupts, but this will cost you your 16-bit timer. Or you could
write your own implementation of tone() that does both the pin
toggling and the tone changes using a single timer. Any such option will
require you to learn about low-level timer
programming, which is significantly
more demanding than learning to use millis().

Your code inspired me to do something different. See my edited answer above. About making the tone tag...

That's perfect! Still, is there any way I can use delay() in the body? It is a security system and it needs to be user-friendly.

How can I use this as an Arduino library?

@CelloGuy: 1) There is no incompatibility between being delay()-free and being user friendly, but see the amended answer. 2) Making a piece of code into a library is a different question, unrelated to this one.