text:
A confusion with setting timers
I was reading a tutorial on timers. My aim is to generate 16MHz pulse output from the pin 8.
Here is the code I modified from the tutorial (I use Arduino's ATmega328P):
#include <avr/io.h>
#include <stdint.h>

int main (void)
{
    DDRB |= (1 << 0); // Set LED as output
    TCCR1B &= ~(1 << CS11); // Set up timer
    TCCR1B &= ~(1 << CS12); // Set up timer
    TCCR1B |= (1 << CS10); // Set up timer

    for (;;)
    {
        // Check timer value in if statement
        if (TCNT1 >= 0)
        {
            PORTB ^= (1 << 0); // Toggle the LED
            TCNT1 = 0; // Reset timer value
        }
    }
}

I use the following formula:

Target Timer Count = (1 / Target Frequency) / (1 / Timer Clock
  Frequency) - 1

So Target Timer Count = 0 in my case.
But I get 615kHz on scope.
My timer setting should output 16MHz since I use no prescaler:

What am I doing wrong?

You can have the timer toggle the led, instead of doing it yourself (by using the COM1A1/COM1B1 bits in the TCCR1A register. To set the maximum value of the timer from 65535, set the timer to CTC mode, and set OCR1A to 1 (or maybe 0). If you want to do software PWM, just use while(true){PORTB ^= (1 << 0);}.

If you want to output a signal at the same speed as the system clock, I would not recommend using a timer.  You can output the system clock to Port B Pin 0 by programming the CKOUT fuse on the 328P.
The reason I suggest not using a timer to output a signal at the same frequency of the system clock is that the compare of TCNT1 you have as well as the toggle of the output will take clock cycles so the output will never quite be the clock speed.
If you use a timer for outputting a signal, I suggest using CTC mode of Timer 1 using the output compare to set the top.  You can then either poll the appropriate Output Compare Match flag or handle the related interrupt.

I agree with this. This is the only way that the Atmega328P running at 16 MHz can output a 16 MHz signal. Using timers the maximum you can get is 8 MHz. If you want to see code that does 8 MHz using timers see Example of generating 8 MHz signal


text:
The program keeps skipping over the running 1 and 2 states even though the prereqs are met
The serial prints are for troubleshooting. All outputs are LEDs for testing purposes. The running 1 and 2 states are sometimes skipped over, but not always. I think this is from the light sensor being bad and jumping up and down, but using a higher value does nothing. I also tested the light sensor in the example program and got 1s and 2s so that really shouldn't be the problem. When it does work and the second light sensor is covered (the one that measures sugar level) it continuously cycles through and never returns to ready state. If more detail is needed please let me know
//Digital Inputs
int measureSwitch = 13; //switch that sets 2 tsp and 1 tsp

//Digital Outputs
int motor = 12;
int buzzer = 11;
int readyLed = 10;
int running1Led = 9;
int running2Led = 8;
int doneLed = 7;
int sugarLevelLed = 6;

//Analog Inputs
int cupSensor = 20; //the light sensor should read 0 when the cup is resting on it
int lightSensor = 100; // the sugar should cover up thelight sensor so the light can pass thru, making it zero

//different run times

int running1Time = 100; //1 tsp tentative times
int running2Time = 250; //2 tsp tentative times
int buzzerTimer = 200; // how long the buzzer will go off for

void setup() {
  Serial.begin(9600);
  pinMode(measureSwitch, INPUT);
  pinMode(motor, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(readyLed, OUTPUT);
  pinMode(running1Led, OUTPUT);
  pinMode(running2Led, OUTPUT);
  pinMode(doneLed, OUTPUT);
  pinMode(sugarLevelLed, OUTPUT);
}

//Ready State

void readyState(){
  digitalWrite(readyLed, HIGH);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, LOW);
}

//Running 1 State

void running1State(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, HIGH);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, HIGH);
}

//Running 2 State
void running2State(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, HIGH);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, HIGH);
}

//Done State
void doneState(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, HIGH);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, HIGH);
  digitalWrite(motor, LOW);
}

//Waiting State
void waitingState(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, HIGH);
  digitalWrite(sugarLevelLed, LOW);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, LOW);
}

//Sugar Level State
void sugarLevelState(){
  digitalWrite(readyLed, LOW);
  digitalWrite(running1Led, LOW);
  digitalWrite(running2Led, LOW);
  digitalWrite(doneLed, LOW);
  digitalWrite(sugarLevelLed, HIGH);
  digitalWrite(buzzer, LOW);
  digitalWrite(motor, LOW);
}

void loop() {
  while(analogRead(A0) > lightSensor){ //when there is no cup placed on the
sensor, be in ready state
    readyState();
    Serial.println("READY STATE");
  }

//when the cup is on the sensor and the switch is set to 1 tsp
    for(int time1 = 0; ((time1 < running1Time) &&
                        (analogRead(A0) < cupSensor) &&
                        (digitalRead(measureSwitch) == HIGH)) ; time1++){
    //run the running 1 state for 4 seconds
      running1State();
      delay(1);

      Serial.println("RUNNING STATE 1");
      Serial.println(time1);

  }

    //when the cup is on the sensor and the switch is set to 2 tsp

    for(int time2 = 0; ((time2 < running2Time) && (analogRead(A0) < cupSensor)

&& (digitalRead(measureSwitch) == LOW)); time2++){

//run the running 2 state for 8 seconds

      running2State();
      delay(1);
      Serial.println("RUNNING STATE 2");
      Serial.println(time2);
      Serial.println(analogRead(A0));

  }

  for(int buzzerTime = 0; buzzerTime < buzzerTimer; buzzerTime++){

    doneState();
    Serial.println("DONE STATE");
    Serial.println(buzzerTime);
    delay(1);
  }

  while(analogRead(A0) < cupSensor){
    waitingState();
    Serial.println("WAITING STATE");
  }

  while(analogRead(A1) > lightSensor){
    sugarLevelState();
    Serial.println("SUGAR LEVEL STATE");
  }
}

Try pulling the output of the light sensor to ground via a 10k resistor, that should calm the values.
Note that you are going to need to completely change the value of the variable lightSensor. This is because it will now be outputting different values due to the extra resistor to ground.

simulate this circuit – Schematic created using CircuitLab

and probably the bottom connection of LDR1 (as shown in the diagram) should be labeled +5v if the Arduino is a Uno etc.

I wasn't used to the design software

source: Stack Exchange

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

sort: votes


text:
Arduino DigitalWrite() Super Basic Circuit measure voltage with multimeter
I am having a problem measuring the voltage with a multimeter. I am not sure if arduino is even sending out a voltage from the Pin.
I will try to create a really basic circuit drawing for reference. (Drawing attached).

What I am trying to do is to measure with a Multimeter the Voltage (or current) across the alligator clips.
I will attach the code below:
//Code Section Start//

int ledPin = 13;                 // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(ledPin, HIGH);   // sets the LED on
  delay(10000);                  // waits for a second
}

//Code Section End//

Typically the digital write I believe will out put 5 volts and with a 1k Ohm resistor that is only 5mA current. I have heard Arduino can take up to 40mA currents so I don't think I am frying something.
There are two weird things I have noticed. When I try other Pins like "int ledPin = 10;" The green light on the Arduino does not light up. It only lights up when I use pin 13. However, even using Pin 13 or any other pin, I cannot find a voltage or current with the Multimeter. I am using an Arduino Micro.
Can someone please help me identify what I am doing wrong or some method of how to check what is wrong? So that I can have a complete circuit with a voltage I can measure.

If you see the LED being toggled, you are probably tapping into the wrong pin/pad. With the power off, try to retrace (by observation) the electrical path between LED and your tapping point (where you attach the resister). Do you have a schematic of the specific board you are using?

I can't quite understand your diagram. Are the alligator clips supposed to be touching each other, or separated?

... or are they both clipped side by side to the same 'groundy' bit of wire? If so, move the positive one to the other side of the 1k resistor

Thank you guys for answerng so quickly. duskwuff the Alligator clips are clamped together.  @Neil_UK the Alligator clips do not relate to the positive and negative lines, sorry I should have been more specific. The positive and negative lines are the wires that connect to the multimeter (Since the alligator clips are metal I believe if i just put the wires from the multimeter on them, that should read the current/Voltage)

@Yuriy The LED is on the board. (https://www.arduino.cc/en/Main/arduinoBoardMicro) the left board in the pic, right next to the word micro is a LED. How do i trace that? Also How would I be tapping the wrong pin/pad? I am int pin 13 I thought that was all I had to do? Can I track the electrical current through this diagram? (http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf) I believe that is the schematic for the arduino micro.

OK, well move the positive meter connection to the other side of the 1k reistor

@Neil_UK Ahh right thank you! The V=IR if R=0; V/R=inf so the Multimeter wouldn't work! Thank you very much!I really appreciate all you guys helping!

On the Arduino micro board (https://www.arduino.cc/en/uploads/Main/arduino-micro-schematic.pdf), the green LED is connected to IO13 (pin 13). So it makes sense that it lit up only when you are using pin 13, but not with pin 10...

As you have drawn it, the alligator clips are clamped together (shorted togther).  You reading the voltage "across" a shorted element in the circuit should yield ~0V (shorts by definition have no to very little resistance, meaning there should be no voltage across them).  In order to get your proper voltage reading, you should place the multimeter positive clip above the resistor (where the voltage drop is occuring).
Remember.
Measure current THROUGH.
Measure voltage ACROSS.
p.s. if you're trying to alternate the pin, you should do something like DigitalWrite(pin10, digitalRead(pin10)!=HIGH); (if it's low, then the statement evaluates to true, setting the pin high, if it's high, then the statement evaluates to false, setting the pin low)

As you connected the alligator clips (from the image it seems that they are touching each other) you won't be able to measure anything.
This is how to connect a multimeter to read the current (A) and the voltage (V). You can consider the + of E as the pin 13 and the - as the ground

Remember that your code will not change the state of pin 13, it will be always high.
If you want to make the signal change try this on your void loop :
  digitalWrite(ledPin, HIGH);
  delay(10000);
  digitalWrite(ledPin, LOW);
  delay(10000);

you are telling that you are not getting any current or voltage on your multimeter
right......
i suggest you to use the following code:-
int ledPin = 13;                 // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(ledPin, HIGH);   // sets the LED on
}

this will stay your arduino pin 13 always high then you can measure the voltage on that pin........

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


text:
Converting `millis()` to decimal seconds?
I would like to get my Arduino to print milliseconds as decimals of seconds.  For example, instead of printing 10456, printing 10.456
I have tried to set a float value or millis, and dividing by 1000 but that gives me a whole number "0" to "1" which is not ideal
The code I use is:
float ourtime = (millis() / 1000);
dataFile.print (ourtime);

What would be the easiest, and least taxing (for the processor) way of getting a script to return milliseconds as seconds while taxing the unit as little as possible ?

Could you make explicit the meaning of "the best way"? Do you mean, a way that works properly, a way with readable code, a fast way (how fast), a way is as little code as possible?...

Dividing an integer by an integer (1000) yields an integer, regardless of what you cast that result to.
Instead you need to divide the integer by a float, or cast the integer to a float first. The simplest way is:
Serial.println(millis() / 1000.0, 3);

The 3 as the second parameter tells Serial.println() how many decimal places to print. The .0 at the end of 1000.0 forces the compiler to see 1000 as a float value (you can also use 1000f if you prefer).
Since floating point can be quite expensive it's possible to emulate it using integer division and modulus (although they are still quite expensive):
uint32_t now = millis();
uint32_t secs = now / 1000;
uint32_t ms = now % 1000;

Serial.print(now / 1000);
Serial.print(".");
if (ms < 100) Serial.print("0");
if (ms < 10) Serial.print("0");
Serial.println(ms);

You could replace the % with a x1000 and a subtraction too if you like:
uint32_t now = millis();
uint32_t secs = now / 1000;
uint32_t ms = now - (secs * 1000);

Serial.print(now / 1000);
Serial.print(".");
if (ms < 100) Serial.print("0");
if (ms < 10) Serial.print("0");
Serial.println(ms);

A further method would be to first "print" the milliseconds to a string, then split it into two chunks. Print the first chunk, then a decimal point, and finally the second chunk. This avoids the use of any division or multiplication, but does use expensive string operations:
char num[10];
snprintf(num, 10, "%lu", millis());
uint8_t nlen = strlen(num);

for (uint8_t i = 0; i < nlen - 3; i++) {
    Serial.write(num[i]);
}
Serial.write('.');
for (uint8_t i = nlen-3; i < nlen; i++) {
    Serial.write(num[i]);
}
Serial.println();

So really there is no "perfect" method for converting milliseconds into seconds that uses hardly any CPU cycles. All base 10 operations tend to be a bit expensive on a small microcontroller without hardware support for integer MUL/DIV instructions, or a Floating Point Unit.

You mean if (ms < 100) and if (ms < 10). Integer division is not cheap either: I timed your float code version at 11480 CPU cycles (not counting the call to millis()) and you int version at 7561 cycles, i.e. 34% less time. Both for the millis value 12345678UL. So it's faster, but not by orders of magnitude.

You are right, my keyboard is hiding under the desk at the moment and I can't actually see it.  No division on an AVR is cheap. If you are that concerned about the speed of division you would pick an MCU with a hardware division unit, or an FPU and use floating point.

Serial.println(millis() / 1000.0, 3);
is a great idea, but if used alone, it drops zeros.
So the output would be "0.849", "0.874", "0.95" (and not "0.950") which may cause problems.

Sure. I am just saying that replacing floating point division by integer division does not provide as large a speedup as one may naively expect.

Also you have to wonder how much of the difference is due to the serial print routines, one handling float and the other handling integers...

A third method would be to print each character individually via a string without using any division at all...

uint32_t ms = now % 1000; given that you already have done thee division, the mod operation is unnecessary, especially given how expensive it is.

@dannyf You would have to multiply by 1000 and subtract it from now instead, which can be as expensive.

@dannyf: The compiler is smart enough to factor the now / 1000 and now % 1000 into a single call to __udivmodsi4().

Division is quite expensive.
Division can be done with subtraction, or shifting - right shift 10 (= /1024) and then compensate for that 24....
You may need too benchmark to see if on your chip this will yield any gaiin.
edit:
I did some quick benchmarking against the brutal force approach by Majenko (division followed by the mod operation), for full range 16-bit types, dividing by 1000, on a PIC16, XC8 free mode:
for 16-bit types
 1. Majenko's approach (1000 divisor + mod): 45.9M ticks;
 2. revised Majenko's approach (1000 divisor, no mod): 36.9M ticks;
 3. My approach (1024 divisor, no mod): 20.8M ticks.
[edit 2]for 32-bit types
 1. Majenko's approach (1000 divisor + mod): 101.6M ticks;
 2. revised Majenko's approach (1000 divisor, no mod): 63.0M ticks;
 3. My approach (1024 divisor, no mod): 19.3M ticks.
the same trend applies under the pro mode.
the same trend applies for AVR, with the speed gain being bigger.
edit 2: 32-bit benchmarking added.
I also revised my approach for 32-bit types to speed up the execution a little.
lessons learned:
1) mod ops shall be avoided as much as you can;
2) divisions shall be avoided as much as you can.
3) algorithm rules!
however, be cautious to extrapolate the data here. on a chip with hardware multiplier + divider (STM8, my favorite chip), this trend may not apply and you should benchmark on the target chip to be safe.

Care to show the algorithm to “compensate for that 24”?

I don't think it the division that is slow, but the use of a float on a CPU that doesn't support floating point operations.


text:
ESP8266 and Arduino integration
I am trying to upload a sketch and getting below error:
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed.

Connections:
TX - TX
CH_PD - 3.3 V
RX - RX
VCC - 3.3
GPIO GND
GND - GND

Before uploading the sketch I have reset the arduino and ESP and selected board as ESP8266 and baud rate as 115200 but still getting the same error.

You don't say what you're using to program it (an FTDI board? the USB adapter on an Arduino?) but you probably want to connect
TX - RX
RX - TX


text:
Arduino LCD Display 2x16 custom char byte limit
Some years ago I stumble with a problem while using the 2x16 LCD. What happened was that there was a limit to how may byte arrays I could declare. So my project came to a halt because I needed to create more custom characters to advance any further...
The lcd accept custom characters to store them but I suppose there is a limit to this, am I wrong?
I'm trying to create a set of custom characters that move on screen. Since there are a lot of animations I need several of them to have a smooth animation. The problem resides in the limit of characters I can pre-establish after executing lcd.begin()
I don't post code because to my understanding that is not relevant and because sincerely is a crap since I wrote it down when I was learning programming some years ago. I want to resolve this so I can rewrite the code.
LCD version: QAPASS 1602A
Here is an example:
byte Ghost[8] = {
  0b00000,
  0b01110,
  0b01110,
  0b10101,
  0b11111,
  0b11111,
  0b11111,
  0b10101
};
lcd.createChar(0, Ghost);
So the right question is: Do I need to reset the LCD chip then declare the new characters to the lcd to make it available? How?

there was a limit to how may byte arrays I could declare.

If the problem was that you ran out of free RAM, then the fix is to move those byte arrays into program space.
Atmega 328 processors (Uno) are very RAM-limited. Fortunately you can assign constant data - fixed character strings, lookup tables for math, fonts, CRC calculation, etc - to be stored in program space which is much more generous. The upside is you can free lots of RAM in an application like yours that needs lots of constant data. The downside is that access to the data is a little bit slower:
// Definitions for data in program space
#include <avr/pgmspace.h>

// Place the character table in Flash
byte const Ghost[8] PROGMEM = {
   0b00000,
   0b01110,
   0b01110,
   0b10101,
   0b11111,
   0b11111,
   0b11111,
   0b10101
};

// Read a byte of character data
OneByte = pgm_read_byte(&Seg7_segtbl[index]);

Update:

LCD version: QAPASS 1602

If that has an Hitachi HD44780 controller on it, its datasheetsays it has a 64-byte character RAM - more than enough for a full display of 2 x 16 unique characters, but if you need a wider choice of characters than a set of 64, you may need to re-load the RAM with a custom sub-set for any given screen-full. For animating, though, you'll probably need all of the individual parts of each animation in the LCD RAM at once; reloading during animation will most likely disturb the smoothness. One possibility is to load part of a subset between animation frames - if that's even possible. (I haven't studied this controller to that level of detail).

Thanks sir! So &Seg7_segtbl[index] where index means a specific value of the constant byte variable stored in flash memory... This can come in handy but I think my problem is more related to the lcd itself. I heard that the lcd can store custom characters on its own but obviously it has a limit.

Correct (about the address expression). To help with your LCD, we'll need to know what LCD and driver chip you're using (manufacturer and part#), and more specifics about the the problem you have: what are you trying to do and how did you do it? And what were you expecting to would happen, and what happened instead?

Check my edit and I'm grateful for the tips and your time

Typical HD44780-based   2x16 LCD support 8 programmable characters, not 16.  They show up as characters #0 to 7 and again as characters #8 to 15.  Definitely not 64 programmable characters, not 32, not 16 – just 8 of them.

@jwpat Then perhaps I misinterpreted the datasheet or I found the wrong one? But Itook that spec from the datasheet.

The 64 bytes of RAM are used 8 bytes per character.  Each byte represents one 5-dot line of a character.  See heading "Character Generator RAM (CGRAM)" in HD44780 spec, which says:   “In the character generator RAM, the user can rewrite character patterns by program. For 5 x 8 dots, eight character patterns can be written, and for 5 x 10 dots, four character patterns can be written.”  Note, typical  HD44780-based 2x16 LCDs are set up 5 x 8 rather than 5 x 10

@jwpat7 Yeah that's the current problem! It accept only 8 custom characters.

For now I came with the solution of reseting the arduino with asm volatile ("  jmp 0"); I write a number to the EEPROM and then reset so in the setup I use a statement to read the EEPROM to load the characters I need

Sorry not fixing anything! I still got my error


text:
M0 pro: SPI communication, code works on Uno, but not in M0. Using ICSP port
I am trying to establish a communication between a sensor and a M0 -pro using SPI. The code :
    #include <SPI.h>

    unsigned int result  = 0;
    void readAngle();

    void setup() {
      Serial.begin(9600);
      SPI.setBitOrder(MSBFIRST);
      SPI.setClockDivider(SPI_CLOCK_DIV8); //sets the clock speed for data transfer, slowed down 8 times
      SPI.setDataMode (SPI_MODE1);

      digitalWrite(11,HIGH);
      pinMode(11,OUTPUT);

      SPI.begin();
      SerialUSB.println("First Try");
}

    void loop() {
      readAngle();
      SerialUSB.println(result);
      delay(500);

}

    void readAngle(){
        digitalWrite(11,LOW); //Turn SS on, start communication
        result = SPI.transfer16(0xFFFF); // the read command and the response received
        result = (result << 2) >> 2; // get rid of the last 2 bits, error(14) + parity(15)
        digitalWrite(11,HIGH); //Turn SS of

}

The code works perfectly with an UNO, but with M0, it event doesnt print the first SerialUSB.println("First Try");. The moment i erase the lines that have SPI commands in it, the serial monitor starts working again. As i said in the titel i am using the ICSP port on M0. I use the native usb port to programm.
I think i am missing something very basic. I checked many different forum posts, but there is no indication of M0 requiring other SPI commands. Any help is much appriciated.
PS: i didnt go into detail with the sensor and its datasheet because since it works fine with uno, the cause of the problem should be it.

Which version of the Arduino IDE are you using ? If its an older one, try to get the latest one, sometimes that solves issues like the one you have.

You must declare that the pin as an output before you use it.
Do this by using the pinMode() function, like this:
pinMode(11, OUTPUT);          // sets the digital pin 11 as output

Add the above line at the beginning of your setup() function.


text:
Program Arduino Uno via Nano
To keep the question short:
I'm trying to burn a bootloader on my Arduino Uno using an Arduino Uno. Could someone please tell me the pin connections? Thanks.

To burn a bootloader from source Nano to target Uno make the following connections:
Nano.Pin   Uno.Pin

10         Reset

11         11

12         12

13         13

GND        GND

See here for more details: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard


text:
Weird result printing an array using a loop
first of all I'm sorry for my english.
My problem is that I want to use an array of numbers on a function, but I'm getting a weird result inside a for loop. Doing some tests I've seen that it happens even in the simplest sketch so I should be doing something wrong.
I've created a two level int and I want to iterate through the second level using a for loop. Outside the for loop all data gotten from that array is OK, but just inside the loop I'm just getting garbage as if the array was not initialized.
My simple sketch is this:
const int number_small[][14] PROGMEM = {
  {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
};

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

  Serial.print(String(number_small[0][0]) + "\n");
  Serial.print(String(number_small[0][1]) + "\n");
  Serial.print(String(number_small[0][2]) + "\n");
  Serial.print(String(number_small[0][3]) + "\n");
  Serial.print(String(number_small[0][4]) + "\n");
  Serial.print(String(number_small[0][5]) + "\n");
  Serial.print(String(number_small[0][6]) + "\n");
  Serial.print(String(number_small[0][7]) + "\n");
  Serial.print(String(number_small[0][8]) + "\n");
  Serial.print(String(number_small[0][9]) + "\n");
  Serial.print(String(number_small[0][10]) + "\n");
  Serial.print(String(number_small[0][11]) + "\n");
  Serial.print(String(number_small[0][12]) + "\n");
  Serial.print(String(number_small[0][13]) + "\n\n\n");

  for (int i = 0; i<14; i++){
    Serial.print("I: " + String(i) + " - " + String(number_small[0][i]) + "\n");
  }
}

void loop() {
}

And the output is:
124
124
387
387
399
399
443
443
483
483
387
387
124
124

I: 0 - 0
I: 1 - 184
I: 2 - 0
I: 3 - 1
I: 4 - 0
I: 5 - -18248
I: 6 - -18248
I: 7 - -18248
I: 8 - 0
I: 9 - 135
I: 10 - 0
I: 11 - 0
I: 12 - 769
I: 13 - 0

What I'm doing wrong?,
Thanks!!

Constants like String(number_small[0][0]) are optimized by compiler during the build (=compile time).
However that's not the case of loop. So you have to use specific functions for reading values from PROGMEM in the runtime:
for (int i = 0; i<14; i++){
  Serial.print("I: ");
  Serial.print(i);
  Serial.print(" - ");
  Serial.println((int)pgm_read_word(number_small[0]+i));
}

Btw: Don't use string concatenations. These are extremely hungry for the memory. See Majenko's article: The Evils of Arduino Strings

Hi, thanks for your answer!!. Just I've found the solution and I was posting it. And thanks for the suggestion about strings and the article.

I was sure that I was doing something wrong and yes... Finally I did another test (storing the array on SRAM instead on PROGMEM) and it worked, so I've changed my "research direction" and I've found the solution.
With my initial sketch I was reading the PROGMEM from outside the loop, but from inside the loop what i read is the SDRAM, so I've to use the pgm_read functions to force to read from PROGMEM, and now finally is working:

pgm_read_word(number_small[0] + i)

const int number_small[][14] PROGMEM = {
  {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
};

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

  Serial.print(String(number_small[0][0]) + "\n");
  Serial.print(String(number_small[0][1]) + "\n");
  Serial.print(String(number_small[0][2]) + "\n");
  Serial.print(String(number_small[0][3]) + "\n");
  Serial.print(String(number_small[0][4]) + "\n");
  Serial.print(String(number_small[0][5]) + "\n");
  Serial.print(String(number_small[0][6]) + "\n");
  Serial.print(String(number_small[0][7]) + "\n");
  Serial.print(String(number_small[0][8]) + "\n");
  Serial.print(String(number_small[0][9]) + "\n");
  Serial.print(String(number_small[0][10]) + "\n");
  Serial.print(String(number_small[0][11]) + "\n");
  Serial.print(String(number_small[0][12]) + "\n");
  Serial.print(String(number_small[0][13]) + "\n\n\n");

  int i;
  for (i = 0; i<14; i++){
    Serial.print("I: " + String(i) + " - " + String(pgm_read_word(number_small[0] + i)) + "\n");
  }
}

void loop() {
}

Thanks and greetings!!

I refined your own answer:

No need to use String to print a numeric value; just print the value.
No need to add "\n" add the end of print, use printlninstead.
No need to concatenate strings for printing; just print them one by one.
In a for loop, declare the control variable inside

Code
const int ITEMS = 14;
const int number_small[][ITEMS] PROGMEM = {
  {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
};

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

  for (int i=0; i < ITEMS; i++) {
    Serial.println(pgm_read_word(number_small[0]+i));
  }
  Serial.println();  Serial.println();
  for (int i = 0; i < ITEMS; i++){
    Serial.print("I: "); Serial.print(i); Serial.print(" - " );
    Serial.println(pgm_read_word(number_small[0] + i));
  }
}

void loop() {
}

I would add that pgm_read_word(&number_small[0][i]) is more idiomatic than pgm_read_word(number_small[0] + i).


text:
Is EEPROM's location relocated on sketch compile?
I assumed the microcontroller has 3 components as per storing data:
- flash memory for the program
- RAM for variables
- EEPROM for non-volatile user-storage
And I always assumed those are separate chips on the board. However, working directly with a RobotDyn Uno R3 leads me to believe I may be wrong somehow.
I compiled this program:
#include <EEPROM.h>

struct SettingsStruct {
  String server;
  String port;
  String user;
  String password;
  String description;
} gSettings = {
  "192.168.1.6",
  "8080",
  "fci blah vlak",
  "zangazang4",
  "Extra string here"
};

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

  //saveConfig();

  Serial.print(F("EEPROM size is: "));
  Serial.print(EEPROM.length());
  Serial.print(F(" bytes"));
  Serial.println("");

  loadConfig();
  Serial.print(F("Server: "));
  Serial.print(gSettings.server);
  Serial.println("");
  Serial.print(F("Port: "));
  Serial.print(gSettings.port);
  Serial.println("");
  Serial.print(F("Username: "));
  Serial.print(gSettings.user);
  Serial.println("");
  Serial.print(F("Password: "));
  Serial.print(gSettings.password);
  Serial.println("");
  Serial.print(F("Description: "));
  Serial.print(gSettings.description);
}

void loop()
{
  // nope
}

void loadConfig() {
    for (unsigned int t=0; t<sizeof(gSettings); t++)
      *((char*)&gSettings + t) = EEPROM.read(t);
}

void saveConfig() {
  for (unsigned int t=0; t<sizeof(gSettings); t++)
    EEPROM.write(t, *((char*)&gSettings + t));
}

Problem is that each time I add new elements to the struct, and I run the program, the serial prints different things. I recognize previously saved strings but they are right shifted, meaning that somehow the ZERO address of EEPROM might have moved backwards and previously saved strings move right and offocurse, appear on other struct variables.
This leads me to believe the actual EEPROM is related with the flash memory and depends on it on each compile. As if the ZERO address of EEPROM is established after each compile.
Can anyone confirm this or lead me to some documentation relating this? It's a weird mystery that I would like to clear out.

The EEPROM is a completely separate part of the silicon inside the chip. It has no address of its own.
You are making a fundamental error in what you are doing, though - you cannot directly store the contents of strings by looking at the addresses of those strings. The data in them is dynamically allocated in RAM and is completely separate from the object. You will have to come up with a different way to store your data.

The assumption was that EEPROM starts ALWAYS at the same address. the struct defined above should be able to be loaded as long as the save is equivalent. And it actually is. Problem was that data is shifting in EEPROM and I don't know why. I read your answer many times and it still does not help me understand this. What am I missing?

The struct is saved and loaded fine. The point is that the string data isn't in the struct for you to save. The struct only contains the String objects, and those just contain a pointer to dynamically allocated (at runtime) memory for the string data.

There's my problem. "dynamically alocated at runtime". My thought was that EEPROM is a fixed data storage entity you can always address the same way, similar to old assembly addressing mode. The fact that the EEPROM chip is separate also allows me to sustain this assumption. Why would runtime execution allow data shifting?

You're missing the fundamental issue here. The issue has nothing at all to do with EEPROM. That is exactly as you assume it to be - fixed. You read from address 0 exactly what you write to address 0. The fundamental issue is that you are not writing what you think you are writing to the EEPROM. It's like you have stored the envelope a letter came in and burned the letter itself, then go back to the envelope expecting it to be the letter.

My struct has a single variable called letter. I write it to eeprom, and I expect the /0 termination indicates the end of the string. Then, I add another variable to the struct. Another string, called title, before letter. Without writing, I read the new structure and observe that the title is gibberish then I can see my old letter further on. Where is the gibberish coming from and why is it before what I wrote before at address zero? This is basically what I don't understand. I do get that you are explaining that the struct itself is a reference. I don't get the field result.

You still aren't understanding what I am saying. Your struct does not contain your data . It contains objects that point to RAM which is allocated at runtime when the object is created where your string data is.

When you reload the objects from EEPROM the pointers point to areas of RAM that now are not allocated to the objects so give you gibberish.

Let us continue this discussion in chat.

Not all Arduinos, if you define Arduino as something which can run Arduino core code, have the same EEPROM concept. For instance, the ESP8266 simulates an EEPROM in a bit of flash memory. Clearly, however, in the OP's case an EEPROM as in say the atmega328p is being referred to and the problem is, as mentioned, that strings are not a primary datatype but an object, the data of which is not resident in the structure being saved. These should be converted to, say, an array of characters before being saved.


text:
How can I receive several inputs from wifi and save them?
I'm trying to send and receive some data from one Arduino to another Arduino. I'm using an Arduino Uno and FS1000A / XY-MK-5V 433Mhz TX/RX Modules. For transmitting I use the Radiohead library.
I want to send two strings and save them as different strings. My receiver code is:
#include <RH_ASK.h>
#include <SPI.h> // Not actualy used but needed to compile

RH_ASK driver;

void setup() {
  Serial.begin(9600); // Debugging only
  if (!driver.init())
    Serial.println("init failed");
}

void loop() {
  uint8_t buf[200];
  memset(buf, '\0', 200);
  uint8_t buflen = sizeof(buf);
  if (driver.recv(buf, &buflen)) {
    // Non-blocking
    Serial.print("Message: ");
    Serial.println((char*)buf);
  }
}

First of all, why do I have to use #include <SPI.h>? To receive I use:
if (driver.recv(buf, &buflen)) {
  // Non-blocking
  Serial.print("Message: ");
  Serial.println((char*)buf);
}

This code saves the output as one output! How can I specify which input is the first one and which is the second one?

If commenting out #include <SPI.h> causes an error, then presumably it is required by RH_ASK.hor something it drags in. The buffer buffor the received messages is recreated on each loop iteration so previous messages are lost. What do you want to do with 2 consecutive messages, concatenate them together or what?

I think we'd also need to know what data you are expecting to receive - unless it's always exactly 200 bytes, you'll need a way to tell where it finishes.

I want to sent two integer ( or I can send them as characters) but I want to save them as two variables.


text:
MAX7219 not behaving as expected
I have 2 rows of 12 MAX7219 connected in series with DOUT to DIN (rows are isolated). Now the thing is I am using LedControl Library to work with it. The problem is the last 4 Matrices on both the rows don't work. The sequence in my code is like this where (row, column, matrix) is used to define the row and column of the matrix and I am talking about a single ROW from two ROWs of 12.
Sequence in Code      What Happens
----------------      -----------------
(0, 1, 0)             (0, 1, 0)
(0, 1, 1)             (0, 1, 9)
(0, 1, 2)             (0, 1, 1)
(0, 1, 3)             (0, 1, 10)
(0, 1, 4)             (0, 1, 2)
(0, 1, 5)             (0, 1, 11)
(0, 1, 6)             (0, 1, 3)
.                     .
.                     .
.                     .
(0, 1, 11)            (0, 1, 8)

Now I can understand why does this happens. This code works like this even if the Device Count is 8.
Code:
#include "LedControl.h"
LedControl row1=LedControl(2,4,3,12);
LedControl row2=LedControl(5,7,6,12);

unsigned long delaytime=500;

void setup() {
  int d_row1 =row1.getDeviceCount();
  for(int address=0;address<d_row1;address++) {
    row1.shutdown(address,false);
    row1.setIntensity(address,15);
    row1.clearDisplay(address);
  }

  int d_row2 =row2.getDeviceCount();
  for(int address=0;address<d_row2;address++) {
    row2.shutdown(address,false);
    row2.setIntensity(address,15);
    row2.clearDisplay(address);
  }
}

void loop() {
  int devices=row1.getDeviceCount();
  for (int i = 0; i < devices; i++){
    delay(delaytime);
    row1.setLed(i,0,0,true);
    row2.setLed(i,0,0,true);
    delay(delaytime);
    row1.setLed(i,0,0,false);
    row2.setLed(i,0,0,false);
  }
}

EDIT
I just noticed something, there is no data going to the last 4 matrices. The timings of the blinking of the LEDs on last 4 matrices does not ties correctly (500ms) but it is in fact 250ms (i.e. half time). It means the blinks on last 4 matrices are between pulses of the first 4 matrices.

After fiddling around with various Libraries, I came across this one.
MD_MAX72XX
It has all the functionalities that I needed with a good Simple Wiki to get you started.
Also it is simple enough that even a noob like me could figure it out.
Regards

Have you checked the wiring between matrices and/or swapped modules in case there is a faulty one in the sequence?

yes I did check and it works. When any other module is swapped with that position, same bug.

Looking at your library source, it seems the number of devices is clamped at 8. This isn't a hard limit imposed by the chip but rather practical design. SPI, especially at high speeds, can get unreliable when the bus capacitance, related to the cable lengths, gets so high that signals are skewed beyond recognition. Also the buffer in the library used to hold the row data is 64 bytes in size, intended to hold the data for 8 devices with 8 rows each.
You can edit the library to make it support 12 devices though it will require attention to detail like, increasing the buffer to 96 bytes, getting rid of short-circuits within the methods that make sure that no more than 8 devices can be addressed, for-loops, etc.

That was the case. I am not that good with C and buffer things. So I abandoned this Library for something else. I did try changing the buffers and stuff but I failed, So I thought, instead of trying to customize this Library, I should look for something else as my changes would mean Library is working outside its recommended features. So... yeah...

@echo_salik You can post your solution here (another library?) and accept your answer so that this question is moved off the stack.

Ah yes. Sure. Sorry, forgot. :)


text:
Can I use NodeMCU with Arduino to connect to wifi or do I need a separate module?
I am just starting out with electronics. I got a Arduino Mega 2560 board and am able to do simple things like blink. Now I want to start a project on IoT and want to connect this board with internet. I got some leads here. While googling ESP8266, I came across NodeMCU which has a processor too. I already have Arduino, so can I use only the wifi module of NodeMCU and connect it to Arduino?

imho, slaving an ESP to an ATMEGA is like pulling a racecar with a horse; you should be coding in the ESP and using the MEGA as a mere IO expander.

NodeMCU already has a processor built in with the WiFi so you don't need a separate processor. If you just want to add WiFi to your Arduino board use an ESP8266 board connected to the Arduino. That is essentially the WiFi part of NodeMCU.

I went through almost the exact same thing you are going through when I was looking at the ESP8266 boards (the NodeMCU is one of those).  I too discovered that the NodeMCU is a micro computer in itself, even more powerful than the Arduino UNO!
You can even code the NodeMCU using the Arduino IDE.  As has been said previously, I'd use your NodeMCU directly to accomplish what you want to do.


text:
What is the worst time case for Arduino Mega?
I'm going to implement home automation using an Arduino Mega with 8*6=48 channels relay in my new home. I have prepared an Android app for an HC-05 Bluetooth controller. How much time can I keep running an Arduino Mega with all the appliances in a home? Can I keep it working 24/7 for a while?

That shouldn't be a problem. Just make sure you get a proper power supply. I'd also suggest using the watchdog timer, so that if the program somehow hangs, it will reset itself. Maybe tie the reset pin of the HC05 to an Arduino pin, so you can reset it. That way you never have to manually reset the system if anything happens. Also, maybe have a certified electrician take a look.

Can I keep it working 24/7 for a while?

yes, if properly designed.

Your answer is rather terse. Please expand on it.

Yes.
(For better guidance than that, we'd need to know more.)

I would be wary of going "all in" if the MCU holds+controls the state of all the relays, especially if there's networking happening in the sketch. That creates a single-point of failure for the whole house. I've found that a brief power outage or an MCU freeze/reboot resets the state. That can be frustrating and downright dangerous in a emergency situation.
An obvious solution is to save the relay states in EEPROM or externally on a server. The issue with those is that EEPROM wears out, and your server might not be available soon after a power-cycle when the MCU needs it to resume (router re-connecting, computer rebooting slower than MCU, etc).
The real solution, and the one that preserves life-safety is having local hardware state for each relay. You need the ability to both read state from the Arduino, and change the state from the Arduino. This can be as simple (yet expensive) as physically latching relays, or a capacitor-backed 1-bit state machine like an RS flip-flop. You can build the flip-flop in a variety of circuits, from shift registers, to a 555, to a simple NPN+n-channel MOSFET coupling (my pref).
The big downside is that this needs two pins for each relay. But, with such "smart relays", you can unplug the Arduino and nothing happens around the house. It also allows non-Arduino things (even a simple button/switch) to control the state of a relay, no matter what's happening with the Arduino at the time, but with the ability of the Arduino to react to that change and not over-write or forget the state. The MCU can reboot on a schedule to keep responsive, without anyone noticing the reboot.
Yes, it adds more complexity and cost, but a manageable amount of both, and the satisfaction difference is hard to truly express. In short, any system should work as reliably as lights did 100 years ago: switches work, and never unexpectedly change. If lights are not working or are turning off unexpectedly in a small fire, things can get ugly quick, especially with guests.


text:
Nick Gammon "Camera shutter speed timer"
I am reading the period of pulses from a 600ppturn shaft encoder, using the FreqPeriod library, by Martin Nawrath.
This works using counter1 and the comparator on pin6 and pin7 on the Arduino Uno.

The period duration for 1-2500Hz is being used in a midi musical instrument to give a speed to volume and a note change at a fixed speed.
This has worked well on the Uno but now I want to use a Mega (which does not have both comparator pins).
So I have tried using the Nick Gammon interrupt sketch. This has produced very erratic results returning both positive and many negative numbers (shown by using "volatile long period;" in the monitor.
Can you tell me what is happening and would it be better to use a counter instead of interrupts?
Hope I have given enough information to be getting on with, many thanks.
// Camera shutter speed timer
// Author: Nick Gammon
// Date: 15th January 2012

volatile boolean started;
volatile unsigned long startTime;
volatile unsigned long endTime;
volatile unsigned long period;
volatile unsigned long lfrq;

// interrupt service routine
void isr () {
    if (started)
        endTime = micros ();
    else
        startTime = micros ();
    started = !started;
} // end of Pulse Width

void setup () {
    digitalWrite (2, HIGH); // pull-up
    Serial.begin (9600);
    Serial.println (" Pulse Width test = ");
    attachInterrupt (digitalPinToInterrupt (2), isr, CHANGE); //CHANGE RISING
} // end of setup

void loop () {
    if (endTime) {
        period = (endTime - startTime) * 32 ; // pulse width?
        Serial.print (" \n  ");
        Serial.print ( " period =  ") ;
        Serial.print (period) ;
        lfrq = 16000000.0 / period;
        Serial.print(" Hz = "); // one rev per sec = 26666 micros period
        Serial.print( lfrq );
        endTime = 0;
    }
} // end of loop

If you simply want frequency and period, in the Interrupt Service Routine, simply count the times the ISR is called.
In the loop() at regular intervals, say 10 mS, look at the count and multiply up to get the counts per second. If you use 10mS intervals,
multiply by 100. That is your frequency in Hz. The inverse, i.e. divide 1 by your frequency in Hz, and that is your period. Then reset the count back to 0.

Why are you using the analog comparator for what is a digital input? An encoder provides pulses, not a range of analog values. I have a page about rotary encoders if that helps.

I am  reading the period of pulses from a 600ppturn shaft encoder, using FreqPeriod Library , by Martin Nawrath because I was very new and ignorant ( but now slowly learning)  to programing. Martins   sketch answered my need to produce a continuous   series of pulse period measurements at low Hz to compute a rising volume with turning speed and to trigger a midi note change a speed set by a pot`. This sketch is the only one I found that worked out of the box .

his sketch is the only one I found that worked out of the box and was happy with . It is only now  I am boning up on interrupts and timers with my need to use the  Mega . . PS this is my instrument on YouTube ;  https://www.youtube.comwatch?v=Hquj4RQdFmI

Hold The Pages! I have got the above Nick Gammon sketch working to producing a chain of readings.

I think the problem started when I updated my IDE from 1.6.0 to 1.8.0. I have had problems compiling . The only way I found to make some sketches compile and upload was to include a library such as  <SD.h> . I since realized that "digitalWrite" may not be supported , replacing with  "pinMode" and removing <SD.h> ,the sketch now works as I am sure intended. I will now incorporate this into my existing musical instrument sketch and let you know how I get on.

Can you tell me what is happening [...]?

Not really, but here is a wild guess: your input signal is bouncy, the
ISR fires too often, your loop cannot keep up with the rate, and you end
up accessing endTime in the ISR and loop simultaneously.
If you have a scope, look at your encoder signal. Is it clean?

would it be better to use a counter instead of interrupts?

Using the input capture feature of a timer will give you the best
possible accuracy, as you will have single-cycle resolution. In
contrast, micros() has only 4 µs resolution (64 times worse) and
the ISR may be delayed by up to ≈ 16 µs by the TIMER0_OVF
ISR.
You can use the FreqPeriod library you linked to as an inspiration for
writing your own timer-based code, but it will require some changes:

As pointed out by Nick Gammon in a comment, you don't need the analog
comparator, nor the conditioning RC network, as the encoder's outputs
are already digital. Or you may use a low-pass filter if the encoder
is bouncy.
You will use the input capture pins of either timer 4 (digital pin 49)
or timer 5 (digital pin 48). The other input capture pins are not
available on the Mega's pin headers.
You will replace ISR(ANALOG_COMP_vect) by either ISR(TIMER4_CAPT)
or ISR(TIMER5_CAPT) (the relevant “capture event” ISR). No need to
adjust a comparator threshold in the ISR.
In the begin() method, you will leave the analog comparator alone,
and you will enable the capture event interrupt.

Obviously you will have to study the
datasheet
before start coding.

Hold The Pages! I have got the above Nick Gammon sketch working to producing a chain of readings.  Please excuse my lack of comprehension, using this sketch will I get a reading for all pulses? Although I do not seem to get two readings using pulse edge"CHANGE" as apposed to  one reading with pulse edge  "RISING" why is this, am I wrong in my thinking ?  Two readings per pulse period I think should be better than one?  I  still can not comprehend  what would be better for my needs counter or interrupts. Does the Martin Nawrath sketch use interupts or counter ,or both ?

Could this be so?

because the code is faulty: there is no assurance of atomicity between startTime and endTime. ie. the interrupts could have arrived, multiple times, while the if loop is executing.
two ways to fix it:

calculate period in the isr; or
clear endTime once the clock starts in the isr.

While you are doing all those things with those volatile variables in the loop function, the interrupt can still be firing.  If it fires in the middle of a read of startTime or endTime then you get might get part of the variable holding old value and part holding new value and when you put it together it makes garbage.
You need to do a cli() at the beginning of loop to turn off interrupts and quickly make local copies of all those variables and then sei() to turn interrupts back on.  Now you can safely work with the copies you made.


text:
5pt font for Neopixel shield
I have a 5x8 Neopixel shield for my Arduino. I want to display text on it, while it is in "landscape mode", i.e. a only 5pt high text. The default font that is used by the printcommand is 8pt high. How can I load a font with 5pt height into my code?
I understand that the Neopixel library depends on Adafruit GFX, which allows for different fonts. But changing the font according to the Adafruit tutorial on GFX to one of the supplied fonts does not return any readable text (only a moving line of dots). I found this font converter and used it to produce a 5pt font, but again only a moving dot appears.
This is my code (basically the Neomatrix example with modified orientation of the matrix):
// Adafruit_NeoMatrix example for single NeoPixel Shield.
// Scrolls 'Howdy' across the matrix in a portrait (vertical) orientation.

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

#define PIN 6

Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(8, 5, PIN,
  NEO_MATRIX_TOP     + NEO_MATRIX_LEFT+
  NEO_MATRIX_ROWS + NEO_MATRIX_PROGRESSIVE,
  NEO_GRBW  + NEO_KHZ800);

const uint16_t colors[] = {
  matrix.Color(255, 0, 0), matrix.Color(0, 255, 0), matrix.Color(0, 0, 255) };

void setup() {
  matrix.setFont(&Dialog_plain_5);
  matrix.begin();
  matrix.setTextWrap(false);
  matrix.setBrightness(30);
  matrix.setTextColor(colors[0]);
}

int x    = matrix.width();
int pass = 0;

void loop() {
  matrix.fillScreen(0);
  matrix.setCursor(x, 0);
  matrix.print(F("Howdy"));
  if(--x < -36) {
    x = matrix.width();
    if(++pass >= 3) pass = 0;
    matrix.setTextColor(colors[pass]);
  }
  matrix.show();
  delay(100);
}

and this is the content of the font file:
// Created by http://oleddisplay.squix.ch/ Consider a donation
// In case of problems make sure that you are using the font file with the correct version!
const uint8_t Dialog_plain_5Bitmaps[] PROGMEM = {

    // Bitmap Data:
    0x00, // ' '
    0xF0, // '!'
    0xC0, // '"'
    0x07,0xF2, // '#'
    0x79,0xF4, // '$'
    0xD1,0x10,0xB0, // '%'
    0x88,0xCA, // '&'
    0x80, // '''
    0x2A,0x00, // '('
    0x15,0x00, // ')'
    0x08,0x00, // '*'
    0x01,0x1C,0x40, // '+'
    0x00, // ','
    0xC0, // '-'
    0x00, // '.'
    0x6A,0x00, // '/'
    0xD6,0xE0, // '0'
    0xC9,0x20, // '1'
    0x62,0x48, // '2'
    0xE8,0xE0, // '3'
    0x26,0x62, // '4'
    0x08,0x90, // '5'
    0x7A,0xE0, // '6'
    0x25,0x20, // '7'
    0xEA,0xE0, // '8'
    0xD5,0xE0, // '9'
    0x00, // ':'
    0x00, // ';'
    0x02,0xC6, // '<'
    0x77, // '='
    0x06,0x16, // '>'
    0xD0, // '?'
    0x27,0xB7,0x66,0x00, // '@'
    0x4A,0x68, // 'A'
    0xFA,0xD0, // 'B'
    0x68,0x86, // 'C'
    0xE9,0x9A, // 'D'
    0xDA,0x40, // 'E'
    0x9A,0x40, // 'F'
    0x78,0xB5, // 'G'
    0xBE,0xD0, // 'H'
    0xF0, // 'I'
    0x55,0x40, // 'J'
    0xAC,0xCA, // 'K'
    0x92,0x40, // 'L'
    0x9F,0xF9, // 'M'
    0xBF,0xD0, // 'N'
    0x69,0x96, // 'O'
    0xF7,0x40, // 'P'
    0x69,0x96,0x00, // 'Q'
    0xEA,0xCA, // 'R'
    0x91,0x60, // 'S'
    0x21,0x08,0x40, // 'T'
    0xB6,0xE0, // 'U'
    0xAA,0xA4, // 'V'
    0xAF,0xBC,0xA0, // 'W'
    0xA4,0x4A, // 'X'
    0x53,0x08,0x40, // 'Y'
    0x64,0x88, // 'Z'
    0xAA,0x80, // '['
    0xAA,0x40, // '\'
    0x55,0x40, // ']'
    0x61, // '^'
    0x70, // '_'
    0x00, // '`'
    0xDE,0x80, // 'a'
    0x9A,0xE0, // 'b'
    0x92,0x00, // 'c'
    0x3E,0xD0, // 'd'
    0xDE,0x00, // 'e'
    0x49,0x20, // 'f'
    0xF6,0xA0, // 'g'
    0x9E,0xD0, // 'h'
    0xF0, // 'i'
    0x55,0x40, // 'j'
    0x9A,0x60, // 'k'
    0xF0, // 'l'
    0xFD,0x6A, // 'm'
    0xF6,0x80, // 'n'
    0xD7,0x00, // 'o'
    0xD7,0x40, // 'p'
    0xF6,0xB0, // 'q'
    0x2A, // 'r'
    0x4C,0x80, // 's'
    0x49,0x20, // 't'
    0x16,0xD0, // 'u'
    0xB9,0x00, // 'v'
    0xD7,0x60, // 'w'
    0xCB,0x00, // 'x'
    0xB9,0x40, // 'y'
    0x68, // 'z'
    0x4A,0x24, // '{'
    0xF8, // '|'
    0x48,0xA4 // '}'
};
const GFXglyph Dialog_plain_5Glyphs[] PROGMEM = {
// bitmapOffset, width, height, xAdvance, xOffset, yOffset
      {     0,   1,   1,   3,    0,    0 }, // ' '
      {     1,   1,   4,   3,    0,   -4 }, // '!'
      {     2,   2,   2,   3,    0,   -4 }, // '"'
      {     3,   4,   4,   5,    0,   -4 }, // '#'
      {     5,   3,   5,   4,    0,   -4 }, // '$'
      {     7,   5,   4,   6,    0,   -4 }, // '%'
      {    10,   4,   4,   5,    0,   -4 }, // '&'
      {    12,   1,   2,   2,    0,   -4 }, // '''
      {    13,   2,   5,   3,    0,   -4 }, // '('
      {    15,   2,   5,   3,    0,   -4 }, // ')'
      {    17,   3,   3,   4,    0,   -4 }, // '*'
      {    19,   5,   4,   6,    0,   -4 }, // '+'
      {    22,   2,   3,   3,    0,   -2 }, // ','
      {    23,   2,   1,   3,    0,   -2 }, // '-'
      {    24,   2,   1,   3,    0,   -1 }, // '.'
      {    25,   2,   5,   3,    0,   -4 }, // '/'
      {    27,   3,   4,   4,    0,   -4 }, // '0'
      {    29,   3,   4,   4,    0,   -4 }, // '1'
      {    31,   4,   4,   4,    0,   -4 }, // '2'
      {    33,   3,   4,   4,    0,   -4 }, // '3'
      {    35,   4,   4,   5,    0,   -4 }, // '4'
      {    37,   3,   4,   4,    0,   -4 }, // '5'
      {    39,   3,   4,   4,    0,   -4 }, // '6'
      {    41,   3,   4,   4,    0,   -4 }, // '7'
      {    43,   3,   4,   4,    0,   -4 }, // '8'
      {    45,   3,   4,   4,    0,   -4 }, // '9'
      {    47,   2,   3,   3,    0,   -3 }, // ':'
      {    48,   2,   4,   3,    0,   -3 }, // ';'
      {    49,   4,   4,   5,    1,   -4 }, // '<'
      {    51,   4,   2,   5,    0,   -3 }, // '='
      {    52,   4,   4,   5,    0,   -4 }, // '>'
      {    54,   2,   4,   4,    0,   -4 }, // '?'
      {    55,   5,   5,   6,    0,   -4 }, // '@'
      {    59,   4,   4,   4,    0,   -4 }, // 'A'
      {    61,   3,   4,   4,    0,   -4 }, // 'B'
      {    63,   4,   4,   4,    0,   -4 }, // 'C'
      {    65,   4,   4,   5,    0,   -4 }, // 'D'
      {    67,   3,   4,   4,    0,   -4 }, // 'E'
      {    69,   3,   4,   4,    0,   -4 }, // 'F'
      {    71,   4,   4,   5,    0,   -4 }, // 'G'
      {    73,   3,   4,   4,    0,   -4 }, // 'H'
      {    75,   1,   4,   2,    0,   -4 }, // 'I'
      {    76,   2,   5,   2,   -1,   -4 }, // 'J'
      {    78,   4,   4,   4,    0,   -4 }, // 'K'
      {    80,   3,   4,   4,    0,   -4 }, // 'L'
      {    82,   4,   4,   5,    0,   -4 }, // 'M'
      {    84,   3,   4,   4,    0,   -4 }, // 'N'
      {    86,   4,   4,   5,    0,   -4 }, // 'O'
      {    88,   3,   4,   4,    0,   -4 }, // 'P'
      {    90,   4,   5,   5,    0,   -4 }, // 'Q'
      {    93,   4,   4,   4,    0,   -4 }, // 'R'
      {    95,   3,   4,   5,    1,   -4 }, // 'S'
      {    97,   5,   4,   4,   -1,   -4 }, // 'T'
      {   100,   3,   4,   4,    0,   -4 }, // 'U'
      {   102,   4,   4,   4,    0,   -4 }, // 'V'
      {   104,   5,   4,   6,    0,   -4 }, // 'W'
      {   107,   4,   4,   4,    0,   -4 }, // 'X'
      {   109,   5,   4,   4,   -1,   -4 }, // 'Y'
      {   112,   4,   4,   6,    1,   -4 }, // 'Z'
      {   114,   2,   5,   3,    0,   -4 }, // '['
      {   116,   2,   5,   3,    0,   -4 }, // '\'
      {   118,   2,   5,   3,    0,   -4 }, // ']'
      {   120,   4,   2,   5,    0,   -4 }, // '^'
      {   121,   4,   1,   4,   -1,    1 }, // '_'
      {   122,   2,   1,   4,    0,   -4 }, // '`'
      {   123,   3,   3,   5,    1,   -3 }, // 'a'
      {   125,   3,   4,   4,    0,   -4 }, // 'b'
      {   127,   3,   3,   4,    0,   -3 }, // 'c'
      {   129,   3,   4,   4,    0,   -4 }, // 'd'
      {   131,   3,   3,   5,    1,   -3 }, // 'e'
      {   133,   3,   4,   3,   -1,   -4 }, // 'f'
      {   135,   3,   4,   4,    0,   -3 }, // 'g'
      {   137,   3,   4,   4,    0,   -4 }, // 'h'
      {   139,   1,   4,   2,    0,   -4 }, // 'i'
      {   140,   2,   5,   2,   -1,   -4 }, // 'j'
      {   142,   3,   4,   4,    0,   -4 }, // 'k'
      {   144,   1,   4,   2,    0,   -4 }, // 'l'
      {   145,   5,   3,   6,    0,   -3 }, // 'm'
      {   147,   3,   3,   4,    0,   -3 }, // 'n'
      {   149,   3,   3,   4,    0,   -3 }, // 'o'
      {   151,   3,   4,   4,    0,   -3 }, // 'p'
      {   153,   3,   4,   4,    0,   -3 }, // 'q'
      {   155,   2,   4,   3,    0,   -4 }, // 'r'
      {   156,   3,   3,   5,    0,   -3 }, // 's'
      {   158,   3,   4,   3,   -1,   -4 }, // 't'
      {   160,   3,   4,   4,    0,   -4 }, // 'u'
      {   162,   3,   3,   4,    0,   -3 }, // 'v'
      {   164,   4,   3,   5,    0,   -3 }, // 'w'
      {   166,   3,   3,   4,    0,   -3 }, // 'x'
      {   168,   3,   4,   4,    0,   -3 }, // 'y'
      {   170,   2,   3,   5,    1,   -3 }, // 'z'
      {   171,   3,   5,   4,    0,   -4 }, // '{'
      {   173,   1,   6,   2,    0,   -4 }, // '|'
      {   174,   3,   5,   4,    0,   -4 } // '}'
};
const GFXfont Dialog_plain_5 PROGMEM = {
(uint8_t  *)Dialog_plain_5Bitmaps,(GFXglyph *)Dialog_plain_5Glyphs,0x20, 0x7E, 7};

I was having the same problem until I read the library source code. Later I found the documentation reference.
The classic font cursor position is defined as the top-left corner of the character cell. For GFX and custom fonts it is the 'y' position is relative to the baseline of the character cell.
My display is 5 by 5. The TomThumb font is 3 by 5. Instead of matrix.setCursor(x, 0); I needed to use matrix.setCursor(x, 5); so the 'y' coordinate corresponds with the bottom of the pixel matrix, not the top.
It's described in Adafruit's docs.


text:
Arduino interrupt not called using PinChangeInterrupt
I am new to Arduino and I was trying to figure out how to use an interrupt. When I ran this it would read my magnet but the interrupt would never be called and I couldn't figure out if anyone can help me that would be great.
Thanks.
Here is the code
#include <PinChangeInterrupt.h>

//#define INTERRUPT_PIN 12
#include <Math.h>

#define RADIUS 3
const int hallPin = 7; // the number of the hall effect sensor pin
const int ledPin =  13; // the number of the LED pin
// variables will change:
int hallState = 0; // variable for reading the hall sensor status
double inital_val = 0.0;
double distance = inital_val;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  pinMode(hallPin, INPUT);
  //attachInterrupt(hallPin, calc_distance, HIGH);
  // initialize the hall effect sensor pin as an input:
  attachInterrupt(digitalPinToInterrupt(hallPin), calc_distance , HIGH);
  Serial.begin(9600);
}

void loop() {
  //read the state of the hall effect sensor:
  hallState = digitalRead(hallPin);
  if (hallState == LOW) {
    // turn LED on:
    Serial.print("Main Loop: HallState LOW\n");
    digitalWrite(ledPin, HIGH);
    Serial.print(distance, 2);
    Serial.print("\n");
  } else {
    Serial.print("Main Loop: HallState HIGH\n");
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

void calc_distance() {
  Serial.print("INTERRUPT! \n");
  if (digitalRead(hallPin) == HIGH) {
    Serial.print("YES!\n");
    distance += PI * 2 * RADIUS;
  } else {
    Serial.print("NO!\n");
  }
}

Are you sure hallPin=7 has an interrupt on your particular board?  Unos interrupt on 2,3 only.

The attachInterrupt function is only for normal interrupts. Read the reference: attachInterrupt
When you need the Pin Change Interrupts, there is a library for that: EnableInterrupt
Try to keep the interrupt routine as short as possible. Do not use the Serial functions in calc_distance because the Serial functions themself use also interrupts.
The Arduino Mega does not have 'double' floating point variables, the compiler changes it into 32-bit 'float' variables. You are reading the interrupt pin for a test ? I don't understand why you do that. Please make "distance" a volatile variable. In the loop function, the interrupts should be turned off when reading "distance". Because "distance" is a 4 bytes 'float' variable and the Arduino Mega is a 8-bits microcontroller. An interrupt could occur when the "distance" is only read for a part from memory.

Yes to moving the serial stuff out of the interrupt, but attachInterrupt should be able to handle pin changes just fine.  Maybe  attachInterrupt(digitalPinToInterrupt(hallPin),calc_distance , RISING);  or attachInterrupt(digitalPinToInterrupt(hallPin),calc_distance , CHANGE); would be better than whenever it is HIGH.

The attachInterrupt function is only for pin 2 and 3 for an Arduino Uno, according to the reference. Because it uses the normal interrupts. The special "Pin Change Interrupt" (PCINT) requires specific code or a library. When a library is used, the functions from that library should be used for the interrupt. This code seems to use a little of both.


text:
Slackbot integration using ESP8266 gets "ssl->need_bytes=16432 > 6859"
I'm trying to use Uri Shaked Slackbot code using an Adafruit Feather Huzzah ESP8266 WiFi.
I have created the Slackbot integration and copied the API key. The code connects to the WiFi and does the time configuration but then hangs when connecting to slack with the error message in the serial monitor.

ssl-need_bytes=16432 > 6859

/**
   Arduino Real-Time Slack Bot
   Copyright (C) 2016, Uri Shaked.
   Licensed under the MIT License
*/

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include <Adafruit_NeoPixel.h>

#define SLACK_SSL_FINGERPRINT "AC 95 5A 58 B8 4E 0B CD B3 97 D2 88 68 F5 CA C1 0A 81 E3 6E" // If Slack changes their SSL fingerprint, you would need to update this
#define SLACK_BOT_TOKEN "https://slack.com/api/rtm.start?token=[MY TOKEN]" // Get token by creating new bot integration at https://my.slack.com/services/new/bot
#define WIFI_SSID       "[My WIFI]"
#define WIFI_PASSWORD   "[WiFi Password]"

#define LEDS_PIN        2
#define LEDS_NUMPIXELS  8
#define WORD_SEPERATORS "., \"'()[]<>;:-+&?!\n\t"

ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;

Adafruit_NeoPixel pixels(LEDS_NUMPIXELS, LEDS_PIN, NEO_GRB + NEO_KHZ800);

long nextCmdId = 1;
bool connected = false;

/**
  Sends a ping message to Slack. Call this function immediately after establishing
  the WebSocket connection, and then every 5 seconds to keep the connection alive.
*/
void sendPing() {
  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["type"] = "ping";
  root["id"] = nextCmdId++;
  String json;
  root.printTo(json);
  webSocket.sendTXT(json);
}

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

/**
  Animate a NeoPixel ring color change.
  Setting `zebra` to true skips every other led.
*/
void drawColor(uint32_t color, bool zebra) {
  int step = zebra ? 2 : 1;
  for (int i = 0; i < LEDS_NUMPIXELS; i += step) {
    pixels.setPixelColor(i, color);
    pixels.show();
    delay(30 * step);
  }
}

/**
  Draws a rainbow :-)
*/
void drawRainbow(bool zebra) {
  int step = zebra ? 2 : 1;
  for (int i = 0; i < LEDS_NUMPIXELS; i += step) {
    pixels.setPixelColor(i, wheel(i * 256 / LEDS_NUMPIXELS));
    pixels.show();
    delay(30 * step);
  }
}

/**
  Looks for color names in the incoming slack messages and
  animates the ring accordingly. You can include several
  colors in a single message, e.g. `red blue zebra black yellow rainbow`
*/
void processSlackMessage(char *payload) {
  char *nextWord = NULL;
  bool zebra = false;
  for (nextWord = strtok(payload, WORD_SEPERATORS); nextWord; nextWord = strtok(NULL, WORD_SEPERATORS)) {
    if (strcasecmp(nextWord, "zebra") == 0) {
      zebra = true;
    }
    if (strcasecmp(nextWord, "red") == 0) {
      drawColor(pixels.Color(255, 0, 0), zebra);
    }
    if (strcasecmp(nextWord, "green") == 0) {
      drawColor(pixels.Color(0, 255, 0), zebra);
    }
    if (strcasecmp(nextWord, "blue") == 0) {
      drawColor(pixels.Color(0, 0, 255), zebra);
    }
    if (strcasecmp(nextWord, "yellow") == 0) {
      drawColor(pixels.Color(255, 160, 0), zebra);
    }
    if (strcasecmp(nextWord, "white") == 0) {
      drawColor(pixels.Color(255, 255, 255), zebra);
    }
    if (strcasecmp(nextWord, "purple") == 0) {
      drawColor(pixels.Color(128, 0, 128), zebra);
    }
    if (strcasecmp(nextWord, "pink") == 0) {
      drawColor(pixels.Color(255, 0, 96), zebra);
    }
    if (strcasecmp(nextWord, "orange") == 0) {
      drawColor(pixels.Color(255, 64, 0), zebra);
    }
    if (strcasecmp(nextWord, "black") == 0) {
      drawColor(pixels.Color(0, 0, 0), zebra);
    }
    if (strcasecmp(nextWord, "rainbow") == 0) {
      drawRainbow(zebra);
    }
    if (nextWord[0] == '#') {
      int color = strtol(&nextWord[1], NULL, 16);
      Serial.println("Color");
      Serial.print(color);
      if (color) {
        drawColor(color, zebra);
      }
    }
  }
}

/**
  Called on each web socket event. Handles disconnection, and also
  incoming messages from slack.
*/
void webSocketEvent(WStype_t type, uint8_t *payload, size_t len) {
  switch (type) {
    case WStype_DISCONNECTED:
      Serial.printf("[WebSocket] Disconnected :-( \n");
      connected = false;
      break;

    case WStype_CONNECTED:
      Serial.printf("[WebSocket] Connected to: %s\n", payload);
      sendPing();
      break;

    case WStype_TEXT:
      Serial.printf("[WebSocket] Message: %s\n", payload);
      processSlackMessage((char*)payload);
      break;
  }
}

/**
  Establishes a bot connection to Slack:
  1. Performs a REST call to get the WebSocket URL
  2. Conencts the WebSocket
  Returns true if the connection was established successfully.
*/
bool connectToSlack() {
  // Step 1: Find WebSocket address via RTM API (https://api.slack.com/methods/rtm.start)
  HTTPClient http;

  Serial.printf("Connecting to\n");
  Serial.printf(SLACK_BOT_TOKEN);
  Serial.printf("\n");

  http.begin(SLACK_BOT_TOKEN, SLACK_SSL_FINGERPRINT);
  int httpCode = http.GET();

  if (httpCode != HTTP_CODE_OK) {
    Serial.printf("HTTP GET failed with code %d\n", httpCode);
    return false;
  }

  pixels.setPixelColor(3, pixels.Color(0, 2, 0));
  pixels.show();

  WiFiClient *client = http.getStreamPtr();
  client->find("wss:\\/\\/");
  String host = client->readStringUntil('\\');
  String path = client->readStringUntil('"');
  path.replace("\\/", "/");

  // Step 2: Open WebSocket connection and register event handler
  Serial.println("WebSocket Host=" + host + " Path=" + path);
  webSocket.beginSSL(host, 443, path, "", "");
  webSocket.onEvent(webSocketEvent);

  pixels.setPixelColor(4, pixels.Color(0, 2, 0));
  pixels.show();

  return true;
}

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);

  pixels.begin();
  drawColor(pixels.Color(2, 0, 0), false);

  pixels.setPixelColor(0, pixels.Color(0, 2, 0));
  pixels.show();

  WiFiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
  while (WiFiMulti.run() != WL_CONNECTED) {
    delay(100);
  }

  pixels.setPixelColor(1, pixels.Color(0, 2, 0));
  pixels.show();

  configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");

  pixels.setPixelColor(2, pixels.Color(0, 2, 0));
  pixels.show();
}

unsigned long lastPing = 0;

/**
  Sends a ping every 5 seconds, and handles reconnections
*/
void loop() {
  webSocket.loop();

  if (connected) {
    // Send ping every 5 seconds, to keep the connection alive
    if (millis() - lastPing > 5000) {
      sendPing();
      lastPing = millis();
    }
  } else {
    // Try to connect / reconnect to slack
    connected = connectToSlack();
    if (!connected) {
      delay(500);
    }
  }
}

they probably use "too strong" of a cert, according to https://github.com/esp8266/Arduino/issues/1375. you can use a server-side proxy to talk to both the ESP and the API, using a shorter key cert on the "proxy"

Yep, I read igrr's comment. I've downloaded the axTLS library and are trying to tweak it to get it working but no luck so far.

@mach I have this exact same issue.  I do get mine to connect sometimes, but it's very inconsistent (sometimes it works, sometimes it fails).  Once it connects and I get to the repeated pings it works perfectly.  Did you find a solution for the ssl-need_bytes error?

@mach @Axel
I replaced use rtm.start with rtm.connect as per April 2017 Slack Recent Updates https://api.slack.com/changelog
and this got rid of the error on my Wemos.
http.begin("https://slack.com/api/rtm.connect?token=" + SLACK_BOT_TOKEN, SLACK_SSL_FINGERPRINT);

OMG, going to test this tonight!


text:
Can regular Arduino pins be used during SPI?
I have a circuit in which I'm using an Arduino Pro Mini to interface with an RF69 radio via SPI. The SCK pin on the Pro Mini is pin 13, which also happens to be the LED pin. Is it possible to write pin 13 high and low in the same sketch that I'm interfacing with the radio? I don't need to do SPI communication simultaneously with the LED. I can put the radio to sleep then use the LED. I'm wondering if this will some how mess up the SPI communication or if everything will be OK.

probably, but just try it, it won't zap anything...

You need to disable SPI before you use digitalWrite on the SPI pins, or nothing will happen! Then re-enable SPI when you start communication again.

I did not check the datasheet of the RF69, but it is customary for SPI devices to have a “slave select” input pin. When such a device is not selected, it will leave its MISO pin in high impedance and completely ignore whatever may happen on the MOSI and SCK pins. This effectively disconnects the device from the SPI bus. In this situation you show be able to play with the LED without disturbing the device.
Beware that the slave select pin is usually active low: write it to HIGH to deselect the device.

Great, thank you. This is exactly what I needed.


text:
USB and Arduino: Power Arduino, charge LiPo, and transfer data at the same time
I was hoping to design my own Arduino board for a recent project of mine, a portable project that was powered by a 3.7 LiPo battery. Most ideally, I wanted to replace the USB B port with a single USB Micro port that implements the following features:

Provides power to the Arduino while it is plugged in (just like a regular Arduino does).
Connect the D+ and D- pins of the USB to the Arduino somehow to allow for on-board programming (however the Arduino accomplishes this already, I'll refer to this as the "onboard usb/serial converter"). I want it to keep it programmable on-the-go.
Charges an on-board 3.7V LiPo Battery. I was hoping to use Adafruit's PowerBoost 500 Shield as a reference for my schematic.

However, I haven't been able to find a schematic or example that implements all 3 features above at the same time from the same USB port. I don't have much experience with charging circuits, so the following questions might sound dumb. Below are some solutions I was thinking of that probably won't work, but I wanted to make sure:

Connect the Output Voltage of the LiPo Battery to the V+/GND supply of the USB cable (probably not safe to connect all V+ sources together).
Just connect the D+/- data cables to the "onboard usb/serial converter" without connecting the Vbat/Vusb somehow, have the USB V+/GND connect to the LiPo charging circuit, and the Battery Voltage power the Arduino.

I know some devices have this charging/data-transfer functionality (e.g. my phone can transfer photos to my computer while being powered on and charging at the same time), but I'm wondering how it's possible to have similar functionality for an Arduino board. Any advice?
Absolute worst case, I'll just have 2 USB ports, one for charging the LiPo and one for Serial Communication/Programming
EDIT: The idea of using an ATMega32U4 seems appealing (despite the 3.3V vs 5V operating voltage), mainly because it has a pin for VBUS for USB and Vcc for main power. But I was wondering how to do this on say an ATMega328P that doesn't have a pin for VBUS.

Arduino Lilypad USB does power, charging, data through the same USB connector.  I've created a derivative work based on Lilypad USB recently.  It worked well.

just wire the micro usb to an "ftdi", the ftdi to the MCU, and the ftdi's power pass though pin (5v) to a lithium charging board (about 50 cents); and bob's your uncle;  all three for under $2...

I'd recommend using the Arduino Leonardo as a reference for your circuit. Its pretty much the same as an Arduino UNO but has a built in USB interface so you don't need the USB-Serial converter.
I'd also recommend running the chip at 3.3V. That way you can use a linear regulator to regulate the 3.7V battery voltage down. Otherwise you'd need a boost converter to bump the voltage up to 5V which needs more parts.
If you follow those recommendations then all you will need is a LiPo charging IC to handle the charging. You'll need to add an ISCP header to flash the initial Leonardo bootloader, but after that you can use USB and the Arduino IDE to program it.
I did exactly this for a school project a while back. You can find the schematics here: https://github.com/seanwatson/ece4416-project/blob/master/hardware/rev2/sw-4416-project-v2-sch.pdf

Hmm, I was hoping to avoid using an ATMega32U4 because I don't have much SMD Soldering experience. But it seems like it has a pin for USB power AND a separate Vcc power? That looks awfully convenient! I will give this a try

The presence of those two pins does not mean that they are dual inputs and the chip will run off of whichever is powered; they have specific purposes.

Personally I'd avoid using a linear regulator on a battery powered system... Losing 25% of the energy stored just to heat the regulator is not very efficient. In any case I second the 3.3V suggestion: with a simple buck regulator (even already pre-soldered in modules like the ones sold on ebay at around 1$) you get more efficiency than with a boost regulator and a 3.3V uC consumes less power

Oh, sorry for the necroposting. I didn't notice that this was a very old post that was bumped because @GeorgeTroulis didn't accept an answer...

@frarugi87 it's ok, the reason I haven't accepted an answer yet is because I never actually tried any of these solutions yet :| Should I still accept one of these solutions? Because they are all so good! Thank you for your feedback :)

Use a TP4056 1A LiPo charger board (it has overdischarge protection) and a boost converter, like the XL6009. It will run you at most 5$ if you are prudent. Overdischarge protection is important.
If you want a port for programming, add a micro-USB breakout board, and if necessary a pushbutton for bringing RST down to GND. I prefer just having GND, TX, RX pins on a 3 pin header, and plugging my cable into that.

Following on from Sean Watson's answer, I would probably use the Bare Conductive Touch Board as your reference. It's a Leonardo derivative with all the features you're asking for. Full disclosure - I work at Bare Conductive and worked on the design of the board.
Eagle schematic and board file are here. Also, since this board successfully passed CE and FCC radiated emissions and immunity testing, you know that the reference design is sound for this if you want to create a product to sell.
The design uses a boost converter to allow for 5V operation - if you run the Atmega32u4 (or Atmega328) at 3.3V, you don't get guaranteed correct operation with a 16 MHz clock (check the data sheet). Since the Arduino bootloader for the Leonardo is written for a 16 MHz clocked MCU, this saves you the task of modifying the bootloader - and gives you the full 16 MIPS maximum performance.

How do you mean "at 3. V, you don't get guaranteed correct operation with a 16 MHz clock"? Looking at section 29.3 of the Atmel datasheet, it's hard to distinguish that 3.3V @ 16 MHz is in the safe operating area, but since the Arduino Leonardo already works at 16 MHz, doesn't that mean it's "guaranteed"? I'm guessing you mean that if I buy my own 32U4, I'll have to modify the bootloader to get guaranteed 16 MIPS performance (with an external 16 MHz Oscillator of course)?

The Leonardo works with a 5V VCC (take a look at the schematics) - so you can't be sure that 3.3V operation is guaranteed from that. Looking at this datasheet I can see that 3.3V is clearly NOT in the Safe Operating Area - it's section 29.6 here. Also there is a typo above - the curve is clearly linear between 2.7V < VCC < 4.5V, not 2.7V < VCC < 5.5V as written.

Oh my bad, I was looking at the datasheet for the ATMega328P, which does not include the 32U4. Also how silly of me, I was under the impression that the Leonardo operated at 3.3 V (what is wrong with me?). Perhaps using a boost converter for 5V operation then is my best option if I want 16 MHz guaranteed. I might be willing to go 8 MHz though, just to avoid the boost converter. I don't think my project will be affected, and it seems to be what the lilypad does


text:
Compiling code via terminal
How can I compile my code via terminal? I am working on a Chrome app that allows you to write, compile, and upload code to an Arduino, and I need to know this so I can use the command line compiler on my Linux server. Mac or Linux terminal, it doesn't matter.

I'm not really sure what exactly you need but to compile in the command line you need something like avr-gcc.

Check out platformio.org it's the best solution out there for command line compiling.

See my answer to a related question for an example PlatformIO CLI session.

Assuming an AVR-based Arduino, you would need the avr-gcc compiler, the
avr-libc and the Arduino libraries. Also avrdude if you want to upload.
The only issue is that the commands used for the build process are quite
long (lots of options). You can see them by enabling verbose compilation
in the IDE. Thus you will probably want some way to automate the whole
thing.
There are several options for this. The most straightforward seems to be
the arduino-builder command-line tool. This is part of the Arduino
project and should ensure maximum compatibility. Otherwise you could use
a plain old Makefile. I personally use Sudar Muthu' Makefile. It can
be installed on a Debian-based Linux distribution by:
sudo apt install arduino-mk

It is not fully compatible with the classic Arduino build process
though: it does automatically include <Arduino.h> into your sketch,
but it does not add forward declarations. Some prefer it this way, as
the automatic inclusion of forward declarations is somewhat buggy and
does not play well with some C++ features.

There is an Arduino CLI (command line interface):
https://github.com/arduino/arduino-cli
You use commands such as to access Arduino IDE functions:
arduino-cli compile --fqbn arduino:avr:leonardo sketch
and
arduino-cli upload -pCOM14 --fqbn arduino:avr:leonardo sketch
(obviously port will be different under Linux)

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


text:
Can the Arduino be hurt by connecting too many LEDs in serial?
Today I learned about Vf for leds, after founding out that 3 leds in series driven by 5 V did not make them light up while 2 did.
However, I also read that it is quite bad for a power source to use more volts (like 3 times 2V) this way than the power source (5V for the Uno).
Can the Arduino be hurt this way?

The Arduino can only supply a few tens of ma for each output pin, so as a practical matter you present it with an open circuit when you string along too many.  Essentially the same as having nothing connected to the pin at all.  That won't hurt the Arduino, no.

@Downvoter, can you instead of downvoting all my posts, explain WHY you downvoted, so I may improve the post.

The forward voltage of an LED or diode is the applied voltage of the "knee" in the exponential characteristic at which it starts to substantially conduct, and in the case of an LED, produce light.
It is not, under ordinary circumstances of indicator-type LEDs, a voltage that would be produced internally to the LEDs, at least not with any substantial current capability.
As long as you are supplying the LEDs from a voltage within the Arduino's I/O range, it should not be hurt by a series strings of too many LEDs.  However, in theory (if rarely in practice) a series string of too few LEDs that did not include a current limiting resistor would stress the Arduino beyond its ratings - and possibly (and more commonly) also the LED(s) beyond their current limits.

Thank you very much  ... about your last paragraph ... I already found that out ... luckily by only destroying one LED and not my Arduino.

Placing 3 "typical" LEDs in series and then driving them with the Arduino will not produce any light because the Arduino can only output 5V on any pin.  It would require approx 6 volts to drive current through the LEDs when connected in series.  This is for typical green, yellow, red type LEDs that have a 2 volt or so forward voltage drop. Note: some other colors require more forward voltage.
When you place two of these LEDs in series the forward voltage drop required to light them is only about 4 volts, that's why they light up when 3 in series didn't.  However, since the Arduino outputs 5 volts on its pin and the LEDs only require 4 volts the extra 1 volt can cause more current to flow which, if excessive, can damage the output pin.  Thats why when driving LEDs in this way its usually a good practice to place a current limiting resistor in series with the LED(s).  This resistor limits the current induced by any driving voltage which is over the voltage needed to drive the LEDs to conduction.