text:
Millis...alternate flash
I thought I had the Millis() command sorted but i'm stumped on the one. Aim is to get 2 led's alternately dimming, they work great with delay(); of course....but i can't figure where i'm going wrong with Millis().
Please have a look and point out what i've got wrong.
Thanks
Doug
int LED3 = 5;
int LED4 = 6;

// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED3=0;
unsigned long previousMillisLED4=0;

int intervalLED3 = 500;
int intervalLED4 = 500;

void setup() {
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);

      digitalWrite(LED3,LOW);
      digitalWrite(LED4,LOW);

}

void loop() {
  //unsigned long currentMillis = millis();
      for(int P=0;P<6;P++){
        //if ((unsigned long)(currentMillis - previousMillisLED3) >= intervalLED3) {
            analogWrite(LED3, 127);
            analogWrite(LED4, 254);
        delay(500);
              //previousMillisLED3 = currentMillis;

      //if ((unsigned long)(currentMillis - previousMillisLED4) >= intervalLED4) {
            analogWrite(LED3, 254);
            analogWrite(LED4, 127);
       delay(500);
             //previousMillisLED4 = currentMillis;
      }
}

Sorry, problems inputting code, but its all there.
I realize that there are some closing brackets missing in the LOOP() section for millis but it is set for delay() to show that it works.

Well, the for loop is useless. Then you need to plan your time cycle. For instance what you want is
time(ms)  LED3  LED4
   0       127   254
 500       254   127
1000 -> back to 0

So implement this. One way can be the one suggested by st2000:
int LED3 = 5;
int LED4 = 6;

// just one tracking, since there is only one sequence
unsigned long previousMillis=0;

int endOfPhase1 = 500;
int endOfPhase2 = 1000;

void setup() {
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    digitalWrite(LED3,LOW);
    digitalWrite(LED4,LOW);
}

void loop() {
    unsigned long currentMillis = millis();

    if ((currentMillis - previousMillis) < endOfPhase1) {
        analogWrite(LED3, 127);
        analogWrite(LED4, 254);
    }
    else if ((currentMillis - previousMillis) < endOfPhase2) {
        analogWrite(LED3, 254);
        analogWrite(LED4, 127);
    }
    else
        previousMillis += endOfPhase2;
}

Just a small note about this: I tend to prefer summing the period instead of setting previousMillis to millis because this way small errors do not accumulate.
This way is the simplest, but the state machine oriented is the one I suggest you, since it is more powerful and you will reuse this a lot of times. Moreover it will detect the "change" of state, thus avoiding the continuous analogWrite (in the previous code the analogWrite instructions are executed a lot of times).
Just define a state machine as two states (state 1, where LED3 is 127 and LED4 is 254, and state 2, where LED3 is 254 and LED5 is 127). The transitions will be after 500ms in each state, but I'll make two separate constants so you can trim them later. Usually each state has a function to be performed when you enter the state, a function to run continuously, a function when you exit and one or more transitions. The way to perform this is

calculate if there is a state change
if there is, perform the exit functions of the previous state and the enter functions of the next state
advance to the new state
perform the actions to be done continuously in the new state

In our case just state transition, enter and advance should be implemented. Usually you use a switch case on a variable holding an index for the state. In this case, for instance,
int LED3 = 5;
int LED4 = 6;

// just one tracking, since there is only one sequence
unsigned long previousMillis=0;

int state1duration = 500;
int state2duration = 500;

uint8_t state;

void setup() {
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    digitalWrite(LED3,LOW);
    digitalWrite(LED4,LOW);

    state = -1; // Invalid state, used to force a transition at startup
}

void loop() {
    unsigned long currentMillis = millis();

    // Check the transition
    uint8_t nextState = state;
    switch (state)
    {
    case 1: // Transition for state 1
        if ((currentMillis - previousMillis) >= state1duration)
        {
            nextState = 2;
            previousMillis += state1duration;
        }
        break;
    case 1: // Transition for state 2
        if ((currentMillis - previousMillis) >= state2duration)
        {
            nextState = 1;
            previousMillis += state2duration;
        }
        break;
    default: // When unknown state, go to state 1
        nextState = 1;
        break;
    }

    // If there is a change, perform the enter functions
    if (nextState != state)
    {
        switch (nextState) // enter functions of the next state
        {
        case 1: // Entering state 1
            analogWrite(LED3, 127);
            analogWrite(LED4, 254);
            break;
        case 2: // Entering state 2
            analogWrite(LED3, 254);
            analogWrite(LED4, 127);
            break;
        }
    }

    // Advance to the new state
    state = nextState;
}

This can be more complicated, but believe me, it is not. Once you get what this means you will be able to solve a lot of problems this way.
According to my experience, never try to simplify this to your particular problem, since it will make things more complicated. Just add, when needed, the exit functions (before switch(nextState) put another switch on state) and the execution (after the advancing, put another switch on state) if needed.

Thanks Guys.
Firstly, the FOR loop was an attempt to execute the cycle a number of times, but even if that worked I had the wrong approach with millis(). I will use the simpler example at this stage but will study the longer version to see if i can get a better grip on it. I have inserted an increment [count = (count+1);]into the phase2 IF statement and added a counter [if (count == 1000) //return to main program] at the end to exit.
This now satisfies my coding question.
Thank you for you input.
Doug

You are trying to use millis() exactly like delay().  The method delay() stops the program from progressing forward.  It blocks the program.  This is frowned upon as the processor could be doing something useful during this time.
The method millis() does not stop the program.  Instead it is like telling you what time it is.  It is your code that then need to know at what time you want to do something.
But in your code, you are doing something odd.  You are switching the brightness of the LEDs then IMMEDIATELY switching them back.  You are using the same time for the two things you want to do.  Instead try to initialize previousMillisLED4 to 500, intervalLED3 to 1000 & intervalLED4 to 1000.

The final sub routine...I did move the counter to get a better result. The variable "ditchFlag" is set in an IF statement further up in the sketch.
The duration of the subroutine is a combination of the timers and the number in "count".
void ditchDim() {
while (ditchFlag == 1) {            //set to 1 when conditions are met

unsigned long currentMillis = millis();

if ((currentMillis - previousMillis) < endOfPhase1) {
    analogWrite(LED3, 127);
    analogWrite(LED4, 254);
}
else if ((currentMillis - previousMillis) < endOfPhase2) {
    analogWrite(LED3, 254);
    analogWrite(LED4, 127);
}else{
  count = (count+1);
    previousMillis += endOfPhase2;
    }
      if (count == 5) {
        count = 0;
        ditchFlag = 0;
        return;
    }
  }
}

thanks
Doug

authors: امیرحسین کریمی


text:
I am making an easy game but something in my code is wrong
I am making a game where you need to push the button when the LED lights up but it is not registering the push at the right time. I need to push the button when LED is about to go off.
My code:
randNumber = random(2);

if(randNumber == 0){
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
}

if (btnAddFirst.pressed() && randNumber == 0){
  Serial.println("You did it");
}
else {
  Serial.println("u failed");
}

Don't use delay(), since nothing can happen (not even reading a button) while that delay is running.
Instead use millis() as in the BlinkWithoutDelay example sketch.

source: Stack Exchange

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

sort: votes


text:
Multichannel communication with Arduino and HC-12 transmitter
The HC-12 module has 100 possible channels starting at 433 MHz. Can someone tell me how to program the Arduino to use multiple channels at the same time? My goal is to build an RC transmitter with Arduino and an HC-12 module for a quadcopter. Therefore I need 6 channels, like a normal transmitter does. Thanks in advance!

I believe you are misunderstanding what it means by channels. The HC-12 can transmit on up to 100 channels, which means different frequencies under the 433 MHz band. For example 433.05 MHz or 433.15 MHz. This is so multiple HC-12 modules can be used next to each other and only the module receiving on the channel of the transmitter will receive the data broadcast.
What you need to do for your quadcopter is send an array of bytes that begins with a constant, followed by the data you need (a packet). Example:
byte packet[] = {0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}

// in your loop
packet[1] = ; HOW MUCH THE ENGINE IS THROTTLED
packet[2] = ; HOW FAR THE CONTROL TO GO FORWARD IS DEPRESSED
// etc

Iterate through this array writing the data through the serial port to the HC-12. Whenever your receiver detects the constant (in this case 0x00) read the values that follow as the controls for the quadcopter.

I'm starting on HC-12 myself and as I understand, you can only access 1 module at a time by selecting each modules individual channel, assuming you have set the modules to separate channels, you cannot receive data from multiple modules even if set to the same channel at the same time, it would just be a jumble of unsortable data. But you may be able to select one channel after another and collect each set of data separately 1 thru 6 and then extract the information you need by using AT+C001,002,etc. Or you could use 1 RX and program the on board arduino to cycle thru the 6 motors sequentially and collect the 6 sets of data that way. this question would be easier to answer with a diagram of you proposed circuit.

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

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


text:
How to convert Arduino example sketch to a complete c++ project?
I'm experimenting something new with my Arduino Leonardo. I removed its original bootloader and flashed it with LUFA mass storage example with added functionalities(now its a firmware). I'm trying to now add RFID reader(read/write) example to my firmware. For that I have to convert the sketch to a c++ code. So I copied relevant header file and cpp file from the library folder(libraries->rfid-master->bla.h,bla.cpp). But I'm confused what to do with the .ino file under examples(libraries->rfid-master->examples->ReadAndWrite->blabla.ino). I guess this code should be copied to the main class of my firmware. Any ideas?

Basically *.ino is *.cpp without headers. So you can

rename it to *.cpp,
If you have any functions which are used before they have been defined, provide declarations for each function before its first use
#include <Arduino.h> on the top
#include <Wire.h> if you are using Wire and so on

and you have "normal" CPP file.
If you are making library this way, than you create also *.h file, where you declare all exported functions and objects and #include that file in your *.cpp as first line (than you do not need/have to forward declare any of that exported functions)
You may like to take a look at https://github.com/arduino/Arduino.git https://github.com/sudar/Arduino-Makefile and https://github.com/ladislas/bare-arduino-project
the Bare Arduino have 2 projects each using 2 libraries, so you can get inspiration there

The Makefile you are linking to seems like a slightly outdated fork of Sudar Muthu's Arduino-Makefile. Why not link to the original instead?

Just because I first found the Bare-Arduino, which used this version (and then patched it with the sudar version as I now see). Anyway it is able to compile my files against Arduino 1.8.0, so it could work as starting point. Or the original Sudars makefile, but the Bare project have nice examples, how to organise your project, which I think would help @Isuru with the start. And later he can migrate to other version/system. (I build simple one over that too, to help my projects, nothing much but helped me to sort my mind faster)

Whereas it makes sense to pull WeAreLeka/Arduino-Makefile as a submodule of ladislas/Bare-Arduino-Project, it doesn't make sense to provide a direct link to that fork, as it has no added value over the original. If you do want to give a direct link to Arduino-Makefile, you should edit your answer in order to link to the real project.

You forgot about having to predeclare functions.

@Pharap "for each function, which is used before declaration write its header before first use" is (IMHO) exactly that... and functions used after declaration are already declared. Or are there some other cases, where usual ino -> cpp needs it?

@gilhad .ino files allow you to use your own functions without declaring them first, .cpp files do not, they require you to declare a function before it's used or the compiler won't know it exists. Here is an example. I wouldn't take "write its header before first use" to mean "you must forward-declare your functions before using them", because a header is a specific kind of file and it doesn't require a header file, it just requires a function declaration.

header file is something different from header of funfction. In your example is writen void sendMessage(void); before sendMessage is used. (and #includes as I mentioned too). No other difference.


text:
Win10 64bit, IDE 1.8.0 back to IDE 1.6.13 won't compile anything including Blink. 1.6.12 does compile
Arduino: 1.8.0 (Windows 10), Board: "Arduino/Genuino Uno"
c:\program files (x86)\arduino\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied
exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences.

http://forum.arduino.cc/index.php?topic=134161.0 seems to contain multiple possible solutions. Run Arduino as Administrator. Create a new sketch, and copy all code to this new sketch. Something with the %tmp% directory.

Code file has full permissions and access. Running the IDE as administrator makes no difference. Same error message for everything (blink ++++) as above. re-install of IDE made no difference.

It looks like @grtblu and ArduinoAngryAtMe are the same person. It is confusing when someone else replies to a comment. It would help if you remembered your login credentials and replied as the OP.

I suggest downloading the IDE into a folder which is not in Program Files. Put it in Documents or some such place.

There are some reports of this error in the Arduino IDE issue tracker: https://github.com/arduino/Arduino/issues/5616 and https://github.com/arduino/Arduino/issues/4683 where it was found to be caused by antivirus software.

Try locating the code file in explorer.exe, go to its properties and check if the system has full access to the file. Just to be sure, run the Arduino IDe as an administrator.

I understand the logic in running as the administrator and its usually a good solution, but it may cause problems because the IDE reads and writes to folders within the user's profile and the Administrator MAY not have permissions to these files, so you need to check that as well.  It would be better to give users the permissions they need on the Arduino IDE folders and registry hives.


text:
Multiple I2C sensors with the same address
I am trying to find the simplest way to connect multiple (preferably around 10-20) IMU sensors to one controller. There are two constraints: sampling at 60Hz and reasonably simple wiring as I want to put it on clothes.
I am totally new to the Arduino world, please let me know what other details I should provide.
It seems that just having multiple IMUs on the I2C bus would work great, but they usually all come with the same address.
So, the solutions I found so far:

Using several different IMUs from different companies - hard to find 20 of them
Using a multiplexer - requires star-like wiring topology.
Using multiple controllers - inefficient and doesn't seem right.

For now, the solution with a multiplexer seems to me the most reasonable, but is there any other way I am missing? Can I somehow produce IMUs with, say, 16 different addresses and wire them all together to one I2C?
Thanks for your help!

See also http://arduino.stackexchange.com/questions/18790/how-to-set-address-for-using-more-than-mpu9250/18793#18793

If you're using MPU6050 IMUs, there's an easy trick: put them all on the I2C bus, and connect each IMU's AD0 pin to a separate digital pin on the Arduino[*]. When you want to read from a specific IMU, set all AD0s to HIGH, except the one you want to read to LOW. All the IMUs with AD0 set to HIGH with have an I2C address of 0x69, whereas the only one on LOW will have an address of 0x68.
If you want to read them all, you just go through a loop and set the one you want to LOW, the others to HIGH, and you're set.
[*] If you want 20 IMUs, you'd better get a Mega, or, even better, a Maple. Small form factor, quite a bit of oomph, lots of pins and flash, and some clones cost next to nothing; eg Itead sells Maple clones for 6 bucks. ElecFreaks sells them for 9 bucks. You could use the 16 pins at the bottom for the AD0s.
This trick works with any kind of I2C device that has a customizable address scheme through one or more pins. I do that with AT24Cxx EEPROMS, which have a 0x50-57 address range. When you want to have more than eight chips, setting all but one to 0x50 and one to 0x51 solves the problem pronto.
Reference: https://github.com/PaulStoffregen/FreeIMU_original/blob/master/documents/PS-MPU-6000A-00v3.4.pdf

That's a pretty clever idea!

And coming from you, that's a nice compliment, Nick!

A minor extension -- for adding more devices, using a shift register like the 74HC595 to 'drive' those A0 pins. Daisychained, you could get 32 (and maybe more) for the cost of just 3 pins on the microcontroller -- with SDA and SCL, a total of 5 uC pins to manage 32 MPUs.

You can also get I2C Multiplexers such as the TCA9545A that can split one I2C line into 4 buses. I have connected up to 9 MPU9150 on one line with that.

Another way is to use a software emulation of the I2C interface so that any of the digital I/O pins may act as an I2C pin. One well-written library you can use for this is SoftWire by Steven Marple. It can be installed via the Arduino Library Manager or directly from its GitHub repository here.
With this, you can select arbitrary pairs of pins to act as SDA and SCL for each I2C device and then you can communicate with each device individually.
Note that with this method, you need two digital pins for each I2C device. In that sense, I believe @dda's answer is the best in regard to these IMUs in question.


text:
Arduino uno shift register
I have shift register 74HC595. I added 7 push buttons from Q1-7 and the 8th to ground. On the other side which pin of the register will go to Arduino pin 2? And wich one to the 5v pin?
How can I read one button at a time in the code because on the Arduino it is just 1 pin?

my problem is that i have a lot off buttons 16 how can i do it a 4x4 buttons - do you have 7 buttons or 16 buttons?

You cannot.  The 74HC595 does not have parallel inputs, such as you would need to read from 7 switches.
You need a parallel-in, serial-out shift register, such as a CD4021B.  You can find details on how to use it with an Arduino here

How can I read one button at a time in the code because on the Arduino it is just 1 pin?

Basically you "clock in" the data by toggling a clock line - each toggle presents the next bit, which you read in using your one digital input.

Okay , my problem is that i have a lot off buttons 16 how can i do it a 4x4 buttons with there values to send them to windows form

And does it work with just the arduino pins?

How many unused digital pins do you have on your Arduino?

I think i just need the grnd and the 5v , i dont have anything attached to the arduino just the buttons , my goal is to play a game i created with those buttons

If you post another question, asking how to connect 8 switches to an Arduino, I'll answer it - since it's a different question and this one has already been answered.

Just one. I have a 4x4 labels in C# on each button press i want to change its color

Okay I'll post a new question

OK. If you want to encourage people to help you further, then if your question has been answered (never mind that it wasn't the question that you should have asked) you should accept one of the correct answers and optionally up-vote any which have been helpful.

I can 't post the question always the red box pop out

I don't know what that means. You could almost certainly Google for how to connect many switches to an Arduino, though - and you should do research before posting the question!

Thanks for the help man , i'm really paniking now tomorrow i have ti present my project

So i need to put multiple switches with just the arduino i can get a multiplexer now

You don't need a multiplexexer. Ask another question about how to connect 8 switches to an Arduino. Maybe you'll get lucky and someone will answer - I'm going to bed. If not, think how much you'll learn about planning :-)

A shift register is an output device. You won't be able to "Read" 7 push buttons in this way.
A shift register like that is for taking a "series" of bits on one wire and parallelizing them onto 8 wires.
It does not work in reverse. The reverse is called a multiplexer.

so using this shift register can i send data from C# to arduino code as bytes  ? I just want to compare values on my C# with values given when i press a button .

That's nonsense, jose.  See my answer re types of shift registers.

Shift registers are available in several flavors:
• Serial-in, Serial-out (SISO) units like 7491 have serial input and output.
• Serial-in, parallel-out (SIPO) units like 74164 have serial input, parallel output.
• Parallel-in, Serial-out (PISO) units like 74165 or 74166 (etc. – just search for shift register in a list of 7400 series integrated circuits or other series) have parallel input, serial output.
Other variations: The 7494, 7495, and 7499 have serial and parallel input, parallel output.  The 7499 also has serial output.  The 7494 and 7499 can shift right or left.  (Most of the models listed earlier only shift one direction.)
Anyhow, by using an appropriate shift register, along with a bunch of resistors and diodes, it is possible to read lots of switches.  As suggested in another answer, you might want to ask about how to do that.


text:
System voltages: Can I use a 5V touchscreen shield on a 3.3V arduino?
The system voltage on my arduino 101 is published at 3.3V, even though it also has a 5V output pin.
My Seeedstudio touchscreen is supposedly a 5V device. http://wiki.seeed.cc/2.8inch_TFT_Touch_Shield_v2.0/
I believe I've successfully ported the library for this touchscreen to the 101 because it now runs and compiles on both the 101 and the Mega, although it gives erroneous values on the 101. Could it be because of this voltage difference? is there any way to fix it?
Edit- I should add that the 101 is labeled as "5V tolerant".
Edit II: I've found a pretty informative review that explains a little bit about how the 101 is supposed to work with 5V peripherals. I'm not sure though how it could work in cases where a shield does not recognize 3.3V as logic high. Usually 3.3V is right around the cutoff voltage for many circuits. http://www.tweaktown.com/reviews/7706/intel-curie-based-arduino-101-programmable-microcontroller-review/index2.html

You'll probably need a fairly common device known as a logic level converter.  One such example, in breakout board form, can be found here: https://www.sparkfun.com/products/12009
There are tons of other options depending on what exactly you need.

For what it's worth, I connect the transmitter output of a 3.3v WiFi radio (ESP8266) directly to an input pin on a 5v Arduino. with reliable results. 3.3V is high enough to be recognized as a (5v) logic HIGH. You will need a level conversion going the other way, 5v -> 3.3v, however.

That's not necessarily true.  Logic HIGH typically has a range of values that are acceptable, and many chips are designed to be 3.3V or 5V tolerant.  However, only the datasheet will tell you if a 3.3V logic level will be interpreted as HIGH.

Thanks Michael. Part of my question is whether the touchscreen chip recognized 3.3V as High. According to the datasheet, that would seem to be the case. But my results suggest otherwise. I've got the same code running on the 101 and the Mega, but the screen only shows white backlight on the 101, and the touchscreen output numbers are all out of whack. And unfortunately, I'm not sure I can implement a logic level converter because I don't have room to do anything between my SPI headers. The touchscreen shield fits right on top of the 101 board.

For a 5V CMOS device a logic high is typically 3.5V (about 0.7xVcc). For a TTL device it's about 2V.

What about power? A tipical 5v 16x2 LCD "works" with 3.3v, but flickers a lot and is unreadable.


text:
Show images on a monitor using Arduino via Wifi
Consider a computer monitor hanging on a wall. Next to it is an Arduino Uno with a wifi. Is it possible to create something like this? Using wifi it should be possible to send data (images) to Arduino. This will be output to a monitor, like an image gallery. Images can be any type (videos included).
Is it possible? Where does one start?
Thank you.

This should be a fun challenge, if you're looking for a learning experience. As others have pointed out, you'll be working at the limits of the Arduino to get much of anything to work. If your goal is results, on the other hand, you'd be best off rethinking your design.

I have somewhere in my stash a shield that enables an Arduino to overlay graphics on the screen. But it is kinda crude and low-res. What you're trying to achieve is definitely not for Arduino, it is way underpowered.
You'd better look into doing this with something like a Raspberry Pi.

What you want is the GameDuino shield which gives you a full VGA experience on your Arduino. Also good for making games with.

For the novice/intermediate, this is going to take way too much time and effort to meet the requirements you have asked with an Arduino Uno (if it is even possible).
May I suggest a Raspberry Pi instead.
The Raspberry Pi (depending on the model) has multiple video outputs:

HDMI
Composite video
LCD display

Each of these video outputs require very little effort to get going.
Adding WiFi capability requires just a USB WiFi dongle (and possibly downloading a driver) a bit of set-up and that about it. The RPi 3 (Model B) has on-board WiFi so you won't need the dongle.
What you want is very similar to a digital photo frame, so I would search for people who have already done that using google. I imagine that there would be plenty of free code/software out there on the internet.
All of this is a lot easier on the Raspberry Pi compared to using the Arduino.

pcDuino is another hardware platform much like the Raspberry Pi that would meet your requirements. The pcDuino is less popular than the Raspberry Pi and so there may be less open source code out there in cyberspace - but it would still be worth a try.


text:
Arduino Ethernet Shield on Arduino Mega Pin Usage!
I currently have an Arduino Ethernet Shield which is Mega Compatible. I've found on the Arduino Ethernet Library https://www.arduino.cc/en/Reference/Ethernet that the Shield uses different Pins on the Arduino Uno and Arduino Mega. How is this possible? The Ethernet shield isn't connected to those pins mentioned.
Arduino Uno:
Pin: 13 - SCK
Pin: 12 - MISO
Pin: 11 - MOSI
Pin: 10 - SS for Ethernet Controller
Pin: 4 - SS for SD Card
Arduino Mega:
Pin: 52 - SCK
Pin: 50 - MISO
Pin: 51 - MOSI
Pin: 53 - SS for Ethernet Controller
Pin: 4 - SS for SD Card

Those 4 pins D50 to D53 are the ICSP pins which appear twice on the MEGA; the Ethernet Shield uses the second set of connections located in the middle of the Mega board.
The header files gets told (by the Arduino IDE) that the board is a MEGA so the compiler uses those pin numbers to connect.

The SS pin is not on the ICSP header. It needs to come from one of the headers on the side still.

Firstly, I am assuming you are using an Ethernet Shield similar to the Arduino Ethernet Shield.
Secondly, I assume that you are referring to the following quote on the Ethernet Library page:

The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.

This communication interface is called SPI.
The Ethernet Shield connects to the SPI interface (ie MISO, MOSI, SCK) using the in-circuit Serial Programming (ICSP) pins which are also connected to the SPI interface pins (ie. pins 50, 51, and 52)

As noted in the above quote, pin 53 is not used as the SS pin (but needs to be kept as an output pin and not used). Pin 10 is used instead for the ethernet SS pin on both the Uno and Mega.


text:
Arduino pro mini (clone) @1Mhz target does not answer
Recently I have been experimenting with battery powered sensor (mySensors).
I created node with 3.3V Arduino Pro Mini (ATMega328P @ 8Mhz with nordic radio chip and BME280 sensor) and successfully programed it many times using either USBAsp programmer or serial (to USB) programmer.
I wanted to lower power consumption and so I disconnected power led and burned fuses as follows:
lfuse 62
hfuse DA
efuse 7
It worked successfully and I recompiled the sketch and upload it with USBasp.
I got an error that data cant be verified. It was late in the night so I jumped to Internet and googled it. In one forum I found, post (which I am unable to find again) that stated the he was able to upload sketch when he switched programmer to 5V. (Power was connected to Vcc)
I did that and it worked fine.
Than I tried to make change to sketch and upload it again (on 3,3V) and again got verification error so I unplugged programmer and switched back to 5V.
When I did that, the device stopped answering.
I regularly used this command to check that device responds and see fuses
avrdude.exe -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -cusbasp -Pusb

What i did

Checked wiring.
Tried program fuses on blank new arduino - worked (programmer is
fine)
Measured voltage ok
Measured current (its around 4mA, I see it as the board is not
sleeping and is actively doing something)
I noticed that when I issue command mentioned above the on board led
quickly lights up and then goes off again.
I tried to power it from raw, from Vcc and from Vcc on serial hader (picture).
I measured power on Vcc when connected to Raw pin and it reads 3.3V
so power regulator should be ok.
I used -B10 switch to averdude with no luck

My question is

Is it possible that I burned the ATMega chip?
Is it possible that I see target not answering because of USBAsp is unable to lower programming frequency? (warning: cannot set sck period. please check for usbasp firmware update.)

Please suggest if there is anything I can try before throwing it out.
Thank you.

EDIT 2017-01-07
I was able to brick another board.
I think that the programmer is the cause.
I tried to upload bootloader with fuses from arduino and it failed with verification error.
I was able to burn bootloader from command line after seting fuses and restarting the board.
When I tried to upload the program it I got
avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x00 != 0x0c
avrdude: verification error; content mismatch

avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: safemode: lfuse changed! Was 62, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: hfuse changed! Was da, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: efuse changed! Was 7, and is now 0
Would you like this fuse to be changed back? [y/n] n
avrdude: safemode: Fuses OK (H:07, E:DA, L:62)

I answered yes because in in earlier attempts it just froze.
Now the board is in same condition as the first one.
Is it possible to revive it?
Thanks.

Here is link to post that suggests that I may burned the arduino.Method #6: Apply >3.3V to the 3.3V Connector Pin rugged-circuits.com/10-ways-to-destroy-an-arduino. Strange thing is that it worked two maybe three times ok :-)

TL;DR if the AVR is running at 1Mhz you have to slow down the sleep of the USBasp. Use avrdude  -B10 .... to slow it down.

Ok, I need to solder jumper on USBAsp programmer. I will try in the evening and let you know.

That is another option. My solution is to just add -B10. Which seems easier than soldering to me.

I thought that USBAsp software must be upgraded to support this options, but it accepted -B10 and used 93750 Hz but result was still target doesn't answer.

You could try the jumper on the USBASP.

Ok I was able to brick another board using USBAsp programmer. I also solder the jumper with no effect. I updated the post, but dont know what to do. I dont want to brick any more boards :-). Should I look for another programmer?

What was the command you used to set the fuses? You can also lower the speed in software. I've had similar problems every now and then. Sometimes the -B10 didn't work. Sometimes only the jumper worked. Sometimes nothing worked, and then all of a sudden It did work. I'm still not sure what was going on.

@gaben I used avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cusbasp -Pusb -e -Ulock:w:0x3F:m -Uefuse:w:0x07:m -Uhfuse:w:0xDA:m -Ulfuse:w:0x62:m. Do you think its fault of USBAsp? I was combining -P200, jjumper and it sometimes work sometime didnt and twice it bricked my board. Really dont know what is the problem.

Those are more sensible fuse setting then in the other post. Not sure what the -P flag does.

I am closing this thread.
The board is probably not destroyed, more likely are fused corrupted.
There are ways of reviving ATMega328 chip and program fuses back its called high voltage programming. You need to probably unsolder the chip or modify your board (post from tontrack).
Also if you are wondering what to do or not to your Arduino board here is quite interesting page (you wil find it in comment).
I did not found a way how it could have happen but it did.
Anyway Iam done with UsbAsp programmer and ordered AVR pocket programmer. Until it arrives I stop any more attempts.
Hope this helps somebody.

How to destroy your Arduino https://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/


text:
Arduino Nano 3.0 and Arduino Uno Benchmarks
What are the benchmarks (MIPS) of an Arduino Uno (ATmega32P) and Arduino Nano 3.0 (Atmega328) @ 1.6MHz?

ATmega16U4/ATmega32U4, ATmega48A/PA/88A/PA/168A/PA/328/P, ATmega2560, and numerous other Atmel AVR 8-Bit microcontrollers have an instruction set typically with “135 Powerful Instructions – Most Single Clock Cycle Execution” per datasheets.
That is, many of the AVR instructions, including almost all of the logic and arithmetic instructions, execute in 1 cycle.  A fair number of memory access instructions take 2 cycles.  A few instructions (eg JMP) take 3 cycles, and some (RCALL, CALL, RET, RETI, et al) take 4 or 5 cycles.  Others (eg SBRC) take 1, 2, or 3 cycles, depending on operand values and whether a branch occurs that disrupts the pipeline, which is shallow.  For an overview, see the instruction set summary in any AVR-part datasheet. For details, see Atmel's AVR Instruction Set Manual, doc0856 at atmel.com.
Overall, the average instructions per second in a typical compiled C program probably is between 1.5 and 2, so a 16 MHz system might do 8 to 11 MIPS on average, while carefully tailored do-nothing code can easily achieve 16 MIPS.

Do you mean 16MzHz?
Benchmarks are here.

I checked the page out, but It did not answer my questions. I want to know how many instructions per second (IPS) can the microcontrollers preocess  at their 16MHz clock speed.


text:
ESP-01 won't start correctly
I'm trying to connect my Arduino Uno to an ESP-01 module, but I can't get it to start correctly. All I can get out from the ESP-01 is an "invalid" message when it is enabled. Can anyone please help? Additional information can be found below.
Here's my configuration:

Arduino connected to a computer via USB cable (serial connection working)
ESP-01 connected to the same UART connection, TX from Arduino is lowered to 3,3V with resistors
ESP-01 powered with external battery + capacitor to ensure sufficient current
I've tried all different configurations with GPIO0 and GPIO2 connecting them to ground and 3,3V, with and without resistors.
I've tried 3 different ESP modules

Here's how things work:

Arduino sends back every received UART transmission so that I can monitor the whole thing.
I can send messages to Arduino from a terminal on the PC and Arduino responds.
I can send messages from Arduino by pressing a button and the messages can be seen on the terminal.
When I send AT\r\n from Arduino I can read it on the terminal but nothing happens on the ESP-01.
When I send exactly the same message from the terminal, the blue light on ESP flashes but there is no response from the ESP. Arduino sends that message back to terminal of course.
When I connect CH_PD to 3,3V the ESP gives a message: Ai-Thinker Technology Co. Ltd.
invalid
The baud rate is correct (115200) since I can only read that invalid message on this rate

Sharing the hardware UART between the terminal and the ESP generally does not work well. You'll be much better off to add a SoftwareSerial port on another pair of pins to talk the the ESP.

This is one of the common problem that you have got.... If I am not wrong then you are unable to upload program to the esp.... I have a solution please  try that it may work for you...... Start the uploading process and unplug the power and plug the gpio 0 to groung and when you see the green to be complete plug the power and at the same time unplug gpio 0.... It may not work at first try... But keep trying, this method worked for me


text:
Equivalent for PORTB in Arduino Mega 2560
Like I said in the subject, I would like to know the equivalent for the instruction:
PORTB |= 0x01;
PORTB &= ~0x01;

More precisely I was using it to trigger a fast pulse conversion on my shield-ADC on an Arduino Uno. Now I am using an Arduino Mega 2560.
Can you write the exact same instruction for ATMega2560?

This code sends a pulse on pin PB0, which on the Uno is equivalent to
digital 8. On the Mega, digital 8 is PH5, thus you would write
PORTH |= _BV(PH5);
PORTH &= ~_BV(PH5);

The equivalence between the Arduino pins and the AVR pins is provided in
the official
documentation, but
there are nicer versions at pighixxx.com:

Uno pinout
Mega pinout

The other answer has provided correct information and useful documentation on the question as asked.  This answer uses a slightly more portable method of producing a brief pulse on a given digital pin.
This more-portable method uses some standard (although not well-documented at arduino.cc) functions to get port numbers, port pointers, and bit masks from a pin number.  These functions – digitalPinToPort(), portInputRegister(), and digitalPinToBitMask()– can be used at run time to compute physical ports and pins from Arduino pin numbers.  In some cases the computation could occur at compile time if compiler is smart enough or is allowed to optimize.  But avr-gcc as configured for the Arduino IDE is not so allowed, which is a reasonable default for embedded programming.
This method also uses the fact that an AVR pin – as on most Atmel-based Arduinos – will toggle when you write a 1 to its bit in its input register.  For example, see §14.1 in Atmel doc8271, the ATmega48A/PA/88A/PA/168A/PA/328/P datasheet, which states:

Three I/O memory address locations are allocated for each port, one each for the Data Register – PORTx, Data Direction Register – DDRx, and the Port Input Pins – PINx. The Port Input Pins I/O location is read only, while the Data Register and the Data Direction Register are read/write. However, writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register. ...

Example program
/*  jiw - Jan 2017 - toggle Arduino digital pin 8 several ways
Re: http://arduino.stackexchange.com/questions/33033/equivalent-for-portb-in-arduino-mega-2560 */
volatile uint8_t *portofpin;
uint8_t bitofpin;
void setup() {
  pinMode(8, OUTPUT);       // Set pin as output
  portofpin = portInputRegister(digitalPinToPort(8));
  bitofpin = digitalPinToBitMask(8);
}
void udelay() {
  delayMicroseconds(5);
}
void loop() {
  PORTB |= 0x01;        // Set Uno pin 8
  PORTB &= ~0x01;       // Clear Uno pin 8
  udelay();
  PINB = 1;         // Toggle Uno pin 8
  PINB = 1;         // Toggle Uno pin 8
  udelay();
  PINB = bitofpin;      // Toggle Uno pin 8
  PINB = bitofpin;      // Toggle Uno pin 8
  udelay();
  *portofpin = bitofpin;    // Toggle Arduino pin 8
  *portofpin = bitofpin;    // Toggle Arduino pin 8
  udelay();
}

Compilation on Uno
loop(), from compilation of the example program for an Uno board:
void loop() {
  PORTB |= 0x01;                // Set Uno pin 8
 10e:   28 9a           sbi     0x05, 0 ; 5
  PORTB &= ~0x01;               // Clear Uno pin 8
 110:   28 98           cbi     0x05, 0 ; 5
  udelay();
 112:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
  PINB = 1;                     // Toggle Uno pin 8
 116:   81 e0           ldi     r24, 0x01       ; 1
 118:   83 b9           out     0x03, r24       ; 3
  PINB = 1;                     // Toggle Uno pin 8
 11a:   83 b9           out     0x03, r24       ; 3
  udelay();
 11c:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
  PINB = bitofpin;              // Toggle Uno pin 8
 120:   80 91 00 01     lds     r24, 0x0100
 124:   83 b9           out     0x03, r24       ; 3
  PINB = bitofpin;              // Toggle Uno pin 8
 126:   80 91 00 01     lds     r24, 0x0100
 12a:   83 b9           out     0x03, r24       ; 3
  udelay();
 12c:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 130:   e0 91 01 01     lds     r30, 0x0101
 134:   f0 91 02 01     lds     r31, 0x0102
 138:   80 91 00 01     lds     r24, 0x0100
 13c:   80 83           st      Z, r24
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 13e:   e0 91 01 01     lds     r30, 0x0101
 142:   f0 91 02 01     lds     r31, 0x0102
 146:   80 91 00 01     lds     r24, 0x0100
 14a:   80 83           st      Z, r24
  udelay();
 14c:   0c 94 83 00     jmp     0x106   ; 0x106 <_Z6udelayv>

As you can see in the above, instead of using read/modify/write sequences to implement PORTB |= 0x01; PORTB &= ~0x01;, the compiler produced sbi 0x05,0; cbi 0x05,0;, to directly set and then clear bit 0 of register 5, PORTB.  This uses 4 clock cycles total, producing a pulse that's high for 2 cycles.
avr-gcc implemented PINB = 1; PINB = 1; via ldi r24, 1; out 3,r24; out 3,r24, which takes 3 cycles total and produces a pulse that's high for 1 cycle.
It implemented PINB = bitofpin; PINB = bitofpin; via lds r24, 0x0100; out 3,r24; lds r24, 0x0100; out 3,r24, which takes 6 cycles total and produces a pulse that's high for 3 cycles.  (In setup(), the value of bitofpin was stored in RAM location 0x100, and the value of portofpin was stored in 0x101, 0x102.)
Finally, it implemented *portofpin = bitofpin; *portofpin = bitofpin; via a six-instruction sequence that takes 14 cycles and produces a pulse that's high for 7 cycles.  Obviously, the compiler could have produced a 4-instruction sequence (by not reloading r30, r31, and r24) that takes 8 cycles and a pulse that's high for 1 cycle, but it didn't.

Compilation on Mega
loop(), from compilation of the example program for a Mega or Mega 2560 board:
void loop() {
  PORTB |= 0x01;                // Set Uno pin 8
 218:   28 9a           sbi     0x05, 0 ; 5
  PORTB &= ~0x01;               // Clear Uno pin 8
 21a:   28 98           cbi     0x05, 0 ; 5
  udelay();
 21c:   fa df           rcall   .-12            ; 0x212 <_Z6udelayv>
 21e:   81 e0           ldi     r24, 0x01       ; 1
  PINB = 1;                     // Toggle Uno pin 8
 220:   83 b9           out     0x03, r24       ; 3
 222:   83 b9           out     0x03, r24       ; 3
  PINB = 1;                     // Toggle Uno pin 8
 224:   f6 df           rcall   .-20            ; 0x212 <_Z6udelayv>
  udelay();
 226:   80 91 00 02     lds     r24, 0x0200
  PINB = bitofpin;              // Toggle Uno pin 8
 22a:   83 b9           out     0x03, r24       ; 3
 22c:   80 91 00 02     lds     r24, 0x0200
  PINB = bitofpin;              // Toggle Uno pin 8
 230:   83 b9           out     0x03, r24       ; 3
 232:   ef df           rcall   .-34            ; 0x212 <_Z6udelayv>
 234:   e0 91 01 02     lds     r30, 0x0201
  udelay();
 238:   f0 91 02 02     lds     r31, 0x0202
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 23c:   80 91 00 02     lds     r24, 0x0200
 240:   80 83           st      Z, r24
 242:   e0 91 01 02     lds     r30, 0x0201
 246:   f0 91 02 02     lds     r31, 0x0202
  *portofpin = bitofpin;        // Toggle Arduino pin 8
 24a:   80 91 00 02     lds     r24, 0x0200
 24e:   80 83           st      Z, r24
 250:   e0 cf           rjmp    .-64            ; 0x212 <_Z6udelayv>

The assembly code for Mega is much the same as that for the Uno, except that bitofpin and portofpin values were stored in RAM 0x200–0x202 instead of 0x100–0x102, and rcall or rjmp was used to call udelay();, instead of call or jmp.

Making assembly listings
To make assembly listing files for a program, use a command like
avr-objdump -CSI$PWD $TMPPATH/togglepin8.cpp.elf > togglepin8.ino.mega.asm

where $PWD represents the current working directory that contains a sketch like togglepin8.ino, and $TMPPATH represents whatever temporary directory the IDE stuck the source in to compile and link it.  The C switch (not used for above listings) tells avr-objdump to demangle symbols.  Switch S says to display source code intermixed with disassembly if possible.  Switch I tells location of source code.

Conditional compilation
Conditional compilation is another way to make the source code portable to several Arduinos.  For example, near the beginning of the sketch one could include the following #ifdef and #define statements to set up BITOFPIN and PORTOFPIN values for later use:
#ifdef ARDUINO_AVR_UNO
#define BITOFPIN  1
#define PORTOFPIN PINB
#endif
#ifdef ARDUINO_AVR_MEGA2560
#define BITOFPIN  _BV(PH5)
#define PORTOFPIN PINH
#endif

To find out what board-dependent symbols are defined at compile time, turn on verbose output during compilation and look for flags of the form -Dsym=val.


text:
RS232-TTL Data Transmission
I'm developing an computacional module to create risk maps in agriculture, I am using one arduino mega as "GreenSeeker", generating "fake" data to transmit via RS232 connection to one Raspberry PI, where she is process the data and generate the maps with GPS coordinates.
But, I have this cable.

I need to transmit data throught Arduino mega, and catch this data in the Raspberry PI.
I`ve have doubt about where connect the Serials pins on Arduino, the USB go on connect on the Raspberry PI USB, and the Serial go on Arduino, i need the right pins and where to connect them, and some code example.

Do you need a full 9 pin connection with hardware handshaking, or just an Rx/Tx? The latter is a simple affair with just a bit of soldering, but the former is going to be an ordeal.

Please edit the question and add an explanation of whatever might be the meaning of  “I need connect the Raspberry PI in one GreenSeeker, and the connector of this machine uses RS232 connection”

better this way?

The device pictured in the question Must Never be directly connected to a modern Arduino, as it uses RS232 levels, while an Arduino can only tolerate lower voltage "logic level" serial signal which are additionally inverted in sense.  Essentially you bought the wrong cable, and getting an adapter to make it work will be more awkward and expensive than getting the right cable.

You can indicate me the right cable?

I think you just want a normal USB A-B cable, exactly like you'd use on a PC.
You probably could use the cable you picture, but you'd need a female DB-9 connector.  If you really want to do that for some reason, you need to connect the Tx pin on the DB-9 (pin 2) to the Rx pin on the Mega, and the Rx pin on the DB-9 (pin 3) to the Tx pin on the Mega.

I really want to do that, because, I need connect the Raspberry PI in one GreenSeeker, and the connector of this machine uses RS232 connection.

@Avoxy way to spin this question and suddenly add other info. Where does the Mega come in? You can connect the greenseeker via this usb-to-rs232 adapter directly to the Pi.

I is using arduino to simulate the GreenSeeker data, i am is on University holidays, and the GreenSeeker machine is available only in my university, which is in other city.

The cable pictured in the this answer has possibility, but the one pictured in the question cannot and must not be used without an inverting level translator.  Attempting to use it without will destroy the Arduino.

@ChrisStratton Do you believe they run at full RS232 voltages? I suppose one should presume they might - but in reality I think many of them run at 5v. But it's a fair point - Avoxy, you should definitely check before you connect it.


text:
Need help with the basics on serial control
I am struggling to get my head around why this just won't work. In my simple mind this simple sketch should do as it's told. But I am obviously missing something fundamental.
If anyone could shed some light on what I am doing wrong that would be very good!
The sketch is just to control a relay by typing on or off into the serial monitor. However although it uploads, all I get is the Serial.println repeating and no action on the physical relay.
I can manage to control things over serial by using the switch, case statements but I wanted to try it using full words rather than single chars and also using IF statements etc.
Thanks in advance!
EDIT
I just changed the string inputs to a char input and serial.readstring to just serial.read and it works with just entering a 1 or a 2 for example. So to re-ask my question - how can I get it to respond the same but using words? Thanks!
int relay=8;
String serialInput;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
}

void loop() {
  Serial.println("To toggle relay enter on or off");
  while (Serial.available()==0) {}
  serialInput = Serial.readString();
  if(serialInput=="on") {
    digitalWrite(relay, HIGH);
  }
  if(serialInput=="off") {
    digitalWrite(relay, LOW);
  }
}

This should give you some clues to help fill in your missing knowledge: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Yes thank you! this certainly helps, how I thought serial comm's works and how it actually works are different things. This helped a lot! Thanks.

You are assuming that Serial.readString() will magically know how long a string you meant to send, and wait until it's all there.  It doesn't guarantee that.
If your PC uses Linux or Mac, you can use Serial.readStringUntil('\n'), which will read until a line end, and send on<ENTER> as your command.
If you use Windows, the line endings are \r\n so it's a bit more awkward.  Build up your string piece by piece, perhaps
int relay=8;
String serialInput;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    char c = Serial.read();   // get one byte from serial buffer
    if ('\r'==c || '\n'==c) {
      // End of line - process the string
      if(serialInput=="on") {
        digitalWrite(relay, HIGH);
      } else if (serialInput=="off") {
        digitalWrite(relay, LOW);
      }
      serialInput = "";
    } else {
      serialInput += c;     // add it to readString
    }
  }
}

Brief description of how it works:
The string SerialInput starts empty.  We do the following repeatedly:

If there is a character available on the serial port, read it.
If it is not an end-of-line character, add it to the end of our string
If it IS an end-of-line character, we know we've got to the end of the line, so...

check whether it matches one of our "target" strings, and act on it if so
clear it back to an empty string

Many thanks for you reply! Not fully understanding your code, but i'll research it some more. I tried to run you code, but it won't compile. I think 1 error was with a missing ' after ('\r'==c  so I added that but it still wont run. the error mentions serialInput not declared in this scope. I tried entering that also as a variable in the loop but still didn't work. any ideas? Thanks again for your time!

Very welcome. Whoops, typos fixed, and also added the first part of the code (which is an exact copy of yours). Also added an explanation of the code, which I hope helps.

Mark, thank you again!!! I really appreciate you taking your time here to help me understand. And I think it's starting to click! Your code works a treat now. Lastly if you don't mind to check that it has clicked with me... the C variable is just a random letter? it could be anything I liked? and the \r is simply waiting until i press enter\return on the serial monitor before checking then against the arguments set. And the \n is that like a double check for a return or specifically a newline? So it might work without that if you so desired? Honestly thanks again for your help!!

Glad it's helpful! Yes, char c could have been char theNewCharacter or anything you like. \r is a carriage return, \n is a new line. Windows puts both on the end of a line, Unix-like OSs put only \n. Rather than worrying about whether we'll get one or both, we just say "whenever we get a character which is part of a line-end, we know we have the whole line, so process it". On Windows you'll get both so you'll process the "real" line, then immediately try to process an empty string, which won't match "on" or "off", so nothing will happen - no harm done.

Fantastic explanation Mark! I GET IT!!! WOOO!!! I don't suppose you do private paid tutoring on Skype etc? I have a lots questions I have struggled with in programming for years and can never seem to get passed the basics. My end goal is to have DIY IOT capability with anything in the house I want, with a nice custom web interface to control or view these things. 3D printed parts and arduino's hooked into everything! But when I struggle so much with the basics it does seem like that goal is unreachable at times. Thanks again!


text:
Creating Arduino library file
I need to create a library file for Arduino. While surfing the Internet, it shows me to use C, C++. Is a C++/C compiler mandatory to create library files in Arduino? Or we can use the Arduino IDE to create library files?

Libraries are just text files. Use your favourite text editor (such as Sublime Text, Notepad++, etc. NOT a word processor like Word) to create and edit them. It is up to the IDE to compile them for you. You don't need anything else.

The Arduino IDE has a compiler, and will in the end compile the library with whatever .ino script you'll write. But you don't need any compiler to write a library. All you need is a text editor, and produce .cpp and .h files.
However when you test the library, you'll have to use the Arduino IDE to compile it.

Thank you.. So there's no need to install an external IDE to compile library files.

no, there is no such need


text:
How many modules can an Arduino Nano v3 support (in code)?
I'm planning to use an Arduino Nano v3 for a simple project plus some devices like capacitive touch buttons, an LCD display and a Bluetooth module on an I²C. Will these devices require (like classes or function in programming) that might take up the entirety of the 30KB space?
Devices:
HC-SR04 Distance Sensor
TTP229 Capacitive touch sensor
LCD1602+HD44780 LCD Display
HC-06 Bluetooth module

Please edit question and specify model number of LCD and Bluetooth module.  Graphic LCDs use rather more memory than text LCDs.  That aside, without details about the application, the question isn't particularly answerable.

The number of modules isn't really relevant; your PC deals with that during compilation and linking. The unbreakable requirement is that the total size of all the modules not exceed the size of available Flash memory.
The Bluetooth module won't need a library module unless you use SoftwareSerial to make another port for it. The two sensors' library footprints won't be too big. The LCD probably has at least one character table and maybe several sizes of each of several fonts. That's likely to be your largest one.
I always find microcontrollers' RAM size to impose much more stringent requirements than their Flash sizes.

The devices will require some code to make them work and there is a chance, depending on how you write the code, that this may consume all the available RAM on the chip.  However I doubt you will go to more than 60% if you use the standard libraries for those devices, but there is only one way to find out...
Get the libraries for the devices and look at the examples for each device.  You should be able to hack an "example" of your own that calls all 4 examples in the main loop().  This should give you an idea of how much memory you are going to use.
If you use too much it might be possible to snip pieces away from the libraries, the LCD will probably have font tables that you don't need for instance.  Or you could use an alternative Arduino.

If that so, I mignt refactor the library. Had an rpi but it consume alot more power.

I doubt you will need to.


text:
Arduino DUE as a FTDI programmer
I want to use Arduino DUE board as a FTDI programmer.
The task is to program ESP32 module which is connected to the Arduino Serial port.
I can use only DUE Native port. There is no DUE programming port in my design.

Cool story dude. Why do you mention this?

Forgot to ask. Is it possible?

Yes, it is possible, and not too difficult. Also, the native port is a lot faster than the programming  port ;)
All you need to do is to read the serialUSB data in and write it to the SerialX port, and read the data in from the SerialX port and write it to the SerialUSB port. It's best to do it on a byte by byte basis, and the due should be plenty fast enough.
This code should do the job. Let me know if it doesn't, and I'll take a look. (I have a Due and esp32)
void setup(void) {
  SerialUSB.begin(9600); //speed here doesn't matter as far as I am aware.
                         //the serial baud here should match the speed that
                         //you try to upload at to the esp32
  Serial1.begin(9600);   //change the Serial port to suit your needs
}
void loop(){
   if(SerialUSB.available()> 0){
    Serial1.write(SerialUSB.read());
   }
   if(Serial1.available()> 0){
    SerialUSB.write(Serial1.read());
   }
}


text:
Can I use the nRF8001 Bluefruit LE Breakout on 3.3V instead of 5V on my Arduino Uno?
I have an nRF8001 Bluefruit LE Breakout module and when I check images on how to wire it, the schematic looks like this with the 5V connection:

I was wondering whether it was possible to use the 3.3V instead. I looked at the documentation, it says this:

By connecting 5.0V on the VIN pin, all of the signals will be level shifted between 5V for the Arduino and 3.3V for the nRF8001, meaning you don't need to worry about damaging the IC by providing logic levels that it can't safely handle.

And this, which confirms that it works, right?

If you are using 3.3V logic, simply connect 3.3V from your development board to the VIN pin on the nRF8001 breakout.

I am pretty new, so I want to make sure, so I do not destroy any modules.
https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/hooking-everything-up

Yes. That nRF8001 board runs on 3.3V. And do make sure that using it with a 5V-Arduino, they put a regulator that steps down 5V to 3.3V. Which is why if you have 3.3V already, you connect it to Vin, and you're good to go.

Ok I use a standard arduino uno board. So i if i understand correctly and to make sure: Vin of the nRF8001 to the 3.3V of the arduino uno with a cable and i am good to go?

Yep. And don't forget the ground pin :-)

Awesome :) Yes exactly!! Thanks. Will upvote answer (can do it in 6 min stackoverflow says)

Yes will do it asap!

Seems to be working very well! I get connection in the serial monitor :) Awesome. I am very close to finish my first robot!


text:
How to flash an ATmega directly without a dedicated flashing device?
An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP).
I tried to flash the program into the microcontroller by saving the machine code to a MicroSD card that I then attached to the microcontroller. I figure we can use the USB SPI reader to test the program without dedicated device like USBtiny.
But I suspect that the compiler is just producing the hex file and then the USB will translate it to machine code.
Was I thinking wrong?
If the compiler loads the machine code through the USB programmer to microcontroller so don't we just need a MicroSD USB to program it?

Your initial assumption "An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP)." is wrong.
The C compiler converts the source code into assembly language. It is then passed to an assembler which converts it to object code. The linker then creates an ELF file from it all. That is then converted into a HEX file using objdump.
That HEX file is then loaded by another program, avrdude, which knows how to control the USB-connected programming device. That device then issues special instructions to the chip through the ISP port to copy the data loaded from the HEX file into the memory of the chip in the right way.
It's quite a complex procedure and you require some active component in the mix to do the job. Just connecting an SD card and hoping it will work is, I am sorry to say, a laughable concept. You require something that a) understands how to read data from an SD card and can interpret it, and b) knows how to program an ATMega through ISP.
It is possible to create something that does that, using another chip, such as another ATMega, and writing the software to do it. If you feel adventurous, of course. You would basically have created a stand-alone programmer, which has advantages when you want to do field upgrades, but is pointless when you are sat at your desk developing software.

thank you,i didn't know how the compilers in common market do.However,writing the raw data or file format to microSD to run in ATmega has been done by many developers.

The compiler doesn't do that, a separate program does that.  For most ATMegas and most people, the program that does this is called avrdude.  It interfaces with your ISP and transfers the code when you give it appropriate settings.  See here:
http://www.ladyada.net/learn/avr/avrdude.html
So you get the hex from your compiler, and send that through avrdude to the chip using your ISP.  At no point is the MicroSD necessary.  FWIW, the ATMega must have its code loaded into its flash memory.  It cannot run code from the Micro SD.

the developers in the world have finished projects to run external program in MicroSD,all the source code doesn't need to be compiled before runtime,i can put the source code into a library,re flashing it on board or running a virtual machine.


text:
Defining Serial UART
I'm new to Arduino..
I'm currently trying to create a GPRS connection through SIM card. For that, I need to connect a serial UART port.
I don't know how to define the Serial UART. Could you please help me with that?

There are millions of examples on google for how to do it. Have you tried asking it?

In the setup function you will need to call the Serial.begin() function.
To receive a serial character you should call the Serial.available() function inside an if statement.
To send a character you can either use the Serial.write() or Serial.print() functions.
Below is a simple example program that will echo the characters back to the PC.
//-------------------------
// Simple serial loopback
//-------------------------

void setup()
{
  // initialize the serial communication:
  Serial.begin(9600);
}

void loop()
{
  byte inChar;

  // check if data has been sent from the computer:
  if (Serial.available())
  {
    // read the most recent byte
    inChar = Serial.read();
    // send back the charater
    Serial.write(inChar);
  }
}

There are plenty of "built-in" examples in the Arduino IDE that use the various serial functions. These can be viewed without any hardware attached. In the IDE go to File > Examples and from there a lot of the examples for the serial UART are in the Communications section. Details of these examples can be found on the Arduino Tutorial site.

The uno's only hardware UART is used for peogramming and producing debug outpt.  If it is connected to a GPRS module then programming will not be possible and debug output will be problematic.

I've seen many boards use jumpers/switches/solderlinks/shields that you disconnect when you need to reprogram. Hopefully you get to a stage where you device works and you don't need to reprogram the micro.

The Arduino has only one UART which is used for program upload and for the serial terminal output to your computer. While you can connect it to another serial device that will make debugging cumbersome as 1) you won't be able to send any debug output; and 2) you will need to change it back and forth between your computer and the GPRS as you re-build and upload your code. You pretty much need a second UART to do this any kind of conveniently.
Look up the library module called SoftwareSerial which can simulate a UART on a second pair of pins, with some limitations: It is limited to communicating at 9600 baud; it can not transmit and receive at the same time; at most, one SoftwareSerial port can be receiving (or even listening) at any one time; and it can interfere with some other internal hardware, notably the interrupt system and at least one of the timers.  (The link points to the Arduino website whose documentation isn't always the very latest, but what's there will give you the idea).
In many cases, and yours is likely one of them, these are not show-stoppers, just something to be aware of as your code becomes more complex. As long as you can operate your device by occasionally sending it a string and receiving another in reply, and your system doesn't include other high-speed devices that must be serviced quickly when they request it, you probably won't notice the limitations.

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


text:
Safe place to download CH340G drivers from
I am working with an Arduino Uno clone that uses the CH340G USB to TTL converter in lieu of the 16U2 found on the Uno. I see that most tutorials suggest downloading the CH340G drivers from what they call "a chinese website". I don't quite trust that site, is there any more trustworthy website where one might be able to acquire CH340G drivers for a modern Linux distro (preferably CentOS or Debian).
I ask here because devices with that chip seem to be popular in the Arduino community. If the unix stackexchange site would be a better place to ask then the question can be moved. Thank you.
EDIT: Apparently my system is having an issue with recognizing the device. Here are some specs:
$ lsusb
Bus 002 Device 002: ID 8087:8000 Intel Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:8008 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 004: ID 04d9:3015 Holtek Semiconductor, Inc.
Bus 003 Device 003: ID 0cf3:9271 Atheros Communications, Inc. AR9271 802.11n
Bus 003 Device 012: ID 045e:0040 Microsoft Corp. Wheel Mouse Optical
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

$ lsusb | wc -l
9

$ # Now I plug in the Uno clone
$ # Wait about a minute just to be sure...
$ lsusb
Bus 002 Device 002: ID 8087:8000 Intel Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:8008 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 004: ID 04d9:3015 Holtek Semiconductor, Inc.
Bus 003 Device 003: ID 0cf3:9271 Atheros Communications, Inc. AR9271 802.11n
Bus 003 Device 012: ID 045e:0040 Microsoft Corp. Wheel Mouse Optical
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
$ lsusb | wc -l
9

$ uname -a
Linux happiness 4.4.0-47-generic #68-Ubuntu SMP Wed Oct 26 19:39:52 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

$ cat /etc/issue
Ubuntu 16.04.1 LTS \n \l

My entire dmesg file can be found on pastebin, here is the end of it:
[37253.943739] usb 3-6: device descriptor read/64, error -71
[37254.159669] usb 3-6: new full-speed USB device number 15 using xhci_hcd
[37254.159841] usb 3-6: Device not responding to setup address.
[37254.363858] usb 3-6: Device not responding to setup address.
[37254.567744] usb 3-6: device not accepting address 15, error -71
[37254.679654] usb 3-6: new full-speed USB device number 16 using xhci_hcd
[37254.679756] usb 3-6: Device not responding to setup address.
[37254.883917] usb 3-6: Device not responding to setup address.
[37255.087716] usb 3-6: device not accepting address 16, error -71
[37255.087749] usb usb3-port6: unable to enumerate USB device

That "Chinese website" is the manufacturer's web site. Can't be more authoritative than that...

Drivers...? for Linux...?!?! What are they?!

Indeed, you should not download drivers from random websites for a Linux system, not only as  matter of safe practices but also because it is unlikely that they would be usable.  USB serial converters for Linux are handled by kernel modules and those need to be compiled for the specific kernel in use or its close relative.  Modern Linux distros likely support the CH340G already as the driver is included in the official kernel source, if not you should pursue obtaining a suitable kernel module from the provider of your distro or get the upsteam or distro kernel sources and compile the module.

Your edits suggests this is an electrical fault or signalling issue, with the board, cable, USB port (or possibly two of these being slightly out of spec in opposite directions so they still work with other things but not with each other), and not a driver problem at all.

@ChrisStratton: Thank you. I've actually just reverted the edit and asked a new question on Unix.SE. In the meantime I'll try on different USB ports on the same machine. I don't currently have access to another computer to test on.

Since you do not appear to have a software problem, posting on unix.se is inappropriate, and removing information from the posting here that revealed the nature of your problem was highly inappropriate.

@ChrisStratton: I see, thank you. I see that you've reinstated the information on this post. Thank you, your help and initiative are much appreciated!

It's more likely that the CH340G chip is dead, or that the crystal driving it isn't accurate enough.

I think you really don't get it: That strange chinese "not-trustworthy website" all tutorials recommend, is the homepage of the manufacturer! So, no matter if windows, linux, mac, or android, it will be hard to find alternative drivers.

Yes, I now know this to be correct. Luckily the current Linux kernels already do come with the proper drivers. Thank you!

Linux doesn't need drivers (indeed, the whole concept is pretty alien to Linux users).
The CH340G is fully supported by the default kernel in all distros I have ever used. On my Ubuntu machine the CH340G on my NodeMCU is detected automatically:
[ 8195.450566] usb 4-1: new full-speed USB device number 2 using uhci_hcd
[ 8195.630710] usb 4-1: New USB device found, idVendor=1a86, idProduct=7523
[ 8195.630714] usb 4-1: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[ 8195.630716] usb 4-1: Product: USB2.0-Serial
[ 8196.675137] usbcore: registered new interface driver usbserial
[ 8196.675153] usbcore: registered new interface driver usbserial_generic
[ 8196.675166] usbserial: USB Serial support registered for generic
[ 8196.677581] usbcore: registered new interface driver ch341
[ 8196.677600] usbserial: USB Serial support registered for ch341-uart
[ 8196.677620] ch341 4-1:1.0: ch341-uart converter detected
[ 8196.690670] usb 4-1: ch341-uart converter now attached to ttyUSB0

Nothing to download, nothing to install, nothing to risk the security of your system with.

"Linux doesn't need drivers", then proceeds to post log showing how kernel loads dynamically three driver modules. I feel conflicted.

@snaipperi Right, those come as part of the kernel itself. You can just as easily build a kernel with those drivers non-modular, or build an entirely monolithic kernel that doesn't use modules at all. Also, Kernel modules aren't always "drivers", various other internal workings like filesystems and even security management tools are implemented as kernel modules.

I was just nitpicking that the statement "linux doesn't need drivers" is incorrect. The ch341 module, regardless of being shipped with the kernel, is an interface driver and is very much needed by the kernel to be able to talk with the chip.

I think what is attempted here is a statement that downloading drivers from a third-party site is pretty alien. If your distro does not already ship the driver as a kernel module, you would typically download the driver's source code and compile it against your kernel version (for which you then also need the source code); though of course, some distros already do this for some drivers, and package the result as an installable package. But it's not unheard of for a manufacturer to provide a downloadable device driver module for Linux (possibly even as closed source).

"Linux doesn't need drivers (indeed, the whole concept is pretty alien to Linux users)."
I feel alienated, however this information is incorrect. I have at least two Ubuntu machines that did not recognize the CH340g chip. One is Linux Mint 18.2 32bit the other is a Linux Mint 19 64bit. I used the 'driver' that I downloaded from the site in question and guess what? It is the exact same driver that NodeMCU uses. For those that want or need to download the driver, but don't want to visit a 'suspicious site' just go here nodemcu-dev and you will find three flavors: Linux, MAC and Windows. Strange that they have an MIT license for their own software.
For Linux, just extract the archive CH341SER_LINUX.ZIP, then open a terminal in the directory and use make && sudo make then load the module ahem.. driver with (may need to use sudo) insmod /{path-to-your-extracted-folder}/ch34x.ko or reboot.
Now, I am not arguing whether or not Linux comes with the module, because I see two (one for each kernel) on just one of my systems located at /lib/modules/{x.x.x-xx}-generic/kernel/drivers/usb/serial/ch341.ko, however the one that is needed comes from the Chinese site in question that happens to be the same place where NodeMCU got theirs (or possibly some other site) for it to be recognized.
Also, I don't get how someone can buy Chinese products (or from anywhere else) and be afraid to visit their site.


text:
How to: Connecting 4-pin Joystick to Arduino board
I am completely new at Arduino. I have a joystick:

It is however quite different from all the other joystick-tutorials, as their joysticks have 5 pins, not just 4. So I am quite at loss here. How do I connect it?

I would imagine one pin goes to 5V, one to GND, and the other two connect to analog inputs. I would expect there to be markings on the board telling you which is which.

Wouldn't I need one to a key to read the data?

I didn't understand what you just asked.

Is the fifth for when you press down on the joystick, like a button? Try connecting a multimeter and see how the resistances change when you play with the joystick.

This joystick probably does not have a push button under it in the way that some others do.  If you need that functionality you can provide it with a distinct pushbutton placed to the side, or you can buy a different joystick.

Hah thanks, that's what I meant by my question, sorry for the lack of clarity @Majenko. All there is left for me to do is find the library/code to interpret the data from the joystick. Thanks for the help.

You read the analog value. That's really all there is to it. Analog values go from 0 to 1023. 512 (or thereabouts) is the middle of the joystick. It goes up and down from there. There's nothing to "interpret", and you certainly won't find a library for it.

Oh, well thanks then. How would it be if one moved it across the X/Y-axis? Would it just display a change?

This looks like it. There's a photo of the pinout and some basic details on it.

Is there nothing printed underneath? The one linked to by Mark Smith has the exact pin-outs under it. You hardly need a library for this. About four lines of code would do it, two of them being analogRead.

If the link that Mark Smith provided is correct, that is a “dual-axis mini xy joystick module PSP 2-Axis Analog Thumb Joystick Module Thumb Joystick for Arduino”, with (as other comments suggested) pins labeled on back of board as GND, X, Y, VCC.
To use it, attach GND to Arduino ground; connect each of X and Y to analog inputs, like A0 ... A7; connect VCC to (typically) 5 V.  Then read results on your analog input lines.
Note, it makes sense to test the device using a DVM beforehand.  Measure resistance from GND to VCC to find out overall resistance, so you can decide if 5 V is appropriate or if you should use a lower voltage.  (For example, if overall resistance is several thousand ohms, 5 V is ok; if only a few hundred, add one or two thousand ohms in series and take analog readings using a 1.1 V reference instead of 5 V reference.)  Also measure resistance from GND to X as you move the thumb control, and from GND to Y.

For sure there should be 4 pins, 'GND', 'VCC', 'X' and 'Y'. GND (-) is used when the joystick goes into a negative axis (depending x or y) on a Cartesian plane it transfers as negative into the Arduino board. The same thing happens when it goes to positive (VCC (+)) (depending x or y) on a Cartesian plane it transfers as positive onto the Arduino Board.


text:
Adapt Dynamixel library to different shields
I have been playing around with this shield for a couple of days now and I have to agree with some statements made in the comments that the "library" lacks many functions.
However I have discovered the following library which was built for the Dynamixel shield: https://github.com/zcshiner/Dynamixel_Serial
I wanted to know since I am using an Arduino Uno, which parameters I would have to change to make it work.
Sorry I am not very fluent in C++. I have tried just changing the direction pin to 10 but it's obviously not sufficient.
Shield to be dealt with: https://dfrobot.com/index.php?route=product/product&product_id=958
The following code should work afterwards:
#include <dynamixel_serial.h> // Library needed to control Dynamixel servo

#define SERVO_ID 0x01 // ID which we will set Dynamixel to
#define SERVO_ControlPin 0x0A // Control pin of buffer chip, NOTE: this does not matter because we are not using a half to full control buffer.
#define SERVO_SET_Baudrate 57600 // Baud rate speed which the Dynamixel will be set to (57600)
#define CW_LIMIT_ANGLE 0x001 // lowest clockwise angle is 1, as when set to 0 it sets servo to wheel mode
#define CCW_LIMIT_ANGLE 0xFFF // Highest anti-clockwise angle is 0XFFF, as when set to 0 it sets servo to wheel mode

void setup() {
  delay(1000); // Give time for Dynamixel to start on power-up
  Dynamixel.begin(SERVO_SET_Baudrate); // We now need to set Arduino to the new baud rate speed
  Dynamixel.setDirectionPin(SERVO_ControlPin); // Optional. Set direction control pin
  Dynamixel.setMode(SERVO_ID, SERVO, CW_LIMIT_ANGLE, CCW_LIMIT_ANGLE); // set mode to SERVO and set angle limits
  Serial.begin(115200);
  Serial.println("Setup Done!");
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  Dynamixel.servo(SERVO_ID,0x001,0x100); // Move servo to angle 1(0.088 degree) at speed 100
  delay(4000);
  Dynamixel.servo(SERVO_ID,0xFFF,0x3FF); // Move servo to max angle at max speed (1023)
  delay(4000);
}

You are setting the baudrate to 57.6K however, you need to communicate with the Dynamixel at the baudrate it is set to. I believe the Dynamixel comes with a preset baudrate of 1Mbs. The first thing thing I would do is to change your 57.6K to 1Mbs and try that. This is assuming the ID is actually 1 (also a default)
Here are two links for info on Arduino baud rates and Dynamixel serial communications.
Controlling AX-12 Servos
How high of a baud rate can I go (without errors)?

Thank you very much I am going to try as soon as I have got the possiblitiy


text:
What does map() do?
Regarding the following code:
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
ax = map(ax, -17000, 17000, -1500, 1500);

I know the reason for taking 17000 as value - that's 1g.  But I am not getting how and why 1500 value is taken.

The map() function is well explained here.
In short, it maps one range of numbers to another.  In this case it will map ax from the range (-17000:17000) into the range (-1500:1500).
Imagine a ruler with both inches and cm on.  If you have a measurement in inches, you can represent that same measurement (point on the ruler) in cm.  Your "ruler" here has one scale ranging from -17000 to 17000, and another scale ranging from -1500 to 1500.  You're finding the reading on the second side at the point ax on the first.
If you mean specifically why are those numbers used -- then I have no idea since you give no context.

.Thanku so much. now i understood. your exampple of ruler just nailed it.

You're welcome. If the answer was helpful you can accept it and optionally up-vote it :-)


text:
creating table in 24LC256
here i am doing some project with the help of Arduino UNO with External EEPROM (24LC256),
 All i want to create table and wants to  store all  data into  24LC256 External EEPROM,there are many library for internal EEPROM to create table with limited data as per size of arduino EEPROM but i have huge data to store so have to use External eeprom to do, so  i can't find any proper library for doing that.!
can anyone tell me how to do that...
any suggestion..Please help me..
thanking you..

I don't quite understand the question. Are you looking for an Arduino library to use (read from and/or write to) the 24LC256?

Creating tables is a database thing. What are you actually trying to do?

Simplest way to create a table is to view it as a vector of struct's. For performance it is good to make the struct size a multiple of the EEPROM page size.
struct row_t {
  ... column fields ...
};

uint32_t row_addr = TABLE_START_ADDR;
row_t data;
data.column = value;
...

eeprom.write(row_addr, &data, sizeof(data));
row_addr += sizeof(row_t);
...

Basically you need to map a two/multiple dimensional table onto a one dimensional address space (of the EEPROM). The programming language can help with some of the calculations (and hide them).
Cheers!

Exactly i want to know what's library do i have to used and how...?

Did you do a web-search or check the arduino playground? You could for instance start here; http://playground.arduino.cc/Main/LibraryForI2CEEPROM


text:
How do I send a string from an Arduino Slave using SPI?
I have an Arduino Uno acting as a master with 3 Arduino Nano's acting as a slaves.
Looking at this example:
http://www.gammon.com.au/forum/?id=10892, it tells me how to send a string from the master to the slave, but I didn't see any examples sending a string from the slave to the master device. I was able to successfully send and receive digits to/from the master and slave, but I couldn't figure out how to send strings from the slave to the master based on the example.
My understanding is that SPI communications can only send information byte by byte, so am I supposed to convert my string into a byte format before putting that into the SPDR variable so that it can be sent back to the master?
In any case, would I be able to get some pointers on how to send strings from the slave to the master?
Thanks in advance.

Remember the master controls the transmission (provides the clock), however it can be done. For example:

Master
// master

#include <SPI.h>

void setup (void)
{
  Serial.begin (115200);
  Serial.println ("Starting");

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{
  char buf [20];

  // enable Slave Select
  digitalWrite(SS, LOW);
  SPI.transfer (1);   // initiate transmission
  for (int pos = 0; pos < sizeof (buf) - 1; pos++)
    {
    delayMicroseconds (15);
    buf [pos] = SPI.transfer (0);
    if (buf [pos] == 0)
      {
      break;
      }
    }

  buf [sizeof (buf) - 1] = 0;  // ensure terminating null

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.print ("We received: ");
  Serial.println (buf);

  delay (1000);  // 1 second delay
}  // end of loop

In this example the master initiates a transmission by sending 0x01 to the slave. Then it gets bytes back until a 0x00 byte (signifying the end of the string). The delayMicroseconds is there to give the slave time to respond.

Slave
// Slave

void setup (void)
{

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit(SPE);

  // turn on interrupts
  SPCR |= bit(SPIE);
}  // end of setup

volatile char buf [20] = "Hello, world!";
volatile int pos;
volatile bool active;

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  if (c == 1)  // starting new sequence?
    {
    active = true;
    pos = 0;
    SPDR = buf [pos++];   // send first byte
    return;
    }

  if (!active)
    {
    SPDR = 0;
    return;
    }

  SPDR = buf [pos];
  if (buf [pos] == 0 || ++pos >= sizeof (buf))
    active = false;
}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{

}  // end of loop

The slave does everything inside the ISR. The arrival of the 0x01 byte makes it reset its "pointer" to the start of the buffer. After that it responds with another byte from the buffer until it has reached the terminating 0x00 byte.

In part of sender I'm use the convert String to char array method before sending to the receiver.
Master
#include <SPI.h>
const int size_arr = 50;  // define array size (must be less than size of slave)
char buf[size_arr]; // define char array, use for convert from string for send to slave
String main_dat = "jack,12,47,123,8888"; // real String data

void setup() {

pinMode(SS, OUTPUT);
digitalWrite(SS, HIGH);
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV4);

}
void loop() {
main_dat.toCharArray(buf, size_arr); // convert String data to char array
Spi_tranmis(buf); // send char array
delay(500);

}

void send_spi(byte pram) {

  digitalWrite(SS, LOW);
  SPI.transfer(pram);
  digitalWrite(SS, HIGH);
  delayMicroseconds(50);

}

void Spi_tranmis(char buf[]) {
for (int i = 0 ; i < size_arr ; i ++) {
  send_spi(buf[i]);
}

send_spi('\n');
}

And in part of receiver i'm use char array receive from master and convert to String leter.
Slave
#include <SPI.h>

const int size_arr = 51; // define array size (must be more than size of master)
char buf[size_arr]; // char array , use for recive from master

volatile byte pos = 0;
volatile boolean process = false;

String msg; // real data

void setup() {
   Serial.begin(9600);
   Serial.println("test");
   pinMode(MISO, OUTPUT);
   digitalWrite(MISO, LOW);
   SPCR |= _BV(SPE);
   SPCR |= _BV(SPIE);

 }

 ISR(SPI_STC_vect) {
  char c = SPDR;

  if (pos < sizeof buf) {
    if (c == '\n') {
      process = true;
    }
     else {
      buf[pos++] = c;
     }
   }
 }

void loop() {
  recvHandle();

}

void recvHandle() {
  if (process) {  // when SPI available
    msg = String(buf);   // convert char array to String
    Serial.println(msg);
    process = false;
    pos = 0;
  }

}

You must define size of char array in receiver more than sender *

String is only array of char ended by char \0. But you can also access it as array of bytes ended with 0. And send them by one byte until it reaches the 0 (send it too). On master you save it to long enough  array of char (work with it as with bytes) including the final zero and bingo, you have char string transmitted :)

How do I send a string from the an Arduino Slave using SPI?

Depending on your definition of string it would look something like this (for master):
String message = "....";
SPI.transfer(message.c_str(), message.length() + 1);

or
char message[MESSAGE_MAX];
strcpy(message, ....);
SPI.transfer(message, strlen(message) + 1);

For the SPI slave this will need to be transformed to either an SPI ISR or busy-wait for chip-select and then the transfer.
Cheers!


text:
Accessing Values From Array Within a Library
There are many great examples of how to access information from an array on the net. I ran into a specific case that has me confused. I am using a library for attiny 85 TinyPpmReader.h. This is a simple library that will take PPM signals in from a RC receiver running in pulse position mode and allows you to attach to a pin to process input. Easy enough.
In the code below, I ran into some confusion when trying to access the data in the array. I am trying to filter out a single channel in the ppm stream and print the contents of only 1 channel (Original example prints 8 channels) and eventually map that value to a servo. (I pasted the serial monitor ouput at the end of the code)
I tried accessing the variable stored in the array like this:
void loop()
{
for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */

if(TinyPpmReader.detectedChannelNb == [5]) //Is this channel 6 in index 0-7?
{
Serial.println(TinyPpmReader.width_us[5); // if so, print only index 5 containing channel 6 values
}
delay(500);
}

Example unedited sketch from library
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

#define PPM_INPUT_PIN  2

void setup()
{
  Serial.begin(38400)
  TinyPpmReader.attach(PPM_INPUT_PIN);
}

void loop()
{

  Serial.print(F("* Period="));Serial.print((int)TinyPpmReader.ppmPeriod_us());Serial.println(F(" us *"));
  Serial.print(F("ChNb="));Serial.println((int)TinyPpmReader.detectedChannelNb());
  for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */
  {
    Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us"));
  }
  delay(500);
}

The serial monitor prints this:
* Period=17928 us *
ChNb=8
Ch=1496 us
Ch=1744 us
Ch=896 us
Ch=1560 us
Ch=1640 us
Ch=1496 us
Ch=1536 us
Ch=1688 us

Any suggestions? It is probably something simple but I dont think I am googling the correct question to get the correct answer.
EDIT: That worked Mark!
New Code Mapping attempt (Compiles,does not work)
#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int PPM_INPUT_PIN = TinyPpmReader.width_us(3); //<------- Doesn't work

//int potpin0 = 3;    <---------          // This worked
int val0;                     // integer to store value

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

void setup()
{
  setupServos();
}

void loop()
{
  val0 = analogRead(PPM_INPUT_PIN);  <---------          // reads the value of the       potentiometer (value between 0 and 1023)            // reads the value of the 2nd potentiometer (value between 0 and 1023)
  val0= map(val0, 1000, 2000, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)
       // scale it to use it with the servo (value between 0 and 180)

moveServo(PANSERVO, val0);

  delay(5);                           // waits for the servo to get there
}

We'll need to know how the library stores data in the array, if you know that. Or a link to the library would help. I can tell you that your loop() function has syntax errors and won't compile as shown here. There is no need to scan the array with the for() loop and only read one element; you can just read that element like: ArrayName[5] (I can't be more specific than that without seeing the library). I have no idea how TinyPpmReader.detectedChannelNb == [5] evaluates but [5] by itself is unusual, if it even has any meaning, in C++. Did it even compile?

This is the link to the library. What Mark suggested below worked to only print the channel 3 values to the serial monitor.
https://github.com/RC-Navy/DigisparkArduinoIntegration/tree/master/libraries/DigisparkTinyPpmGen

This code (from the example) is what prints a single index - index Idx:
Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us")); }

To print, say, index 3 you'd use
Serial.print(F("Ch"));Serial.print(3);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(3));Serial.println(F(" us")); }

To simply get the value from index 3, without printing it:
int a = TinyPpmReader.width_us(3);

(assuming it's an int)

That worked! Thanks!
I was able to only print channel 3 info to the serial monitor.
The ultimate goal was to map channel 3 using:
int a = TinyPpmReader.width_us(3);
But if you check the new code I just added above (below original post) I am not able to map this as an integer for some reason. I added arrows where I changed the code to try to map channel 3. Why does it not compile or map like this?

Glad to hear it.  This is a new question really - we should stick to one question per, erm, question. If you post a new question I (or others) will try to help.

That said, perhaps you're not clear what PPM_INPUT_PIN is.  It's just the number of the pin - not the reading taken from that pin or anything - simply a way to identify the pin. With that in mind, int PPM_INPUT_PIN = TinyPpmReader.width_us(3); looks nonsensical.

OK, I will post another question and try to clarify. This question plus the new one hopefully will help people see how to access the array and map it .Thanks again Mark. Very appreciated!

posted new question about mapping the input here:
http://arduino.stackexchange.com/questions/33224/mapping-ppm-signals-to-servo-values