text:
code optimazation 6x6 Matrix
I planed a 6x6 matrix with a Arduino Nano as controller.
Its only possible to let one LED in the matrix lighten up.
Any idea how I get the Code smaller? (Im a C Noobie ^^)
~Nico
Circuit diagram:

Code:

void setup() {
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(14, INPUT);
  pinMode(15, INPUT);
  pinMode(16, INPUT);
  pinMode(17, INPUT);
}

void loop() {
  int value1 = digitalRead(14);
  int value2 = digitalRead(15);
  int value3 = digitalRead(16);
  int test = digitalRead(17);
  int x1 = 2;
  int x2 = 3;
  int x3 = 4;
  int x4 = 5;
  int x5 = 6;
  int x6 = 7;
  int y1 = 8;
  int y2 = 9;
  int y3 = 10;
  int y4 = 11;
  int y5 = 12;
  int y6 = 13;

  // put your main code here, to run repeatedly:

  if (test == HIGH) {
    digitalWrite(x1, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x1, LOW);
    digitalWrite(x2, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x2, LOW);
    digitalWrite(x3, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x3, LOW);
    digitalWrite(x4, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x4, LOW);
    digitalWrite(x5, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x5, LOW);
    digitalWrite(x6, HIGH);
    digitalWrite(y1, HIGH);
    delay(15);
    digitalWrite(y1, LOW);
    digitalWrite(y2, HIGH);
    delay(15);
    digitalWrite(y2, LOW);
    digitalWrite(y3, HIGH);
    delay(15);
    digitalWrite(y3, LOW);
    digitalWrite(y4, HIGH);
    delay(15);
    digitalWrite(y4, LOW);
    digitalWrite(y5, HIGH);
    delay(15);
    digitalWrite(y5, LOW);
    digitalWrite(y6, HIGH);
    delay(15);
    digitalWrite(y6, LOW);
    digitalWrite(x6, LOW);

  }
}

The concepts which will help you are  for loops and possibly arrays.

Definitely arrays. Any idea how I get the Code smaller? - why does it need to be smaller? It fits into available memory, or it doesn't.

Any idea how I get the Code smaller?

don't try to get the code smaller -> try to get it working.
for things like this, you should think about
1) how to structure the display data: typically it is done in a matrix format. I would structure it as an array of 6 chars / columns, with the rows in the lowest 6 bits;
2) how to track the column being displayed and updated: using a static variable typically;
3) how to update the display periodically: via a timer interrupt usually.
Each update would go something like this:
  turn off all columns;
  present row information;
  update the column index and turn it on;

what's left is to implement that in a way that the code is flexible and portable to a different application.
once that's done, all your application needs to do is to stuff the right information into the display buffer and the display routine, invoked via a timer isr, will take care of the updating all by itself, without user involvement.
if you still need help, let us know.
edit: i put this together quickly to demonstrate the concept.
it is a display routine, led_display(), being invoked via a timer2 interrupt, displaying data in an 8-char buffer, 0x11, 0x22, ..., 0x88.
the scanning is done by colomn (active high), and the rows are connected to D0..D7, and the cols D8..D13, A0, A1, all user configurable.
//global variables
uint8_t lRAM[COL_NUM]={         //display buffer
    0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88
};

const uint8_t row_pins[ROW_NUM]={   //pins tied to matrix' rows
    0, 1, 2, 3, 4, 5, 6, 7,
};

const uint8_t col_pins[COL_NUM]={   //pins tied to columns
    8, 9, 10, 11, 12, 13, A0, A1,
};

once the initialial set-up is done, there is nothing the user needs to do, other than filling the display buffer with information s/he wishes to be displayed.
void setup() {
    // put your setup code here, to run once:
    //pinMode(led, OUTPUT);
    led_init();                         //reset the led module

    //set up timer2
    tmr2_init(TMR2PS_32x);              //timer2 with 32:1 prescaler -> 16Mhz / 256 / 32 = 2Khz per col.
    tmr2_act(led_display);              //install user handler to update the display periodically
}

void loop() {
    // put your main code here, to run repeatedly:
    //digitalWrite(led, HIGH);  // turn the LED on (HIGH is the voltage level)
    //delay(100);               // wait for a second
    //digitalWrite(led, LOW);   // turn the LED off by making the voltage LOW
    //delay(100);               // wait for a second
}

and here is the execution.
ps: the code was originally written to drive 8x7-segment displays but it works with 8x8 matrix as well -> they are essentially the same thing.
the display routine, led_display(), follows the general sketch laid out earlier.
//update the display
void led_display(void) {
    static uint8_t col_index=0;         //current col
    //turn off current col -> the only active col now
    COL_OFF(col_pins[col_index]);

    //update the column index
    col_index=(col_index==COL_NUM-1)?0:(col_index+1);

    //present row data
    if (lRAM[col_index] & (1<<0)) ROW_ON(row_pins[0]); else ROW_OFF(row_pins[0]);
    if (lRAM[col_index] & (1<<1)) ROW_ON(row_pins[1]); else ROW_OFF(row_pins[1]);
    if (lRAM[col_index] & (1<<2)) ROW_ON(row_pins[2]); else ROW_OFF(row_pins[2]);
    if (lRAM[col_index] & (1<<3)) ROW_ON(row_pins[3]); else ROW_OFF(row_pins[3]);
    if (lRAM[col_index] & (1<<4)) ROW_ON(row_pins[4]); else ROW_OFF(row_pins[4]);
    if (lRAM[col_index] & (1<<5)) ROW_ON(row_pins[5]); else ROW_OFF(row_pins[5]);
    if (lRAM[col_index] & (1<<6)) ROW_ON(row_pins[6]); else ROW_OFF(row_pins[6]);
    if (lRAM[col_index] & (1<<7)) ROW_ON(row_pins[7]); else ROW_OFF(row_pins[7]);

    //turn on the display
    COL_ON(col_pins[col_index]);
}

The problem is, that im not allowed to change something in the circuit. I am only coding it for a good Friend how allready solder it. The Circuit works and i have to programm some Programms for it :) Something like waves or circles.

if I understand something wrong correct me :D Im not so good in English

It is maybe possible to make a routine wich is going in the background and you can putt some pattern in it? if yes can you help me programm it :) I dont know much about c & c++

obviously people will be willing to help you but you have to get it started somewhere. no one is going to write the code for you.

You can use arrays to hold sets of row pin numbers or column pin numbers, which then allows use of for loops for pinMode() settings and for testing LEDs one after another, as shown in code below.
Note, using enum { ... }; for integer-constant declarations is slightly more compact than a series of const int statements.  When a constant name in an enum does not have an = and value after it, it is given a value one larger than the previous constant.  So, for example, the first enum in the following code sets x2 to 3, x3 to 4, etc.
enum { x1=2, x2, x3, x4, x5, x6};
enum { y1=8, y2, y3, y4, y5, y6};
const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
const byte colPins[] = { y1, y2, y3, y4, y5, y6};
enum { nRow = sizeof rowPins / sizeof rowPins[0] };
enum { nCol = sizeof colPins / sizeof colPins[0] };

void setup() {
  for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
  for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
  for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
}

void loop() {
  byte test = digitalRead(17);
  if (test) {
    for (byte x=0; x<nRow; ++x) {
      digitalWrite(rowPins[x], HIGH);
      for (byte y=0; y<nCol; ++y) {
        digitalWrite(colPins[y], HIGH);
        delay(15);
        digitalWrite(colPins[y], LOW);
      }
      digitalWrite(rowPins[x], LOW);
    }
  }
}

Note, subroutines and functions can be used to modularize code and (typically) reduce its volume.  See code sample below.  In the code as is, the subroutine doesn't particularly reduce volume, but definitely adds modularity.  You may find it useful to look up refactoring.
enum { x1=2, x2, x3, x4, x5, x6};
enum { y1=8, y2, y3, y4, y5, y6};
const byte rowPins[] = { x1, x2, x3, x4, x5, x6};
const byte colPins[] = { y1, y2, y3, y4, y5, y6};
enum { nRow = sizeof rowPins / sizeof rowPins[0] };
enum { nCol = sizeof colPins / sizeof colPins[0] };

void setup() {
  for (byte i=0; i<nRow; ++i) pinMode(rowPins[i], OUTPUT);
  for (byte i=0; i<nCol; ++i) pinMode(colPins[i], OUTPUT);
  for (byte i=14; i<18; ++i)  pinMode(i, INPUT);
}

void lightup(byte x, byte y, unsigned int howLong) {
  digitalWrite(rowPins[x], HIGH);
  digitalWrite(colPins[y], HIGH);
  delay(howLong);
  digitalWrite(colPins[y], LOW);
  digitalWrite(rowPins[x], LOW);
}

void loop() {
  byte test = digitalRead(17);
  if (test) {
    for (byte x=0; x<nRow; ++x)
      for (byte y=0; y<nCol; ++y)
        lightup(x, y, 15);
  }
}


text:
Can't include files
For some reason, the Arduino IDE can't find the file I have made for the project:
#include <foo1.h>
#include <foo2.h>
#include "foo3.h"

Where foo1 and foo2 are normal libraries thus included with <..> but foo3 is another file I wrote which resides in the same directory as the .ino file from where this code is taken.
If I essentially convert foo3 into a library and include it as a library in my project it works but makes the project harder to move.
Error I get:
Project.ino:6:23: fatal error: foo3.h: No such file or directory
:#include "foo3.h"
:compilation terminated
Error compiling project sources

Note: Error is persistent in both the Arduino IDE and VMicro

In the error message, it shows  <> for the problem file, although your question suggests you're using "" (as you should). Which is it?

Seems I have copied the wrong error message. Thanks for noticing.

The question is a bit unclear, however as far as I know, for the included libraries use:
#include <SPI.h>

So the < and > are used for common libraries which are in the C:\Program files...\Arduino folder
And for specific (own made or sketch-depending) include files
#include "MyFile.h"

should be used, which should be located in the same folder as the sketch file.

Yes, that is what I have done but the file I have included as ".." can't be located by the IDE even though it is in the same folder as the main .ino file.

The 'brackets' aren't to do with where the files are, but to do with the order the directories are searched.  For GCC (Visual Studio is different) files in quotes are searched in the directory containing the file that is doing the including then the "preconfigured system directories" where as the <> brackets skip the local folders.  Also it is easier to find compile errors if you include <> first and the "", because the error location of a duplicate definition will be reported against you code and not the system libraries (which you shouldn't be changing)

It seems that my mistake was that I just created new files with another program and simply put them in the project directory. This probably confused the IDE as the files were not included in the build of the project.
Managed to fix this issue by creating new files within the project itself and simply copying my code into them. For VMicro/Visual Studio:

VMicro\Add Code\Add Empty Arduino .h and .cpp files

Changing to double quotes with header files in the same folder worked for me.

source: Stack Exchange

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

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

sort: votes


text:
How can I implement a parking counter with multiple entrances and exit?
I'm relatively new to arduino projects and am trying to solve a real world problem on a parking lot space counter.
My Idea is to have a sensor placed on the entrances and exit to count the total number of cars in the parking lot.
Now there are several codes online but they only implement for 1 entrance.
Scaling for 4 entrances:

Would it be ideal to implement 1 main unit with multiple cables running to each sensors placed on the entrances and exits of the parking lot.

Given that the parking lot is huge:

Is there a wireless way to transmit data from each sensor to the central unit ?

I'm welcoming any recommendations regarding this project.
EDIT:
This is for an actual prototype. I've scoped around the garage to find that I only need  multiple entry exit (2) system for the ground floor. Rest of the two floors have their own 1 entry and exit points.
The entrance and exit are the same point so I was thinking of a bidirectional sensor.

Does 10 feet of width pose a problem for the sensor ?
  Could I instead use two bi-directional sensors placed on either sides of the entry and exit, and then hook them up to the same input in the Arduino ? So incase 1 misses the other one registers.

Edit 2: The parking deck is big enough to hold about 20-25 cars on each of the 3 floors. I don't know the exact measurement though

Besides Sensors could I use a wire on the floor to register when a car crosses over ? Would that be easier?

Theoretically, the sum stays the same. If you count how many cars go in, and how many go out, it won't matter where they go in or go out.

Mind that if it misses one car (or the message gets lost), the counter will become offset. And the system can't really recalibrate itself. You'll probably want to have persistant/failsafe storage, to avoid the system being desynchronised after a power failure.

You could go with wireless, as long as there is bidirectional communication, you can make the counter "acknowledge" incoming or outgoing cars. If the connection is lost, you'll want to retransmit the message until it is accepted. (This may also lead to desynchronisation).

Is it for a prototype or an actual product?

personally, i would just use ESP8266s and have one host an AP that the other sensors connect to

Define "huge"..

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


text:
SPI.H library to control APA102
I am trying to run a strip of APA102 addressable LED's using a Mini pro.
The same strip I can run using a raspberry pi using SPI so I know the Strip works and what data I need to send to get it running.
My current code is as follows and I have striped it back to the bare minimum as I see it.
It all compiles and runs but nothing on the LED strip. The stip only has data and clock that should be connected to the CLK and Data in to connect to the MOSI.
All i want is to be able to send a 32bit value,
I had also tried
uint32_t value = 0xE0ffffff

but again no luck
void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);

  SPI.begin();

  byte start = 0x00;
  SPI.transfer(start);
  SPI.transfer(start);
  SPI.transfer(start);
  SPI.transfer(start);

  SPI.transfer(0xEF);
  SPI.transfer(255);
  SPI.transfer(0);
  SPI.transfer(10);
}

Check here https://www.pololu.com/product/2552/resources. The AdaFruit library may be configured for HW SPI.

I have played with that Libuary and it works fine but I dont see any were you can configure it to use SPI, you can switch to FastGPIO but not SPI.

As I said, check the AdaFruit library https://github.com/adafruit/Adafruit_DotStar.

Apologies I clicked on the first Library, which was not the Adafruit one. Got it now and looking through it. Thank you

OK a fresh look and its all working OK now, I get a strange issue of when the code it uploaded to the Ardunio that random lights on the strip light up. but if I reset the Ardunio and power cycle the strip it all works as expected. Not sure what this behavior is but it only seems to happen after a upload when the serial link is connected. Anyhow thanks for the link, I am not using there library but looking though it I can see how they are doing it and they are doing a similar thing to me, i am writing 32bit vales using spi.transfer(buffer, size) and it seems to be good :)

I guess the random lights when uploading has to do with the SPI signals used while programming the flash. I would recommend disconnecting the LEDs while uploading, power down, connecting the LED and then powering up. Alternatively adding a chip select signal e.g. blocking the clock signal.

Let us continue this discussion in chat.

take a look at the datasheet, compare it vs. your code for any incompliance.
based on my quick reading, your code isn't consistent with the datasheet.
put the communications in a routine would help maintain uniformity.

Where is the issue with my code? the data sheet requires a 32bit start frame of zeros, followed by N number of Control fames which are them selves 32bit (brightness, RED, Green, Blue). once all control frames have been sent you need to send clock cycles to push the commands to the end of the strip (this is not needed for a single LED) . As I say the same frames work fine on a raspberry pi so its not the data structure thats an issue. As for putting it in a routine I will make this a libuary once I have the syntax right.


text:
How do I power an arduino without USB?
I'm working on a project where my arduino talks to another device that uses serial communication. I've connected my USB cable to a USB-to-serial adapter, so it can communicate with the device.
The problem I'm running into is powering the device: if I'm using the USB for serial, I can't use it for power. I have made sure that the device isn't turning on by putting
pinMode(13, OUTPUT);
for (int i = 0; i < 10; i ++) {
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);
}

at the start of the setup function: if it works, it should start by blinking LED 13.
I tried powering it with a 5V power supply through the power jack, next to the USB connector, but that didn't work. Is there something I'm missing? Do I need a different type of power supply?

The documentation is quite explicit about this.

In that case, can you point me to what you're referring to? I don't think I found that page.

https://www.arduino.cc/en/main/arduinoBoardUno

The kind of voltage regulator on the Arduino board will need about 7v to give 5v out to the board. If you trust that your 5v supply is well regulated - at least that it won't exceed 5v, no spikes, etc. - you can connect it directly to the 5v pin on the board edge. Just be aware that you'll be bypassing the protection of the voltage regulator so it will be on you to make sure you're providing the proper polarity, well regulated 5v. Exceed that value and you'll stand a good chance of damaging the board.

my arduino talks to another device that uses serial communication

What other device? You haven't said which Arduino, but Arduinos are generally "devices" which talk to a "controller" (host) which is generally a PC / Mac.
The host has the job of supplying power (via the USB cable) to the device. Thus your Arduino will be powered by the device it is plugged into.
Disregarding this issue for the moment, you can supply regulated 5V power directly to the 5V pin on the Arduino. On the Uno (and many others) this is labelled "5V".
The power jack is to supply 7V to 12V (eg. from a wall-wart) which then goes through the voltage regulator on the Arduino (depending on the model in question).
There is quite a discussion about this on https://www.arduino.cc/en/main/arduinoBoardUno. On that it mentions:

Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

This is true. Directly supplying 5V to the 5V pin bypasses the regulator and also bypasses the reverse-voltage protection diode. However it is possible to do it.

What about the Vin pin?

For a Uno you can see from the reference schematic what happens:

The power jack (on the left) goes into the reverse-voltage protection diode (D1). The other side of that becomes Vin. Then it goes into the 5V voltage regulator (U1). The other side of that becomes the 5V line.
Thus to supply 5V you can provide 5V power to the pin marked 5V. It is probably not ideal, because the voltage regulator may not be designed to have power applied on its "output" side.
There is more circuitry to decide whether to use the USB power or the Vin power (not shown above).

What about the Vin pin?  I'm a noob, so maybe I don't understand that pin well.

The Vin pin bypasses the reverse-protection diode but still goes into the voltage regulator. See my amended answer.

I suppose the Vin pin is to let you "get at" the input voltage. For example, if you supplied 9V to the power jack them 8.3V would be available at Vin, for example to power a motor. (It is less than 9V because of the diode).

From what I can read, Vin can used to power the board - via https://www.modmypi.com/blog/how-do-i-power-my-arduino. Vin can be utilised as a voltage input (instead of using the barrel adaptor or USB). The voltage should within the 9V – 12V, and it is regulated internally by the board to 5V. Vin can also be used as a voltage output, copying the voltage supplied via the barrel adaptor or USB.

I agree it can power the board, providing you supply 7V to 12V to it. The only difference between that and the power jack is that it bypasses the protection diode.

Thanks for clearing that up for me.  It might help the OP too....


text:
How to convert macros for Arduino code?
I have a piece of code I'd like to make Arduino editor friendly. The code is written in C and contains macros the Arduino IDE can't deal with. Is it a good idea to turn those macros into functions?
#define AN221_EXECUTE_Low   cbi(PORTA, PIN0)        //drive EXECUTE low
#define AN221_PORb_High     sbi(PORTA, PIN1)        //drive PORb high
#define AN221_ACTIVATE      bit_is_set(PINA, PIN2)      //sense ACTIVATE high
#define AN221_NO_ERROR      bit_is_set(PINA, PIN3)      //sense ERRb high i.e. no rror
#define AN221_ERRb_Input    outp(0xEB, DDRA)        //make uP drive ERRb
#define AN221_ERRb_Output   outp(0xE3, DDRA)        //make uP sense ERRb

Compiled ok for me - what were you expecting and what actually happened?

Is it a good idea to turn those macros into functions?

it depends.
macros are fast, but lack type checking.
functions offer type checking but incur overhead.
whether one is better than the other depends on your priorities.


text:
I have a problem uploading blink
I am uncertain what a serial monitor does when I try uploading blink.  I get:
problem uploading to board avrdude stk500_recv910 programmer is not responding

Sorry, that has to be a typo: programmer is you?

You are correct: this is a real message. It means you have misswired your serial lines.

Actually it can be any serial port error.

Blink uploads easily, so we'll need more information - Are you using a USB serial cable, for instance?  Have you selected the correct board and port?

You have probably not chosen the right COM port. Try picking a different COM port, if using USB cable.

This answer is rather terse and would have probably been better as a comment. If you could expand your answer, maybe explaining where to change the COM pot and a screenshot, that would be great.


text:
How do I use a photodiode for arduino?
I am doing a project that requires me to program an arduino to sense changes of a steady stream of light due to the scattering of that light. If the phootodiode does change its resistance to the current, then a flap will turn a certain number of degrees. I'm not sure how to operate a photodiode, but know the basics of how it works.
The apparatus is designed to increase the operating life of a solar panel on Mars. When dust from a dust storm collects on its surface, a photodiode will detect the change in light and change its resistance to a current running through it. Then a flap connected to the solar panel will close to cover the solar panel. I'm using Hitec HS-311 Standard servo to rotate  the flap, but I've had some problems operating it.

A photodiode does not change resistance. It generates a tiny current when light strikes it.

http://electronics.stackexchange.com/questions/73732/how-to-use-sfh235-ir-photodiode-correctly

photodioides are rare and relativily expensive; you probably want a light-dependent resistor (cds), which makes for easy analog-input voltage-divider circuits. Or a phototransistor, which works like a regular transistor and can control a digital input easily.

try to use an opamp to create a voltage output from the diode. you can then adc that voltage output from the mcu.

Could you be more specific please?


text:
How to run TCP socket server on Arduino Uno WiFi?
2017-03-23 update
I still don't know why it works so well on Yún. Maybe it has a better antenna? Anyway, I've returned Uno WiFi and got a SparkFun ESP32 Thing. Unfortunately, it has the same problem as Uno WiFi. To fix it I've switched from TCP to UDP. It made a world of difference: servos are very responsive now. UDP is OK for my use case: I can send the state of the whole system in each message and lost messages or messages arriving out of order are not a big problem.
Original question
I want to control servos over WiFi with high precision and low latency. I managed to achieve this using TCP socket communication with Arduino Yún. I want to repeat this with Arduino Uno WiFi, but I can't find example code for socket communication. I connected to the board using telnet but servo output is jerky — as if there was a delay after each servo.write call.
How can I run a TCP socket server on Arduino Uno WiFi in a way that
allows for fast low latency communication?
Longer description
I experimented with controlling servos over WiFi using an Arduino Yún board that I borrowed from a friend. I connected a MG92B servo to pin 9, 5V, and GND. I start a TCP socket server on the Arduino and send angle values from a Python script dozens of times per second. It works smoothly.
Encouraged by this experiment I bought my own Arduino. I chose Arduino Uno WiFi (developer edition) because, unlike Yún, it's compatible with shields. Unfortunately I can't find example code for socket communication. I found an example that uses telnet, so I adapted it and used it with my Python script. Sadly, the servo movement is jerky — as if there was a delay after each servo.write call.
Below is a video showing both boards running two sketches: "no network movement" and "network movement".
Video

Code
I attach all code I used.
Arduino oscillation test with no remote control
I use this code to test that the servo is working correctly.  It works on both Arduino Yún and Arduino Uno WiFi.
#include <Servo.h>

const int servoPin = 9;
Servo servo;

void setup() {
    servo.attach(servoPin);
}

void loop() {
    // configure movement
    int angleMin = 15;
    int angleMax = 165;
    int interval = 30;

    // oscillate between `angle_min` and `angle_max`
    int angle = angleMin;
    for (int i = 0; i < 2; i = (i + 1) % 2) {
        int sign = pow(-1, i);
        for (int j = 0; j < angleMax - angleMin; j += 1) {
            angle += sign;
            servo.write(angle);
            delay(interval);
        }
    }
}

Arduino Uno WiFi reading from telnet
This is jerky.
#include <Servo.h>
#include <UnoWiFiDevEd.h>

const int servoPin = 9;
Servo servo;

void setup() {
    Wifi.begin();
    servo.attach(servoPin);
}

void loop() {
    while (Wifi.available()) {
        servo.write(Wifi.read());
    }
}

Arduino Yún reading from socket
This is smooth.
#include <Bridge.h>
#include <Servo.h>
#include <YunClient.h>
#include <YunServer.h>

// configure
const int port = 5555;
const int servoPin = 9;

// listen on given port
Servo servo;
YunServer server(port);

void setup() {
    // set up servo
    servo.attach(servoPin);

    // start server
    Bridge.begin();
    server.noListenOnLocalhost();
    server.begin();
}

void loop() {
    YunClient client = server.accept();
    byte angle;

    if (client) {
        while (client.connected()) {
            angle = client.read();
            if (angle != 255) {
                servo.write(angle);
            }
        }

        client.stop();
    }

    Serial.println("waiting for client");
    delay(1000);
}

Python writing to socket
This is the network equivalent of the Arduino oscillation test.  Works both with Yún (port 5555) and Uno (port 23).
import socket
from time import sleep

# connect
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.240.1', 5555))  # use 5555 for Yun and 23 for Uno

# configure movement
angle_min = 15
angle_max = 165
interval = 30 / 1e3

# oscillate between `angle_min` and `angle_max`
while True:
    angle = angle_min
    for sign in [1, -1]:
        for _ in range(angle_max - angle_min):
            angle += sign
            client.send(bytearray([angle]))
            sleep(interval)

I suspect these delays are caused by TCP buffering.
For some theory on this sort of thing, perhaps read about Nagle's Algorithm which covers some of the issues with small packet buffering.  It seems reasonable to me that lower-power and/or lower-speed (or even "just different") boards would use more aggressive buffering.
TCP uses all manner of buffering and checks to ensure guaranteed delivery of data (or reported error), whereas UDP does not.
If UDP is working for you, perhaps you may want to include some of your own error tracking in the comms protocol, unless missing the odd packet is not an issue to your control system.


text:
My HM-10 Bluetooth module only returns OK after any AT command
I bought an HM-10 Bluetooth module (BLE 4.0) to use in my school project. Every command that I send to it, it always returns "OK". Can you guys help me?
Here's the code that I am using in my Arduino Uno.
#include <SoftwareSerial.h>

SoftwareSerial BT(10, 11); // RX, TX
String command = ""; // Stores response of bluetooth device

void setup() {
  BT.begin(9600); // HC-06's usual default baud-rate
  Serial.begin(9600);
  Serial.println("Type AT commands!");
}

void loop() {
  if (BT.available()) {
    // Read device output if available.
    while(BT.available()) {
      // While there is more to be read, keep reading.
      delay(10); //Delay added to make thing stable
      char c = BT.read(); //Conduct a serial read
      command += c; //build the string.
    }
    Serial.println(command);
    command = ""; // No repeats
  }
  if (Serial.available()) {
    delay(10);
    BT.write(Serial.read());
  }
}

On the command write you read only one character to send to bluetooth.
Make same than for bluetooth to serial part above:
void loop()
{
if (BT.available()) // Read device output if available.
{
  while(BT.available()) // While there is more to be read, keep reading.
 {
   delay(10); //Delay added to make thing stable
   char c = BT.read(); //Conduct a serial read
   command += c; //build the string.
  }
  Serial.println(command);
  command = ""; // No repeats
}

if (Serial.available())
{
  while(Serial.available())
  {
     delay(10);
     char d = Serial.read(); //Conduct a serial read
     command += d; //build the string.
  }
  BT.write(command);
  command = "";
 }
}

There was a small bug in your code which I've fixed, hope you don't mind. Also worth noting that the delay(10) is a very risky approach to making sure the whole response is read. It would be more reliable to wait for a line ending.


text:
Bredboard board in new release
I had installed the old release (1.0.5) but for some reasons arduino stops working and I upgraded to new version 1.8.2, all works fine but I would like to use the bredboard 8Mhz version in the new release, but the boards system is not compatible with new version. The boards.txt is this:
##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=stk500
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05
atmega328bb.bootloader.path=arduino:atmega
atmega328bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

How to build it to be compatible with news version? Thank you

try adding atmega328bb.build.board=Bredboard as Arduino IDE 3rd party Hardware specification seems to say it's needed for boards on the IDE board menu

I wrote: atmega328bb.build.board=AVR_ATMEGA328BB

I found a solution in this video:
https://www.youtube.com/watch?v=cebMSJrNntI
Adding:
##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.board=AVR_ATMEGA328BB
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

to /hardware/arduino/avr/boards.txt


text:
(Beginner) Blinking led call function
I'm completely new to this world, so probably my question would sound noobish, but here it is:
I'm trying to make a led blinking just for 5 times by calling a "for" cycle inside void loop(). The confirmation of the successful cycle would come from the Serial Monitor which will print "let's star over", and at the end of each blinking cycle, it will print the text "cycle done".
The point is that my code doesn't work, the led remain switched ON and the serial monitor blank. What is wrong with it?
int ledred = 3;
int count = 5;

void setup() {
  digitalWrite(ledred, LOW);
  pinMode(ledred, OUTPUT);

}

void loop() {

    blinkingred(ledred, count);
    Serial.println("let's start over")

}

void blinkingred(int ledred, int count)
{
  for(byte i=0; i == count; i++)
  {
        digitalWrite(ledred, HIGH);
        delay(1000);
        digitalWrite(ledred, LOW);
        delay(1000);
        Serial.println("Cycle done !");
  }
}

There's two things wrong with your sketch - one fatal and one that is more confusing for humans.
First the fatal problem:
for(byte i=0; i == count; i++)

That for loop is never going to do anything.  The way it is written it will loop only while i is equal to count (0 == 5) which it never will. Instead you need to loop while i is less than count:
for(byte i=0; i < count; i++)

The second issue is that you have named your function parameter variables the same as your global variables. While this is syntactically valid (the local variables will override the global ones) it is incredibly confusing for people to follow what is what and should be avoided at all costs.

the simplest would be to unroll your loop and repeat the code 5 times.
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);

hard to get that wrong.


text:
I think I have a bad batch of TPIC6B595
I want drive a large number of LEDS from an Arduino Pro Mini using a number of TPIC6B595. I purchased these on ebay, perhaps a mistake.
Initially I connected two TPIC6B595 as I would connect 74HC595 (with the exception of taking account of how the open drain outputs work) to the SPI pins of an Arduino Mega (my test bench system) and tried sending an alternating bit pattern to the LEDs. No alternating LEDs. I checked SRCLR was Vcc and OE (G) was Gnd. I poked about with my scope (Rigol DS1102D)  and SRCK, RCK and SERIN looked as expected. Suspiciously SEROUT (pin 18) of the first chip was permanently LOW. Note that this is all on a breadboard.
I have used the 74HC595 now many times and from time to time I have made stupid mistakes in wiring/software. These usually stand out on the scope like a sore toe. Not this time.
So I decided to simplify it all and clock some data into a single TPIC6B595 using a simple non-SPI sketch and see if anything comes out of the SEROUT.
Here are the connections to the TPIC6B595 and to the Mega:
1 Not connected,  20  Not connected,
2 Vcc             19  Ground,
3 Arduino pin 12  18  Not connected (except to scope when tested),
4 Not connected   17  Not connected,
5 Not connected   16  Not connected,
6 Not connected   15  Not connected,
7 Not connected   14  Not connected,
8 Vcc             13  Arduino pin 11,
9 Ground          12 Ground (See note 1),
10 Ground         11  Ground.

The chip is bypassed by a 1uF electro across pins 2 and 10. Not ideal but the clock rates are low and it isn't unreliable, it just doesn't work at all.
Note 1: I am not trying to test the transfer between the Shift Register and the output D flip-flops so RCK should be irrelevant. I just want to see data going in to SER IN , coming out on SER OUT.
Here's the Arduino code. It generates a slow clock and an alternating data bit every few clock cycles:
const int ser_clk = 11; // blue
const int ser_in  = 12; // white
byte data, count;

void setup()
{
  pinMode(ser_clk, OUTPUT);
  pinMode(ser_in,OUTPUT);

  digitalWrite(ser_clk, LOW);
  digitalWrite(ser_in, LOW);

  count = data = 0;
}

void loop()
{
  digitalWrite(ser_clk, HIGH);
  delay(1);
  digitalWrite(ser_clk, LOW);
  delay(1);

  count++;
  if (count >= 3)
     {
       count = 0;
       if (data == 0)
          {
            data = 1;
            digitalWrite(ser_in, HIGH);
          }
       else
          {
            data = 0;
            digitalWrite(ser_in, LOW);
          }
     }
}

Here's a screenshot of the wave-forms (photo of scope - sorry can't make UltraScope work):

The cyan trace is the "clock" from pin 11 of the Arduino feeding pin 13 (SRCLK) of the TPIC6B595. The yellow trace is the data from pin 12 of the Arduino feeding pin3 (SER IN) of the TPIC6B595. I am only looking to get the same data pattern out of SEROUT, pin 18 of the TPIC6B595 and this should do it. The clock is as slow as a wet week (see cursor) and even if I have bad set up and hold times and the wrong transitions the data is held for enough cycles for something to make it through surely?? Pin 18 is persistently and forever low. No screenshot - seems to be no point.
I bought several of these TPIC6B595. Tried 3 so far. All the same. Now I might have killed them with static. I am not using wrist straps, but I also don't believe I could have killed 3 of them.
As improbable as that is I think they are dead or duds, or is there something else wrong that is so obvious I cannot see it?
Regards, Fred.

so RCK should be irrelevant. you probably want to read the datasheet to be sure of that, :)

Shifting should still work even without latching. This is to allow daisy-chaining multiple devices and latching them only once all the devices have been charged.

Have you tried substituting them with a normal '595 and seeing if the desired behavior results?

fwiw all the "too cheap" components i've bought from ebay have worked fine...

Thanks to all those who responded. I have a double embarrassment here as I have the answer. Firstly if you can answer your own question there is an argument it should never have been posted, more thought needed first. Sorry everyone. Secondly when the cause is ignoring well known good practice then it is even worse.
So when tying a pin to Vcc (in this case SRCLR) it is known bad practice to hard couple it to Vcc. A pull-up resistor is a much better method. In this case suitable pull-ups were in the next room and I could not be bothered so I just jumpered SRCLR to Vcc. After I had written the post I was staring at the breadboard and thought - I should not have really done that replaced the jumper with a 10K pullup to Vcc. Instantly the SEROUT pin of the TPIC6B595 came to life as it should have. Now I have taken this short-cut before and gotten away with it. But it seems not this time.
Subsequently I have a one chip version of the alternating LEDS running with the SPI interface.
As to the suggestion by dannyf about the datasheet, there is no doubt the datasheet is a good place place to go. Prior to developing my test sketch as per my original post I consulted the datasheet and if you look in Section 8, page 11 of the TI datasheet revised June 2015 there is a Functional Block Diagram. This block diagram clearly shows that the RCK signal is concerned only with the C2 column of D flip-flops which take the output from the shift register and latch it to the output FET through the output enable logic. RCK is independent of the process to clock data through the shift register, controlled by SRCLK. You will note my test did not exercise the transfer function it was just interested in getting data into the shift register and out again.
I stand by my assertion that for the serial shift register function and checking SEROUT, RCK is not relevant. Once you want to start data transfers from the shift register to the output register then it is different matter. No disagreement there. Having that timing wrong will lead to a mess of corrupted data.
Thanks again to all. This is solved and is a lesson to abide by good practice always.
Regards, Fred.

so I just jumpered SRCLR to Vcc. there may be something else at play. wiring srclr to vcc is perfectly acceptable -> the datasheet shows it, and the input block shows a serial resistor so in effect you have a pull-up resistor. puzzling to say the least.


text:
GSM 900A modem not responding to AT commands
I am using GSM 900A modem which requires 5V Supply. I am connecting it to Arduino UNO. I am giving supply to modem by arduino 5V and GND pin. I am connecting RXD pin to TX(pin 1) of arduino TXD pin to RX(pin 0) of arduino and GND to GND of arduino i.e. pin 14. I am running the basic example codes but GSM is not responding. I have also tried other softwares like Putty but I am unable to write any AT command Please help me. When I tested the modem using this code:
/*

 This example tests to see if the modem of the
 GSM shield is working correctly. You do not need
 a SIM card for this example.

 Circuit:
 * GSM shield attached

 Created 12 Jun 2012
 by David del Peral
 modified 21 Nov 2012
 by Tom Igoe

 http://www.arduino.cc/en/Tutorial/GSMToolsTestModem

 This sample code is part of the public domain

 */

// libraries
#include <GSM.h>

// modem verification object
GSMModem modem;

// IMEI variable
String IMEI = "";

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start modem test (reset and check response)
  Serial.print("Starting modem test...");
  if (modem.begin()) {
    Serial.println("modem.begin() succeeded");
  } else {
    Serial.println("ERROR, no modem answer.");
  }
}

void loop() {
  // get modem IMEI
  Serial.print("Checking IMEI...");
  IMEI = modem.getIMEI();

  // check IMEI response
  if (IMEI != NULL) {
    // show IMEI in serial monitor
    Serial.println("Modem's IMEI: " + IMEI);
    // reset modem to check booting:
    Serial.print("Resetting modem...");
    modem.begin();
    // get and check IMEI one more time
    if (modem.getIMEI() != NULL) {
      Serial.println("Modem is functoning properly");
    } else {
      Serial.println("Error: getIMEI() failed after modem.begin()");
    }
  } else {
    Serial.println("Error: Could not get IMEI");
  }
  // do nothing:
  while (true);
}

I am getting this output on Serial Monitor for 9600 baud rate:

Starting modem test...ERROR, no modem answer.
Checking IMEI...Modem's IMEI: 0
Resetting modem...Modem is functioning properly

The modem library does not communicate on pins 0 and 1. Check the reference library and tutorial. It should be pins 2 (RX) and 3 (TX). Reset is pin 7. The configuration may be found in GSM3IO.h. https://github.com/arduino/Arduino/blob/master/libraries/GSM/src/GSM3IO.h. See also https://www.arduino.cc/en/Main/ArduinoGSMShield

Thats for GSM Shield by arduino but I am working with SIM900A

Yes, but the library is using pins 2 and 3.

But still its not working

Mikael Patel pls help on this issue

Check the power supply. Measure the voltage when the modem is connected. Does the voltage drop?

If you connect a GSM modem to the Arduino's Hardware Serial pins (1/0) then you cannot also use those pins to communicate with a host PC.
Your question is tagged "Arduino Uno" therefore the status reporting messages to the PC will be sent over these pins, and become hopellesly confused with the traffic to the GSM modem.
You must place the modem on pins distinct from the PC interface - either using a software serial interface on different pins of an Uno, using a Leonardo-type board where the PC interface does not involve the hardware UART pins, or by using a board with multiple hardware UARTs.

This answer may be totally misleading because I can't find a "GSM 900A" but I can find lots of "SIM900A GSM" results.  One thing I did notice is they require a 1A+ supply to cater for transmissions so I think running of an Arduino may mean you are not giving it enough power, you should use a 1.5A supply and make sure the grounds are connected.


text:
Not showing output when using pins other than 10 and 11 with SoftwareSerial library on Arduino Mega
I am  trying to run below code on Arduino Mega using GPS module(skg13 bl). It is working fine with pins 10, 11 as rx, tx in the SoftwareSerial but it is not showing output when other pins such as 4, 5 are used.
I further have to send this data through RF module using virtual wire library.
Code is as follows:

#include <SoftwareSerial.h>
#include <TinyGPS++.h>
TinyGPSPlus gps;

SoftwareSerial mySerial(10, 11);

void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);
  Serial.println("GPS start");
}

void loop() {
  while (mySerial.available()) {
    gps.encode(mySerial.read());
  }

  if (gps.location.isUpdated()) {
    double a = gps.location.lat();
    Serial.println(a);
    Serial.println(gps.location.lat(), 6);
    double b = gps.location.lng();
    Serial.println(gps.location.lng(), 6);
  }
}

Thanks in advance!!

Thanks for your help that problem is solved but another problem is arise working with virtual wire library it is not showing gps data code is as :

From https://www.arduino.cc/en/Reference/softwareSerial:

Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

So you will need to use one of the pins from that list for RX, pin 4 or 5 will not work.


text:
Errors when compiling the GSM SMS receive example from the Arduino IDE
I want to receive SMS and check whether the character is 'y' or 'n'. If it is 'y', set a pin to high so that a light glows. I thought I could use the example code given in the Arduino IDE for receiving SMS, but when I compile (without connecting the board, using ctrl+r) it shows the following errors:
Arduino: 1.8.1 (Windows 7), Board: "Arduino/Genuino Uno"

In file included from F:\Arduino\libraries\GSM\src/GSM.h:46:0,
                 from F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino:21:
F:\Arduino\libraries\GSM\src/GSM3ShieldV1BandManagement.h:49:125: warning: 'typedef' was ignored in this declaration
 typedef enum GSM3GSMBand {UNDEFINED, EGSM_MODE, DCS_MODE, PCS_MODE, EGSM_DCS_MODE, GSM850_PCS_MODE, GSM850_EGSM_DCS_PCS_MODE};
                                                                                ^
F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino: In function 'void setup()':
F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino:47:34: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
     if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
                                  ^
Sketch uses 13322 bytes (41%) of program storage space. Maximum is 32256 bytes.
Global variables use 996 bytes (48%) of dynamic memory, leaving 1052 bytes for local variables. Maximum is 2048 bytes.
An error occurred while uploading the sketch
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Please help me rectify the error.
I use a SIM900 GSM board. I connect the tx and rx of the GSM board to the Arduino's tx and rx.

Those are warnings, not errors.  The code should have compiled and be able to flash.

thanks a lot man ... it means a lot to me. i am new to arduino. i will flash it and will let you know :) thanks for your help

Yes they are just warning, but don't assume all warnings should be ignored.  In this case they can be ignored, but you may as well fix them to stop them cluttering the output.
The first one can be fixed by removing the word typedef.
The second one needs you to add .c_str() on the end of the string variable.  Sometimes 'string' classes don't store the data in the same way as a char array.

tx and rx of arduino are connected to the rx and tx of gsm board. ground is also connected. is the problem with the code or the connections?

I modified the example according to my needs. so when i send 'y' to the gsm , i hear that beep sound indicating that message has been received.
But there is no reaction from the arduino. The modified code snippet is as follows:
if (sms.peek() == '#') {
Serial.println("Discarded SMS");
sms.flush();
}
// Read message bytes and print them
while (c = sms.read()) {
Serial.print(c);
if(c=='y'){
digitalWrite(LED_BUILTIN,HIGH);
}
else
digitalWrite(LED_BUILTIN,LOW);
}


text:
Error while updating ThingSpeak using SIM808
im trying to update ThingSpeak from a SIM808 but I'm getting a network error. Please check below and let me know if there is anything wrong in my methodology.
I'm using terminal.exe to send commands via RS232.
AT
OK
AT+CREG?
+CREG: 0,5 //connected in roaming
AT+SAPBR=3,1,"Contype","GPRS"
OK
AT+SAPBR=3,1,"APN","www" //VODAFONE INDIA "www" is APN (as per the operator)
OK
AT+SAPBR=3,1,"USER","" //blank (as per the operator)
OK
AT+SAPBR=3,1,"PWD","" //blank  (as per the operator)
AT+SAPBR=1,1
OK
AT+HTTPINIT
OK
AT+HTTPPARA="CID","1"
OK
AT+HTTPARA="URL","https://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE"
OK
AT+HTTPACTION=0
+HTTPACTION: 0,603,0

Note: while I'm typing in the browser url box, https://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE, I can update my field. I can make calls, send SMS. I have an internet pack.
Please help.

You're using HTTP commands to perform an HTTPS request. You need to use the HTTPS commands instead. Read the SIM808 manual for the right commands.

https://stackoverflow.com/a/69513173/8119511

It worked with changing AT+HTTPARA="URL","http://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE" (from https:// to http://)

You have to send this command: AT+HTTPSSL=1


text:
Arduino Uno not including two header files at the same time
I have an Arduino Uno and I am trying to control a stepper motor with it. I also have an RF transmitter and receiver (433MHZ). I need to transmit data about motor status.
For RF I am following this page. Individually both are working great. I am able to send data from one Arduino (TX) to another (RX). And also I am able to control the motor. But when I am merging these projects, their header files are giving an error.
For RF, I need to include #include <RH_ASK.h> and for the motor I need include #include <Servo.h>. When I am including these headers files, they are giving me this error:
Arduino: 1.8.1 (Windows 10), Board: "Arduino/Genuino Uno"

libraries\RadioHead\RH_ASK.cpp.o (symbol from plugin): In function `RH_ASK::maxMessageLength()':

(.text+0x0): multiple definition of `__vector_11'

libraries\Servo\avr\Servo.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

I do not know what's wrong here. Can anyone please help me?

I found the solution on internet. These both libraries cannot be used at the same time. To do it, I downloaded the servotimer2 library but its not even compiling.

That sounds like a nice solution.

Please, accept @Jot's answer to close this question.

First of all, that page has a link to an old version of the RadioHead library.
This is a link to RadioHead: www.airspayce.com/mikem/arduino/RadioHead. You will find the newest library on that page.
The Servo library uses TIMER1.
The RadioHead in RH_ASK mode uses TIMER1.
Both use the same interrupt of TIMER1. That is what the compiler is trying to tell you with: "multiple definition of _vector_11".
You could move one of them to TIMER2.
There are alternative Servo libraries that use TIMER2.
The RadioHead can set a define for TIMER2. The explanation is in the library files in RH_ASK.h, you have to set "#define RH_ASK_ARDUINO_USE_TIMER2" in RH_ASK.cpp.
Why are you using the Servo library for a stepper motor ?

It is telling you that interrupt vector 11 is being defined multiple times. Such definitions should be done in the source file, not in the header file.


text:
Using Youtube API with ESP8266 = redirection problems
I am using ESP8266 programmed from Arduino to get data from the Google Youtube API. API, of course, works great in a browser using URL:
https://www.googleapis.com/youtube/v3/channels?part=statistics&id=CHANNEL-ID&key=GOOGLE-API-KEY

The problem is that "gooogleapis.com" is not the location where from I would receive the answer to my HTTPS request, it comes from a different location. When above URL is entered, it is being redirected and request answer comes from another location.
So what happens on ESP8266 when I try to open that address(of course, with added proper channel ID and google key) is following:
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=UTF-8
Content-Length: 1580
Date: Sun, 12 Mar 2017 14:40:18 GMT
Alt-Svc: quic=":443"; ma=2592000; v="36,35,34"
Connection: close

<!DOCTYPE html>

  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 404 (Not Found)!!1</title>

404. That’s an error.

The requested URL /youtube/v3/channels was not found on this server.  That���s all we know.
Done.

Which is the Google error page(you seen it!). This is my Arduino code:
#include "ESP8266WiFi.h"
#include <WiFiClientSecure.h>

const char* ssid     = "SSID";  // WiFi network name
const char* password = "pass"; // WiFi pass

const char* host = "googleapis.com"; // page I am trying to load
const char* fingerprint = "22 37 4D 58 43 F4 A1 24 12 71 2B 74 7A FC 36 FC 24 A0 F0 9D";

String ch_id = "CHANNEL ID";
String api_key = "API KEY";

void setup() {
  Serial.begin(115200);
  delay(10);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("Connected to WiFi! Local IP address is: ");
  Serial.println(WiFi.localIP());

  WiFiClientSecure client;
  if (!client.connect(host, 443))
  {
    Serial.println("I am unable to connect to that page.");
    return;
  }

  if (client.verify(fingerprint, host)) {
    Serial.println("certificate OK");
  } else {
    Serial.println("certificate NOT OK");
  }

  String url = "/youtube/v3/channels?part=statistics&id=" + ch_id + "&key=" + api_key;

  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);

  while (client.available()) {
    String linija = client.readStringUntil('\r');
    Serial.print(linija);
  }

  Serial.println("Done.");
}

void loop() {
}

How to find out to which site I am redirected?
How to read that from ESP8266 and redirect the same data to new site?

404 is not a redirect. You should get a 302 or 301. In that case there will also be a Location: header that contains the new URL.

In your browser you used www.googleapis.com, but in your code you used googleapis.com.
https://googleapis.com/youtube/v3/channels?part=statistics&id=CHANNEL-ID&key=GOOGLE-API-KEY

returns a 404 page.
Add www. to your host in code.

Perfect! Can't believe I missed something so trivial. Thank you very much - works now.


text:
Why sensor acts erratically?
I am trying to connect an ADXL355 digital sensor to an Arduino. The wiring and the code I think are OK because the system returns the correct values sometimes and partly correct answers mostly. The code checks the device register, and the correct data is printed to serial most of the time. The code also checks for temperature but only returns the correct value occasionally. The values are polled every few seconds. The values are correct all of the time if they are correct the first time after restart but never if they are incorrect on restart. I thought it might help to unplug the sensor when uploading the program or powering up the Arduino through USB to the computer but there is no clear pattern.
It is not a defective sensor because I have 2 that behave the same way. What could be the problem? Is this a problem with the Arduino?

I only wire VDD, VDDIO, ground,chip select, sclk, MOSI and MISO.
code:
#include <SPI.h>

    const int ID = 0x00;
    const int FIFO = 0x11;
    const int TEMP = 0x06;
    const int TEMP1 = 0x07;
    const byte FIFO_WATERMARK = 0x29;
    const int chipSelectPin = 7;

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

        SPI.begin();

        pinMode(dataReadyPin, INPUT);
        pinMode(chipSelectPin, OUTPUT);

        // writing 0 to to enable sensor
        writeRegister(0x2D, 0x00);

        delay(100);

        Serial.println(readRegister(ID));
        Serial.println(readRegister(FIFO_WATERMARK));
    }

    void loop() {
        int temp = (readRegister(TEMP)); // << 8) | (readRegister(TEMP1))) ;
        temp = (temp<<8)|(readRegister(TEMP1));
        Serial.println(((1852 - temp)/9.05) + 19.21);
        Serial.println(readRegister(ID));

        delay(1000);
    }

    byte readRegister (byte thisRegister){
        byte inByte = 0 ;
        SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer((thisRegister << 1) | 1);
        inByte = SPI.transfer(0x00);
        digitalWrite(chipSelectPin, HIGH);
        return inByte;
    }
    void writeRegister (byte thisRegister, byte value){
        SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer(thisRegister << 1);
        SPI.transfer(value);
        digitalWrite(chipSelectPin, HIGH);
    }

Some one suggested it might be signal bounce on the SPI and the clock rate was set to 500kHz but it didn't work.
Update:
Not long ago, the correct device ID would be read consistently (173 for 0xAD); now that returns 0. The temperature would either return 0 from the register or changing values between -1 and -5 that may have been wrongly calibrated temperature. But sometimes the correct temperature would return. Now it also only returns 0 from the registers.

Could you show some of the output you get?

@Gerben I updated the post with the outputs.

Try adding a bit of delay after setting the ChipSelect pin low.

@Gerben It didn't work, outputs are 0.

This is a poor product, look at this: that describes exactly the problems you (and me) are experiencing. Correct me if you've found any solutions so far.
edit
Try looking at description of regster 0x2f in datasheet and to this question.
I think that the first problem you describe can be solved this way, the second behaviour sounds like you fried the device.

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

Per your post looks like you have not wired any grounds. Consider wiring Analog and Digital grounds.

Here are excerpts from the datasheet

Thank you. I forgot to mention that I wired the ground. But I did not the VSSIO. Someone also suggested it was because the sensor runs on 3.3 V and the Arduino on 5.

Regardless of 3.3V or 5V GND is 0V. DGND and AGND are internally isolated. So erratic behavior can be explained due to poor grounding. Good luck. BTW don't cross post questions.

It could also be caused by insufficient or unregulated power supply.

@Mahendra Gunawardena 6 The VSSIO is tied to the VSS through the P1 6 pin header

Attaching a small ceramic or electrolytic capacitor to the power rail /might/ help to reduce the issue.


text:
I2C MCP4725 DAC connection speed
I'm trying to use the MCP4725 DAC from Adafruit (https://www.adafruit.com/product/935) to output some waveforms over a frequency range up to about 50kHz. At the moment, I'm simply sending values to the DAC via the Wire library and through the DAC's onboard library. It appears that the values are only being sent at 7kHz. Is this due to the added weight of the libraries I'm using? Is there some way I can increase the transmission speed?

Consider using a Teensy 3 or a Due, with 2 built-in 12-bit DACs each

You cannot get 50kYz from a DAC running on I2C on an Arduino.
The maximum rate for I2C (if you select fast mode) is 400kbps. Setting the DAC takes three bytes plus start/stop/ack bits (total 29 bits).
At 400kbps that equates to (400000/29) 13793 settings per second.
Add to that the time taken to actually create and process the data, running the instructions to do everything, you can expect about half that - which is the 7kHz you're getting.
To get 50kHz from a DAC you really need a CODEC and run something like I2S, which you are never going to do on an Arduino.


text:
Serial read in ESP8266-01 not working
I am new to programming. kindly bear with me. I am trying to use ESP8266-01 device for serial read and write application. Before writing the full program for my application, i wanted to test how it functions. I programmed the ESP8266-01 device to read the data from its Rx pin and write it to Tx pin. I used a standard USB-TTL cable to send and receive data from PC using Hterm. The ESP device does not read the data available at the Rx pin. what am i missing ?. Also kindly help me in understanding the difference between serial.println and serial.write with respect to ESP8266-01 device. As per the program if i check the data from the Tx pin of the ESP8266 device, i get only "No data received". I am using arduino IDE 1.6.11. Kindly provide some guidance
regards
Sriniketh
#include <ESP8266WiFi.h>

void setup() {

Serial.begin(9600);
}

void loop()
{
  byte serin=0;
  if (Serial.available()>0)
  {
    serin=Serial.read();
    delay(100);
    Serial.println(serin);
    delay(100);
    Serial.write(serin);
  }
  else
  {
    Serial.println("No data received");
    delay(5000);
  }

}

You might mean bear rather than bare in “kindly bare with me” (which means,  “kindly take off clothes together”)

can you successfully flash the arduino sketch over that serial connection?

A circuit diagram or photo would help, but I would guess you have taken the lead from the PC that is marked Rx and connected to the pin on the ESP marked Rx.  That's the wrong thing to do.  Firstly the PC will use 5V and the ESP uses 3.3V, so you need a little board called a level shifter something like this 2 channel level shifter.  This will let a 3.3v device talk to a 5V device.  Some ESP boards are 5V tolerant, but I don't know what you have so ...
Then when you "talk" over serial you need to cross the Tx and Rx between the two devices, so the can 'hear' each other
 PC - Tx  ---> Rx - ESP
 PC - Rx <---- Tx - ESP

(Lots of other level shifters are available and a lot are cheaper than the example shown, a lot cheaper!)


text:
Better cycling through the RGB colors
I have been trying to achieve a way to tap into the 16 million colors RGB provides for this LED strip. I thought of using LEDS.setBrightness(); but I have not been successful in my attempts. I have read the documentation on color fading, but I have not been able to write this to my Arduino Leonardo. Here is my code below, which cycles through the initial rainbow of 0-255. I was wondering how to get more than 0-255 if not all the colors.
#include <FastLED.h>

#define LED_COUNT 60
#define LED_OUT       13
#define BUTTON_IN     10
#define ANALOG_INPUT  A9
#define EXTRA_PIN_A    7
#define EXTRA_PIN_B   11

struct CRGB leds[LED_COUNT];
int wait_time = 5;

void setup() {
  Serial.begin(57600);
  LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
  LEDS.show();
}

void loop() {
  //start from red
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = 255;
    int g = 0;
    int b = colorStep;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }

  //into blue
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = colorStep;
    int g = 0;
    int b = 255;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //start from blue
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = 0;
    int g = colorStep;
    int b = 255;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //into green
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = 0;
    int g = 255;
    int b = colorStep;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //start from green
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = colorStep;
    int g = 255;
    int b = 0;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //into yellow
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = 255;
    int g = colorStep;
    int b = 0;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
} //end main loop

but RGB's 0-255 levels is all the colors, what are you trying to do?

that's correct, but if you follow my loops you'll see that I am only doing the combinations 0 < 255 and 0 > 255 for rgb. I.E. 0, 0, 255 // blue or 255, 0, 0 //red which is why i said the initial rainbow. there are no combinations of let's say 128, 64, 250.

Ahh, i see; then just nest your loops...

tried that like w/ @6v6gt answer. unfortunately, it does not cycle thru the LEDs properly.  There seems to be a iteration problem with the first nested loop (not the code provided) just the way the FastLED class handles the nesting?

I think it's worth noting that the three 255 values for RGB colour space is just one way to encode the 255^3 (16,581,375) colours. These include each and every brightness level too.
If you are trying to get a rainbow effect, you may have more success or find it easier to use a HSL or HSV colour space.
HSV uses Hue, Saturation and Value instead of RGB. FastLED has optimized it's implementation of HSV to use a 0-255 addressing for Hue (instead of 360), keeping it fast for animations run on microcontrollers:
https://github.com/FastLED/FastLED/wiki/FastLED-HSV-Colors

Re-using fastled is indeed a very good option! You'll overcome reinventing the wheel, and have a more efficiënt wheel ;p

I've included a simple sketch that will cycle a single RGB led using the sine fade technique
// Cycle a single RGB led using the sine fade technique
// For common cathode led

const uint8_t lights[360]={
  0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 15, 17, 18, 20, 22, 24, 26, 28, 30, 32, 35, 37, 39,
 42, 44, 47, 49, 52, 55, 58, 60, 63, 66, 69, 72, 75, 78, 81, 85, 88, 91, 94, 97, 101, 104, 107, 111, 114, 117, 121, 124, 127, 131, 134, 137,
141, 144, 147, 150, 154, 157, 160, 163, 167, 170, 173, 176, 179, 182, 185, 188, 191, 194, 197, 200, 202, 205, 208, 210, 213, 215, 217, 220, 222, 224, 226, 229,
231, 232, 234, 236, 238, 239, 241, 242, 244, 245, 246, 248, 249, 250, 251, 251, 252, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255, 254, 254, 253, 253,
252, 251, 251, 250, 249, 248, 246, 245, 244, 242, 241, 239, 238, 236, 234, 232, 231, 229, 226, 224, 222, 220, 217, 215, 213, 210, 208, 205, 202, 200, 197, 194,
191, 188, 185, 182, 179, 176, 173, 170, 167, 163, 160, 157, 154, 150, 147, 144, 141, 137, 134, 131, 127, 124, 121, 117, 114, 111, 107, 104, 101, 97, 94, 91,
 88, 85, 81, 78, 75, 72, 69, 66, 63, 60, 58, 55, 52, 49, 47, 44, 42, 39, 37, 35, 32, 30, 28, 26, 24, 22, 20, 18, 17, 15, 13, 12,
 11, 9, 8, 7, 6, 5, 4, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

const byte redpin = 3;
const byte greenpin = 5;
const byte bluepin = 6;
int loopdelay = 5000; // ms
int displaylength = 50; // ms

boolean showiterations = false;

//_______________________________
void setup() {
      Serial.begin(9600);
}

void loop() {
for (int k=0; k<360; k++)
{
    if (showiterations) {
    Serial.print(k);
    Serial.print(F(","));
    }
analogWrite(redpin, lights[(k+120)%360]);
analogWrite(greenpin, lights[k]);
analogWrite(bluepin, lights[(k+240)%360]);
delay(displaylength);
}
if (showiterations) {
Serial.println("  ");
}
delay(loopdelay);
}

This sketch is derived from an Instructables posting entitled "How to Make Proper Rainbow and Random Colors With the RGB Color Model", http://www.instructables.com/id/How-to-Make-Proper-Rainbow-and-Random-Colors-With-/
It additionally provides information and rationale behind different techniques for cycling colours.

If you are trying to stagger the colours along the strip whilst creating a rainbow effect,  I have another sketch [from Adafruit, I believe] that will do this.  I've used it effectively with different Neopixel ring configurations.  The sketch demonstrates a number of different techniques. I have currently commented out the invocations of all but the theaterChaseRainbow, but you may wish to explore them all.
#include <Adafruit_NeoPixel.h>
// following atatement should be wrapped with an ifdef for __AVR__, but this facility botches it up.
// As it is, formatting for the sketch is not quite right, and I do not have a solution for that.
  #include <avr/power.h>

const  byte PIN = 7;

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
// Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800)`
Adafruit_NeoPixel strip = Adafruit_NeoPixel(16, 6, NEO_GRB + NEO_KHZ800);

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.  Avoid connecting
// on a live circuit...if you must, connect GND first.

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code

  strip.begin();
   colorWipe(strip.Color(0, 0, 0), 50); // blank
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  // Some example procedures showing how to display to the pixels:
//  colorWipe(strip.Color(255, 0, 0), 50); // Red
//  colorWipe(strip.Color(0, 255, 0), 50); // Green
//  colorWipe(strip.Color(0, 0, 255), 50); // Blue
//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
  // Send a theater pixel chase in...
//  theaterChase(strip.Color(127, 127, 127), 50); // White
//  theaterChase(strip.Color(127, 0, 0), 50); // Red
//  theaterChase(strip.Color(0, 0, 127), 50); // Blue

//  rainbow(20);
//  delay(50000);
//  colorWipe(strip.Color(0, 0, 0), 50); // blank
//  rainbowCycle(10);
//  delay(5000);
//    colorWipe(strip.Color(0, 0, 0), 50); // blank
//   delay(5000);
  theaterChaseRainbow(50);
//  delay(5000);
//    colorWipe(strip.Color(0, 0, 0), 50); // blank
//   delay(5000);
}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait) {
  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

Although your answer is 100% correct, it might also become 100% useless
if that link is moved, changed, merged into another one or the main site
just disappears... :( Therefore, please [edit] your answer, and copy
the relevant steps from the link into your answer, thereby guaranteeing
your answer for 100% of the lifetime of this site! ;) You can always
leave the link in at the bottom of your answer as a source for your
material...

@Avamander, suggestion taken, pls re-evaluate.

You can make a smooth transition/sliding rainbow effect by using a sine wave lookup table, then phase shifting green and blue by 120 and 240 degrees.
#define RED 9
#define GREEN 10
#define BLUE 11

uint8_t sins[360] = {
  127,129,131,134,136,138,140,143,145,147,149,151,154,156,158,160,162,164,166,169,171,173,175,177,179,181,183,185,187,189,191,193,195,196,198,200,
  202,204,205,207,209,211,212,214,216,217,219,220,222,223,225,226,227,229,230,231,233,234,235,236,237,239,240,241,242,243,243,244,245,246,247,248,
  248,249,250,250,251,251,252,252,253,253,253,254,254,254,254,254,254,254,255,254,254,254,254,254,254,254,253,253,253,252,252,251,251,250,250,249,
  248,248,247,246,245,244,243,243,242,241,240,239,237,236,235,234,233,231,230,229,227,226,225,223,222,220,219,217,216,214,212,211,209,207,205,204,
  202,200,198,196,195,193,191,189,187,185,183,181,179,177,175,173,171,169,166,164,162,160,158,156,154,151,149,147,145,143,140,138,136,134,131,129,
  127,125,123,120,118,116,114,111,109,107,105,103,100,98,96,94,92,90,88,85,83,81,79,77,75,73,71,69,67,65,63,61,59,58,56,54,
  52,50,49,47,45,43,42,40,38,37,35,34,32,31,29,28,27,25,24,23,21,20,19,18,17,15,14,13,12,11,11,10,9,8,7,6,
  6,5,4,4,3,3,2,2,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,3,4,4,5,
  6,6,7,8,9,10,11,11,12,13,14,15,17,18,19,20,21,23,24,25,27,28,29,31,32,34,35,37,38,40,42,43,45,47,49,50,
  52,54,56,58,59,61,63,65,67,69,71,73,75,77,79,81,83,85,88,90,92,94,96,98,100,103,105,107,109,111,114,116,118,120,123,125
};

void setup() {
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
}

void loop() {
  for (int i = 0; i < 360; ++i)
  {
    analogWrite(RED, sins[i]);
    analogWrite(GREEN, sins[(i+120)%360]);
    analogWrite(BLUE, sins[(i+240)%360]);
    delay(2);
  }
}

If you want to display every one of the about 16 million possible colours, you will have to nest your for loops like in this example:
x = 1 ;  // only for testing
for ( int redx = 0 ; redx <= 255 ; redx ++ ) {
    for ( int greenx = 0 ; greenx <= 255 ; greenx ++ ) {
        for ( int bluex = 0 ; bluex <= 255 ; bluex ++ ) {
             leds[ x ] = CRGB(redx,greenx,bluex);
             delay(wait_time);
             LEDS.show();
        }
    }
}

An alternative could be to use HSB or HSV instead of RGB, this way you can increase the hue over time to get the rainbow effect.

You should consider making it non-blocking :)
loop(){
   //if(millis() > previous+100){//uncomment this part to only do a step of the rainbow effect every 100ms
   rainbowEffect();
   //previous = millis();
   //}

   //you can do other stuff, like check a buttons' state here.
   //using the same structure as above, you can choose to give it a higher or lower priority.
}

unsigned char r,g,b;
void rainbowEffect(){
   if(r>254){
      r=0;
      g++;
   }
   if(g>254){
      g=0;
      b++;
   }
   if(b>254){
      b=0;
   }
   r++;
   ledStrip.set(r,g,b);
}

I think @Mazaryk was correct, HSV is the way to go for this.  RGB's 16+ million colors include brightness, and some of them just won't display on the strip, so I found a way to at least better fade thru:
int thissat = 255;           //- LOOPS DELAY VAR
int idex = 0;                //-LED INDEX
int ihue = 0;                //-hue (0-255)

void rainbow_fade() {
    ihue++;
    if (ihue > 255) {ihue = 0;}
    for(int idex = 0 ; idex < LED_COUNT; idex++ ) {
      leds[idex] = CHSV(ihue, thissat, 255);
    }
    LEDS.show();
    delay(wait_time);
}

You could take advantage that the rgb color could be represented in a unsigned long. And use a counter.
But have patience looping through 16 mio colors with 1ms at iteration take some time :-). (around 4-5 hours:  16581375/(1000[ms] * 60[m] * 60[h]) = 4,6 )
void loopThrougAllColors(){
  // The trick here is to use a unsigned long value as the color representation.
  // Each byte represent a color (except the first)
  //          none, R  G  B
  //          0x00 00 00 00
  // Note: static means it is a global variable - but only seen in thisfunction.
  static unsigned long ledColor = 0;
  static int ledIndex = 0;

  ledColor++;
  ledColor &= 0x00FFFFFF; /* Overflow preventing (instead of if sentence checking the boundaries). */

  leds[0] = ledColor;

  FastLED.show();
  FastLED.delay(1);
  //delay(10);
}


text:
HELP with, I think, are wrongly placed Interrupts
I am still struggling to get this sketch functional. The problem seems to lie with the interrupts, and relying on them to turn on and off the PIRtrigger when needed. Everything else seems to be OK. This is a slightly modified sketch from what I had uploaded earlier, with some changes that I thought would fix the problem. In general, a "correct" PIN disables the alarm from firing as it sets the "away" flag to "false", which works. An "incorrect" PIN sets "away" to "true" which, when a trigger is activated via an Interrupt, sounds the alarm. The program should then go to readKeypad for further function, which it appears to do. The following shows the result after an incorrect PIN:
Key_input[0] = #
@ checkPIN
@ incorrect PIN
away=1 PIRtrigger=0
at Alarm
after alarm

The trigger then doesn't seem to get activated. Can anyone HELP!? Thanks.
///////////////////////// initialize & includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;

//To change pins for Software Serial, use the two lines in GSM.cpp.
int PIR_SensorPin = 2;
int LED_OutPin = 11; //green
int Alarm_OutPin = 12; //red
int alarm_count;
volatile boolean PIRtrigger = false;
boolean away = false;
const byte interruptPin = 2;
int z = 0;
int i = 0;
int timeout = 10000;
unsigned long time = millis();

//////////////////////////// setup keyPad //////////////////////////
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (LED_OutPin, OUTPUT);   // Set pinMode.
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (LED_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (LED_OutPin, HIGH);
  }
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // PIR as interrupt
  Serial.println ("System Ready");
}

//////////////////////////////// void loop ///////////////////////////////////
void loop()
{
  interrupts();
  readKeypad(); Serial.println ("at keypad");
  alarm();
}

////////////////////////// void trigger ///////////////////////////////////
void trigger() {
  PIRtrigger = true;
  // alarm();
}

///////////////////////////// void alarm ///////////////////////////////////
void alarm() {
//  PIRtrigger = false;
  time = millis(); // reset time.
  interrupts();
  Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("PIRtrigger="); Serial.println (PIRtrigger);
  Serial.println ("at Alarm");
  if (away == true && PIRtrigger == true) {
    // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
    Serial.println ("MOTION detected: SMS Sent");
    for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
      digitalWrite (Alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
      digitalWrite (Alarm_OutPin, LOW); delay (500);
      digitalWrite (LED_OutPin, HIGH); // delay (1000);
      Serial.println (alarm_count);
    }
  }
  PIRtrigger = false;
  //  away = false;
  Serial.println ("after alarm");
  Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("PIRtrigger="); Serial.println (PIRtrigger);
  noInterrupts(); /////////////////////////////////
  readKeypad();
}

///////////////////////////// read Keypad ///////////////////////////////////
void readKeypad() {
  char key = keypad.getKey();
  if (key != NO_KEY) { // if a keypad input
    key_input[z] = key;
    tone(10, 900, 100);
    Serial.print ("Key_input["); Serial.print(z); Serial.print ("] = "); Serial.println(key);
    z++;
    if (z >= sizeof(key_input)) {
      z = 0;
    }
    switch (key) {
      case '*': // resets key_inputs to "0"
        z = 0;
        break;
      case '#': // pressed to "enter"
        z = 0;
        for ( i = 0;   i < 4 ;  i++ ) {
          //        Serial.print(key_input[i]);
        }
        //      Serial.println ("-------");
        delay(100); // for extra de-bounce
        checkPIN();
        break;
    }
  }
}

///////////////////////////// check PIN ///////////////////////////////////
void checkPIN() {
  Serial.println ("@ checkPIN ");
  int correct = 0;
  int i;
  for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
    if (key_input[i] == PIN[i]) {
      correct++;
    }
  }
  if (correct >= sizeof(PIN) - 1) {
    //   Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
    correctPIN();// go to correct PIN instructions
  }
  else {
    incorrectPIN(); // go to incorrect PIN instructions
  }
}

///////////////////////////// correct PIN ///////////////////////////////////
void correctPIN() {              // do this if correct PIN entered
  Serial.println ("@ correct PIN ");
  // digitalWrite (LED_OutPin, HIGH);
  digitalWrite (LED_OutPin, LOW); // on-board LED to show the status of alarm
  PIRtrigger = false; // turn the PIR state to off
  away = false; // turn the away state to off
  noInterrupts();
  readKeypad();
}

///////////////////////// incorrect PIN ///////////////////////////////////
void incorrectPIN() {           // do this if incorrect PIN entered
 //  noInterrupts(); // Serial.println ("interrupt off 1");
  Serial.println ("@ incorrect PIN ");
  away = true;
  digitalWrite (LED_OutPin, HIGH); // tied to Alarm output level
  //Has time passed? delay(timeout) - allow time to leave premises
  PIRtrigger = false;
    alarm();
  }

First, as AH L said, there is no HIGH interrupt on a Uno. Looking at Arduino.h we see:
#define HIGH 0x1
#define LOW  0x0

...

#define CHANGE 1
#define FALLING 2
#define RISING 3

Thus your HIGH interrupt (which doesn't exist) is really a CHANGE interrupt.
Next, you seem to be recursively calling stuff.

loop calls readKeypad.
readKeypad calls checkPIN
checkPIN calls correctPIN
correctPIN calls readKeypad

So this code is digging itself deeper and deeper into function calls. It will eventually run out of stack.
i.e.
readKeypad -> checkPIN -> correctPIN -> readKeypad -> checkPIN ...

You need to restructure.
See my page about interrupts.
Also see my page about state machines.

I know that it is ugly code; from repeatedly making changes/additions to try to get it to work. I have cleaned up some and will continue on others. Thanks for your feedback. I wasn't thinking about a stack issue.

How do I better manage the stack?

Don't do recursive calls. For example don't have a call b and inside b call a. Read the link I gave about state machines.

Thanks. I plan to try state machines in the very near future.

Most Arduinos don't support interrupting when a pin is HIGH. Try changing attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH) to attachInterrupt (digitalPinToInterrupt (2), trigger, RISING).

Thanks. I had tried CHANGE and HIGH with same results. I will try RISING to see what happens.


text:
Easy way to upload sketches using MIDI (without RX pin removed)
I noticed when I use sketches with MIDI (using RX/TX), before uploading I have to remove every time the RX wire ... is there an easy way to prevent this?
(I'm thinking about making a push button/toogle for this to prevent it, but maybe there is an easier way).
Update: I use an Arduino Uno

@CL: Updated my question (sorry for not mentioning)

To allow the bootloader on the Arduino MCU to communicate with the USB chip, the TXD/RXD pins are connected:

These connections have 1 kΩ resistors so that the signals of the USB chip do not interfere with your own hardware too much. However, this means that your own hardware can easily override those signals.
In this case, your MIDI hardware actively drives the RXD line to a high level.
You is no way to work around this in software.
You could try to replace the optocoupler's pull-up resistor (270 Ω) with a 10 kΩ resistor, which would make the USB controller's signals ten times stronger than the MIDI ones, but this might make the signal edges too slow.
To reliably prevent conflicts, you have to add a disable function to the MIDI receiver, or power it down, or disconnect it.

Thank you very much for this clear answer (and also the background).
I will order a toggle or switch that keeps state (like on/off) to hardware-wise open or close the connection from RX to the MIDI circuit, so I don't have to switch it on/off.
I don't like to take out the MIDI connector (they are quite well connected), and removing the cable is a bit tedious :-) Also I don't want to mingle with the MIDI ' quality'  since I will need all messages to be received well.

I changed to a Mega, using 3 channels for MIDI and one for debugging; eventually I might use all 4 for debugging.


text:
Generating random pattern on startup
I'm trying to get an arduino to generate a random pattern in a neopixel grid every time you restart it. But I only get the same number sequence generated each time. What I'm doing wrong?
Here's the sequence that keeps happening: 1110 0000 1101 0011
Here's the code I have so far:
/* ========================== INCLUDES ================================= */
#include "RGB.h"

#include <Adafruit_NeoPixel.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_GFX.h>
#ifndef PSTR
 #define PSTR // Make Arduino Due happy
#endif

/* ========================== NEOPIXELS SETTINGS ================================= */
#define NEOPIN 6
#define MATRIX_W 4
#define MATRIX_H 4

Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(MATRIX_W, MATRIX_H, NEOPIN,
  NEO_MATRIX_BOTTOM + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG,
  NEO_GRB + NEO_KHZ800);

/* ========================== BOARD / GRID STUFF ================================= */

/* coordinates for a 4 x 4 grid
00,10,20,30
01,11,21,31
02,12,22,32
03,13,23,33,
04,14,24,34
*/

int land[4][4] = {};

/* ========================== SETUP AND LOOP ================================= */

void setup(){

  Serial.begin(9600);

  matrix.begin();
  matrix.setBrightness(60);
  matrix.fillScreen(matrix.Color(off.r,off.g,off.b));
  crossFade(off, white, 50, 5);
  drawLand();
}

void loop(){
  matrix.show();
}

/* ========================== FUNCTIONS ================================= */

  void drawLand() {
  for(int row = 0; row < MATRIX_W; row++) {
    for(int column = 0; column < MATRIX_H; column++) {

     land[row][column] = random(0,2);

     Serial.println(land[row][column]);
     if(land[row][column] == 1) {
       matrix.drawPixel(column, row, matrix.Color(red.r,red.g,red.b));
     }
   }
  }
}

It's because an machine running the same program on the same data will calculate the same result. rand() is a pseudo-random generator for that reason. With the same starting value it will create the same sequence of numbers. The only way to get different outputs is to provide different inputs: You have to start rand with a different value each run. You can set initialize rand() by supplying an unsigned int to randomSeed(). But it still needs to be different from run to run for you get different outputs from those runs.
Some devices do this by reading a real-time clock on startup and hashing the result in some way. Another method is to ask the user to press a button or a key and using the response time (and possibly the key, if it's a keyboard) to generate the seed. Counting non-repeating events, like electrical noise or background radiation is another way.
But bottom line: you need different inputs to get different outputs.

I just figured out I needed randomSeed to help it along 5 minutes after posting this. It ain't perfect, but randomSeed(analogRead(A0)); does the trick well.

put a short segment of wire onto the analog pin to increase the max noise value.

Re: previous comments.  You can use a product, sum, and modulus/LSB of analogRead's to make it unpredictable and give somewhat equally probable outcomes.  The timing of multiple analogRead's could potentially affect the randomness.

randomSeed(analogRead(A0)); does the trick well

Better yet, use the lsb of analogreads to seed the random number generator. No repeat patterns any more.