text:
AVR timer overflow interrupt not working
My problem is an interrupt service routine (ISR) that seemingly never executes! Here's some info on my set up: I am flashing an avr attiny85. I have the bare bones of a project set up so far with simply a main.c and two modules: timer and hardwareInit. In the timer module, I have a timer0_init function that I am using to set up timer0 for CTC mode to overflow ever 1 ms. Here is the function:
void timer0_init( void )
{
    cli();
    TCCR0B |= 3;    //clock select is divided by 64.
    TCCR0A |= 2;    //sets mode to CTC
    OCR0A = 0x7C;   //sets TOP to 124 so the timer will overflow every 1 ms.
    TIMSK |= 2;     //Enable overflow interrupt
    sei();          //enable global interrupts
}

with the timer set up, I added an ISR to increment ticks every time the counter overflows, so I can keep track of how much time has elapsed, etc.
ISR(TIMER0_OVF_vect)
{
    cli();
    //ticks ++;
    PORTB |= ( 1 << PORTB0 );
    sei();
}

as you can see, I commented out the ticks++ because it wasn't working, and replaced it with PORTB |= ( 1 << PORTB0 ); which simply turns on an LED, so if the interrupt is ever executed, I will know by proof of the LED being on.
Unfortunately, I can't get it to turn on and can't see what I'm missing. (to prove that I 1. have the LED set up on the right pin, and 2. am manipulating the correct bit in the correct register, I put just this statement PORTB |= ( 1 << PORTB0 ); in my infinite loop and confirmed the LED came on)
For further explanation, here is my main.c:
/*================================= main.c =================================*/

#define F_CPU   8000000UL

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#include "timer.h"
#include "hardwareInit.h"

int main(){

    //Initialize hardware HERE
    DDRB |= ( 1 << PORTB0 );    //set this pin as an output for an LED

    SetClockPrescale(1);    //internal clock divided by 1 = 8 MHz, from hardwareInit

    timer0_init();          //set up timer0 for 1 ms overflow

    while(1)
    {
        /* if( getTicks() > 0 )
        {
            PORTB |= ( 1 << PORTB0 );
            _delay_ms(1000);
            PORTB &= ~( 1 << PORTB0 );
            _delay_ms(1000);
        } */

    }
    return 0;
}

So, what you see in the infinite loop is what I tried first, but after that didn't work, I tried something simpler, just having an empty loop (commented out previous stuff), and waiting for the interrupt to get triggered which would turn on the LED.
Any help you could give would be really appreciated. I'm quite puzzled why this hasn't been working.

None of this is Arduino.

cli() and sei() are useless in your ISR as interrupts are automatically disabled at ISR start and re-enabled on return.

@jfpoilpret Thank you!  I was told that it was a good practice to disable and then re-enable interrupts in an ISR so you don't have interrupts interrupting your ISR.   Can you point me to a source that says ISR does that automatically?

Try commenting OCR0 register's value for overflow interrupt to work .Well it worked for me.

You are misunderstanding what an overflow interrupt is. That is called when the timer overflows (ie. it reaches TOP which in the case of an 8-bit timer is 255). Since you are counting to 124 that will never happen, and thus the interrupt will not fire.
You want the "compare A vector" which is called when the "A" register compares to the limit. Example code:
void timer0_init( void )
{
    TCCR0B = bit (CS01) | bit (CS00);    //clock select is divided by 64.
    TCCR0A = bit (WGM01);     //sets mode to CTC
    OCR0A = 0x7C;             //what to count to
    TIMSK = bit (OCIE0A);     //Enable compare match A interrupt
}

ISR(TIMER0_COMPA_vect)
{
    PINB = bit (PINB0);   // toggle pin 5
}

int main(){

    DDRB |= bit (DDB0);    //set this pin as an output for an LED
    timer0_init();         //set up timer0 for 1 ms overflow
    sei ();                // allow interrupts
    while(true) { }        // forever
    return 0;
}

I changed it to toggle pin 5 (which happens extremely quickly) so it will seem to be on but a bit dim. You can see on an oscilloscope or logic analyzer that it is toggling rapidly.
You don't need to turn interrupts off or on inside an ISR. You are better off using the bit names rather than "magic numbers" in your code, as my example shows.

Also note how Nick change TCCR0B |= to TCCR0B =. Since the arduino code uses timer0 for millis, TCCR0B isn't the default value.

Yes, never assume you know what values registers have in them, unless you set them yourself.

Great! I was missing the point of CTC mode. When I set OCR0A to 124, I thought that since the TOP was changed to 124, the timer would overflow when it hit 124. It's now clear to me that overflow is only when the timer reaches the "true" top, in this case 255.  Thanks for your help.

@Gerben and Nick, is it ok to assume the value of the registers when I am flashing the attiny itself, separate from Arduino or anything else that would have already set them?  I was going based off of the datasheet for the attiny85 which shows the initial values of each bit in each register:
http://screencast.com/t/ry9FSpyWQt9

Probably it is. However I don't really see the point of "or"ing in a bit, when in less (or the same) machine cycles you can just set the desired value. If you assign you definitely get what you want, if you "or" you are just hoping.

Please note that the overflow occurs when trying to increment to 256, resulting in 0. Also, it is perfectly fine to use an actual overflow interrupt here, just preload TCNT0 with the diff between TOP and your desired cycles every time the overflow occurs.


text:
I want to modify setup, to also keep the serial USB port opens so I can send strings via a Raspberry Pi
I am trying to modify the original code from these guys GRA & AFCH, who have made an Arduino Sketch Program that runs a Arduino powered Nixie Clock.
Here is the link to their Firmware file:NixieClockShieldNCS314.ino
Here is the specific part I want to modify.

void setup()
{
  digitalWrite(DHVpin, LOW);    // off MAX1771 Driver  Hight Voltage(DHV) 110-220V

  Wire.begin();
  //setRTCDateTime(23,40,00,25,7,15,1);

  Serial.begin(115200);

    if (EEPROM.read(HourFormatEEPROMAddress)!=12) value[hModeValueIndex]=24; else value[hModeValueIndex]=12;
    if (EEPROM.read(RGBLEDsEEPROMAddress)!=0) RGBLedsOn=true; else RGBLedsOn=false;
    if (EEPROM.read(AlarmTimeEEPROMAddress)==255) value[AlarmHourIndex]=0; else value[AlarmHourIndex]=EEPROM.read(AlarmTimeEEPROMAddress);
    if (EEPROM.read(AlarmTimeEEPROMAddress+1)==255) value[AlarmMinuteIndex]=0; else value[AlarmMinuteIndex]=EEPROM.read(AlarmTimeEEPROMAddress+1);
    if (EEPROM.read(AlarmTimeEEPROMAddress+2)==255) value[AlarmSecondIndex]=0; else value[AlarmSecondIndex]=EEPROM.read(AlarmTimeEEPROMAddress+2);
    if (EEPROM.read(AlarmArmedEEPROMAddress)==255) value[Alarm01]=0; else value[Alarm01]=EEPROM.read(AlarmArmedEEPROMAddress);
    if (EEPROM.read(LEDsLockEEPROMAddress)==255) LEDsLock=false; else LEDsLock=EEPROM.read(LEDsLockEEPROMAddress);
    Serial.print("led lock=");
    Serial.println(LEDsLock);

  pinMode(RedLedPin, OUTPUT);
  pinMode(GreenLedPin, OUTPUT);
  pinMode(BlueLedPin, OUTPUT);

  tone1.begin(pinBuzzer);
  song=parseSong(song);

  pinMode(LEpin, OUTPUT);
  pinMode(DHVpin, OUTPUT);

 // SPI setup

  SPI.begin(); //
  SPI.setDataMode (SPI_MODE3); // Mode 3 SPI
  SPI.setClockDivider(SPI_CLOCK_DIV128); // SCK = 16MHz/128= 125kHz

  //buttons pins inits
  pinMode(pinSet,  INPUT_PULLUP);
  pinMode(pinUp,  INPUT_PULLUP);
  pinMode(pinDown,  INPUT_PULLUP);
  ////////////////////////////
  pinMode(pinBuzzer, OUTPUT);

  //buttons objects inits
  setButton.debounceTime   = 20;   // Debounce timer in ms
  setButton.multiclickTime = 30;  // Time limit for multi clicks
  setButton.longClickTime  = 2000; // time until "held-down clicks" register

  upButton.debounceTime   = 20;   // Debounce timer in ms
  upButton.multiclickTime = 30;  // Time limit for multi clicks
  upButton.longClickTime  = 2000; // time until "held-down clicks" register

  downButton.debounceTime   = 20;   // Debounce timer in ms
  downButton.multiclickTime = 30;  // Time limit for multi clicks
  downButton.longClickTime  = 2000; // time until "held-down clicks" register

  //
  //digitalWrite(DHVpin, HIGH); // on MAX1771 Driver  Hight Voltage(DHV) 110-220V
  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  doTest();
  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  if (LEDsLock==1)
    {
      setLEDsFromEEPROM();
    }
  getRTCTime();
  setTime(RTC_hours, RTC_minutes, RTC_seconds, RTC_day, RTC_month, RTC_year);
  digitalWrite(DHVpin, LOW); // off MAX1771 Driver  Hight Voltage(DHV) 110-220V
  setRTCDateTime(RTC_hours,RTC_minutes,RTC_seconds,RTC_day,RTC_month,RTC_year,1); //записываем только что считанное время в RTC чтобы запустить новую микросхему
  digitalWrite(DHVpin, HIGH); // on MAX1771 Driver  Hight Voltage(DHV) 110-220V
  //p=song;
}

Now, I need to be able to constantly access the standard Serial USB to be able to receive a string from my Raspbery Pi. I was thinking of adding the following after their code in void setup()
Serial.begin(9600);

Now I doubt this alone could let me constantly listen to input from Serial USB. But how can I make the code not conflict with the EEPROM.read() commands (I believe this takes in the value from an RTC module attached to the kit)
Thus, a simple loop like the following might not work:
void loop(){
if (Serial.available()) {
    light(Serial.read() – ‘0’);
}
delay(500);
}

So my question is how can I add functionality such that the Arduino is constantly listening to the Serial port for instructions?
If you are interested in the potential things I want to be able to do with this functionality, please refer to this code: Potentiall Additions
Thank you

(1) You already have serial initialization (Serial.begin(115200)) at your code. (2) "Now i doubt this alone.... ", "... simple loop like this might not work", why not try it first, and tell the error instead of using imagination

source: Stack Exchange

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

sort: votes


text:
4 IR sensors on Arduino pro micro. 2 are working other aren't
#include <Keyboard.h>
int IRpin = 5;
int IRpin2 = 6;
int IRpin3 = 8;
int IRpin4 = 9;
int led = 13;

void setup() {
  Serial.begin(9600);
  //start the serial port
  Keyboard.begin();
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
}

void loop() {
  float volts = analogRead(IRpin);
  Serial.println("volts1:");
  Serial.println(volts);
  delay(1000);
  if (volts>500.00){
    Keyboard.press(KEY_RIGHT_ARROW);
    Keyboard.releaseAll();
  }
  float voltss = analogRead(IRpin2);
  Serial.println("volts2:");
  Serial.println(voltss);
  delay(1000);
  if (voltss>600.00){
    Keyboard.press(KEY_LEFT_ARROW);
    Keyboard.releaseAll();
  }
  float voltsss = analogRead(IRpin3);
  Serial.println("volts3:");
  Serial.println(voltsss);
  delay(1000);
  if (voltsss > 500.00) {
    Keyboard.press(KEY_UP_ARROW);
    Keyboard.releaseAll();
  }
  float voltssss = analogRead(IRpin4);
  Serial.println("volts4:");
  Serial.println(voltssss);
  delay(500);
  if (voltssss > 600.00) {
    Keyboard.press(KEY_DOWN_ARROW);
    Keyboard.releaseAll();
  }
}

I connected 4 IR infrared sensors to Pro micro and only 2 of them are working. The other 2 are sending random values.
Connection for all 4 IR sensors.:
IR VCC->Arduino VCC
IR GND -> Arduino GND
Output-> 5,6,8,9

What is your question?

Pin 5 is not analog pins.
On the pro-micro only pins A0-5 and D4, D6, D8-10, D12 can convert an analog voltage to a value.
Just use the A0-5 pins instead, as that will work on any Arduino.

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


text:
Connection between ATTiny85 and RaspberryPi3 with nRF24L01+
I'm hoping someone can help me since I've been struggling with this all weekend. I've got 2 nRF24L01+ breakout cards and I'm trying to send data from a ATTiny85 to a Raspberry Pi 3.
My setup is (the attiny85 breadboard has a 3.3V power supply):

And the code I'm testing is for the ATTiny85:
#define CE_PIN 3
#define CSN_PIN 4

#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

const byte addr[6] = "00001";
int count = 0;

void setup() {
  radio.begin();
  radio.openWritingPipe(addr);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop(void){
  radio.write( &count, sizeof(count) );
  count++;
  delay(1000);
}

And for the Raspberry Pi 3:
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <RF24/RF24.h>

using namespace std;

// Setup for GPIO 22 CE and CE0 CSN with SPI Speed @ 8Mhz
RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ);

// Radio pipe addresses for the 2 nodes to communicate.
const uint8_t addr[6] = "00001";

int main(int argc, char** argv){
  radio.begin();
  radio.setPALevel(RF24_PA_MIN);
  radio.openReadingPipe(1, addr);
  radio.startListening();

  // Dump the configuration of the rf unit for debugging
  radio.printDetails();

  int count = 0;

  while (1)
  {
    while ( radio.available() )
    {
      radio.read( &count, sizeof(count) );
      printf("Count: %d\n", count);
    }
    sleep(1);
  }

  return 0;
}

Double check MISO/MOSI on ATtiny. They are DO and DI not MISO and MOSI (which are used when programming).

Double check what about them? As far as I understand,  the RF24 library supports the attiny's USI for SPI

You might have got the wiring wrong; NRF24/MISO => ATtiny85/DI (Pin 5), MOSI => DO (Pin 6).

@MikaelPatel thanks! That looks like it could be the problem. I have been going off the chip pinout from the datasheet (MOSI pin 5, MISO to pin 6). However, I see now that http://tmrh20.github.io/RF24/ATTiny.html has them listed the other way around, like you say.
I'll test when I get home tonight.

Yes, USI uses DO(utput) and DI(nput). The MISO/MOSI are for programming only.

As Mikael Patel pointed out, my MOSI and MISO pins were switched.
On the pinout for the ATtiny85, the MOSI and MISO pins are for when the chip is a slave (i.e. programming). DO and DI and used for output as SPI master.

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


text:
Same code in setup() and loop() give different results
As the answers to this question and this one state, setup() and loop() are identical in the way they execute code (apart from the obvious looping function of loop()).
However.
I get different results with following two pieces of code:
Code run once, in setup()
/*
 * light_ws2812 library test
 */

#include <WS2812.h>

WS2812 LED(1); // 1 LED

cRGB value;

void setup() {
    LED.setOutput(13); // Digital Pin 13

    value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Yellow?
    LED.set_crgb_at(0, value); // Set value at LED found at index 0
    LED.sync(); // Sends the value to the LED
}

void loop() {
}

Code run once, in loop()
/*
 * light_ws2812 library test
 */

#include <WS2812.h>

WS2812 LED(1); // 1 LED

cRGB value;

bool hasBeenSet = false;

void setup() {
    LED.setOutput(13); // Digital Pin 13
}

void loop() {
  if (hasBeenSet == false){
    value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Red
    LED.set_crgb_at(0, value); // Set value at LED found at index 0
    LED.sync(); // Sends the value to the LED
    hasBeenSet = true;
  }
}

The difference:
The code run in setup() makes the LED flash once with the desired color.
The code run in loop() makes the LED stay lit with the desired color.
With the data being transmitted on pin 13, I can tell (because of the LED on there) in both cases data is being sent only once. With the loop() version I can even disconnect the data line after the color has been set, and it will stay lit.
I can only conclude the same code is executed differently in both cases.
Is there some sort of (soft) power reset after setup()? That could be a potential cause, as the color is stored in volatile memory on the WS2812B (if I'm not mistaken).

Link to the library used: http://github.com/cpldcpu/light_ws2812

Let us continue this discussion in chat.

After some discussion it turned out to be a hardware problem. For the sake of completeness I'll outline the suggestions I made.

There was some initial confusion (see the edits) where the hasBeenSet flag was initialized the wrong way around.
I could not reproduce the problem on my Uno and my WS2812 chip, so the issue was: what was different between his setup and mine?
Possible wiring issue. Make sure +5V, Gnd and Din (data in) are wired correctly.
Possibly faulty WS2812 chip - try with another one.
Possibly faulty Arduino - try with another one.
Possibly Arduino running at the wrong clock speed which would throw the timings out.
Possible extra components (eg. capacitors) added to the circuit which were throwing timing out.
Possible bug in the library. We eliminated that by trying with my library for Neopixels.

In the end DaJF reported that the problem was solved by using another (or no) breadboard. It seems the breadboard was introducing issues, maybe noise or bad connections.
We never really worked out why doing it in loop rather than setup made such a difference. I can only conclude that the slight timing difference compensated for the bad connections (or capacitance) on the breadboard.
I'm going to stick my neck out a bit and suggest that the capacitance in the breadboard was affecting the "shape" of the signal (we are talking about timings of around 350 ns here). Possibly if you measured with an oscilloscope you would see the problem.

The hasBeenSet thing was a copy-pasting error. I was trying other stuff in the loop() and I didn't want the hasBeenSet thing to run, so I disabled it. I removed the irrelevant bits of code when I pasted it here, but forgot to make the hasBeenSet thing work again. So technically the cause of the difference wasn't a programming error on my part. I would like you to update that in your answer. If not, that's fine too, it'll make future readers consider their code too :) Otherwise, great answer!

Maybe you could add a link to your page about the NeoPixels/WS2812B as well? As in a "More info about that {here}." at the end of the last paragraph?

Well, the link is mentioned in the last bullet point. Did you want it mentioned again?

I reworded the part about it being a bug to "confusion".

I should've checked, but I figured the link was the GitHub repo. My bad.
I think it's perfect now, thanks!

As you can see in the source code there is really nothing going on between the setup call and the first loop iteration.
If I'm not mistaken, this type of LED needs a frequent "update" on which color to display, at a precisely timed interval (I suppose this gets more important the more LEDs you have, since they are "addressed" bases on this signal timing.)
I think you really should keep calling sync() in the loop even if you are not actually changing the desired color, to keep "refreshing" the LED. This is just based of a quick analysis of the library code and examples though.
Why you get different results in the samples below could simply be due to the LED randomly "settling" in two different states when no longer getting data. The chst conversation seems to indicate there may have been other reasons as well.

No, the LED doesn't need updating. Once the signal is latched you can disconnect the data pin. I have a page about NeoPixels which shows the timings. There are other useful pages about them elsewhere. The latching is done by a gap of about 9 µs with no data (no 1-bits). Once latched they stay latched until more 1-bits arrive.


text:
arrange vector in descending order
im trying to arrange the vector in descending order but its not happening..
int fibonacci[15]={0, 1};
int a=0;

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

  for (int i=0; i<=14; i++) //loop to create the array
  {
    fibonacci[i+2]=(fibonacci[i])+(fibonacci[i+1]);
  }

  //Now arrange in descending order
  for (int i=0; i<16; i++)
  {
    for (int j=i+1; j<16; j++)
    {
      if (fibonacci[i]>fibonacci[j])
      {
        a=fibonacci[i]; //mux number
        fibonacci[i]=fibonacci[j];
        fibonacci[j]=a;
      }
    }
  }

  for (int k=0; k<16; k++)
  {
    Serial.println(fibonacci[k]);
  }
}

void loop() {
}

14 is the last i index, but you are still reading from i+1 and writing to i+2. You should fix your bounds.

I guess that what you want is a descending sort algorithm, but in the case of Fibonacci numbers you can take advantage that they are already sorted at the beginning. Here are different strategies that you can try :
/*
  SORTING IN DESCENDING ORDER
*/

const int nbElem = 15; // 24 max
int fibonacci[ nbElem ] = { 0, 1 };

void createFibonacciArray( int inputArray[], int arraySize )
{
  fibonacci[ 0 ] = 0;
  fibonacci[ 1 ] = 1;
  for( int i=0; i<nbElem-2; i++ )
    fibonacci[ i+2 ] = fibonacci[ i ] + fibonacci[ i+1 ];
}

void displayArray( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize; i++ )
    Serial.println( inputArray[ i ] );
}

void displayArrayReverse( int inputArray[], int arraySize )
{
  for( int i=arraySize-1; i>=0; i-- )
    Serial.println( inputArray[ i ] );
}

void reverseArray( int inputArray[], int arraySize )
{
  for( int i=0; i<nbElem/2; i++ )
  {
    int fTemp = fibonacci[ i ];
    fibonacci[ i ] = fibonacci[ nbElem-i-1 ];
    fibonacci[ nbElem-i-1 ] = fTemp;
  }
}

void inverseBubbleSort( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize-1; i++ )
  {
    for( int j=0; j<arraySize-1-i; j++ )
    {
      if( inputArray[ j ] < inputArray[ j+1 ] )
      {
        int temp = inputArray[ j+1 ];
        inputArray[ j+1 ] = inputArray[ j ];
        inputArray[ j ] = temp;
      }
    }
  }
}

void bubbleSort( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize-1; i++ )
  {
    for( int j=0; j<arraySize-1-i; j++ )
    {
      if( inputArray[ j ] > inputArray[ j+1 ] )
      {
        int temp = inputArray[ j+1 ];
        inputArray[ j+1 ] = inputArray[ j ];
        inputArray[ j ] = temp;
      }
    }
  }
}

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

  // Create and display Fibonacci array
  createFibonacciArray( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI ARRAY\n" );
  Serial.print( "===============\n" );
  displayArray( fibonacci, nbElem );

  // Solution 1: Display array starting from the end
  Serial.print( "\n\nFIBONACCI ARRAY STARTING FROM THE END\n" );
  Serial.print( "=====================================\n" );
  displayArrayReverse( fibonacci, nbElem );

  // Solution 2: Reverse array
  reverseArray( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI REVERSED ARRAY\n" );
  Serial.print( "========================\n" );
  displayArray( fibonacci, nbElem );

  // Solution 3: Inverse bubble sort array
  createFibonacciArray( fibonacci, nbElem );
  inverseBubbleSort( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI SORTED IN DESCENDED ORDER WITH BUBBLE SORT\n" );
  Serial.print( "====================================================\n" );
  displayArray( fibonacci, nbElem );

  // Ascending order sort array
  bubbleSort( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI SORTED WITH BUBBLE SORT\n" );
  Serial.print( "=================================\n" );
  displayArray( fibonacci, nbElem );
}

void loop()
{}

You can use it using bubble sort algorithm (which is most simple but inefficient)
int fibonacci[15]={0, 1};
int a=0;

int arraysize=2; // variable to store size or array

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

  for (int i=0; i<=14; i++) //loop to create the array
  {
    fibonacci[i+2]=(fibonacci[i])+(fibonacci[i+1]);
    arraysize++;
  }

  //Now arrange in descending order using bubble sort
  for (int i=0; i<arraysize; i++)
  {
    for (int j=0; j<arraysize-1; j++)
    {
      if (fibonacci[j]<fibonacci[j+1])
      {
        a=fibonacci[j+1]; //max number
        fibonacci[j+1]=fibonacci[j];
        fibonacci[j]=a;
      }
    }
  }
  //------------------------------------------------

  for (int k=0; k<16; k++)
  {
    Serial.println(fibonacci[k]);
  }
}


text:
Remote temperature sensor system without slave board
I want to build a temperature control network over my house reading data from each room and sending it to the main board for further processing. I need about 6 sensor nodes sending the data over the air to the main node.
There are tons of tutorials of making master-slave temperature/pressure etc control systems of 2 Arduino boards communicating via wireless channel.
I find it a bit expensive to have a board per sensor node. Is that possible to build a sensor device without a controller using just a sensor, a battery and a wireless transmitter plus required radio components? It's ok to send raw data to the main node. Assuming it knows the protocol it will be able to decode the data there from all the incoming channels.

Only if the wireless transmitter itself is a control board. Like the ESP8266.

As @Majenko said on comment, its possible. One of the choice is ESP8266. Your project has been successfully accomplished, you can check here, here, or here. NSP8266 only needs 3-3.6V (low current) supply voltage.

@Sergey if its cost what's bothering you , there are numerous low-cost options for MCUs. For eg you can club a MSP 430 ( probably <1$) chip with a cheap RF transmitter which wont burn a hole in your pocket and is absolutely reliable. Wifi modules can be a little expensive and need constant connectivity. So, you have a choice on this.


text:
Measure voltage of data output?
I'm trying to control a few NeoPixels using a 3.3V Particle Photon.
I've got a 5V power source that I'm using to power the NeoPixels (as they require that voltage. That works fine.
Them I'm using a 74AHCT125 level shifter to increase the data signal from the Photon from 3.3 to 5.
But I'm seeing sporadic response from the NeoPixels and my hunch is there's something wrong with the power output from the 74AHCT125.
Is there a way I can measure the voltage from the data output of the 74AHCT125? I tried connecting the wire from the 74AHCT125 to my multimeter but I'm not getting any measurement from it.

Many ways. What equipment do you have at your disposal? An oscilloscope would be perfect but presumably you don't have one. Do you have a 5v Arduino, for example? Or an assortment of electronic components?

@MarkSmith No oscilloscope, but I do indeed have a 5v Arduino (Uno).

Don't they work with 3.3v signals?

@Gerben Negative: "NeoPixels powered by 5v require a 5V data signal. If using a 3.3V microcontroller you must use a logic level shifter such as a 74AHCT125 or 74HCT245."

Actually Vih should be at least 0.7*Vdd. So that would be 3.5V. I would be surprised if it would still work at 5V.

The reason your mulitmeter is not telling you much is probably because it reads some sort of averaged voltage, and your signal is flipping between low and high very rapidly.
If you had an oscilloscope you could easily have a look and see what the peak-to-peak voltage is, but since you don't you'll have to find another way.
If you have some basic electronic components at your disposal, you could knock up a simple peak voltage front-end for your multimeter - this looks like roughly the right thing.  You'll need to calibrate it with a known 5v level (i.e. see what reading your meter tells you for a fixed 5v supply) because you'll drop some voltage across the diode.
Otherwise perhaps you could use an analogue input of a 5v Arduino: write a simple sketch to measure (very rapidly!) and tell you the maximum reading every second, say.  I don't know off hand how fast the Uno will sample, or the clock rate of your Neopixels - you'll need the Arduino to sample at least as fast as your clock rate.
For the purpose of a quick hassle-free check, I'd probably plump for the first option.


text:
How to create a smooth change in voltage?
We are given two voltages A and B between 0 and 5V.
So how do I generate a smooth/continuous analog change in
voltage from A to B in a predefined time? The current with that varying voltage is 1 ma or less. The output voltage value is described by a simple quadratic (aX^2)+(bx)+c, at time x seconds.
If that not possible using an Arduino - what is the nearest  solution to it? It seems that it would require an RC circuit?
When I mean smooth/continous I mean it doesn't move in "digital steps" or to use an analogy with resistance instead of voltage - it would be like the way resistance changes when a potentiometer is turned between two places, in a given time, by hand.
A potential solution would be to make a circuit that generate arbitrary voltage between 0 and 5v, some how, at a point in time. For each subsequent small change in time, the change in time is constant, generate the desired voltage from a sketch. If the change of time is small and constant, will putting in a high pass RC filter work? Though I'm not sure of a circuit that can create an arbitrary voltage, or arbitrary voltage resolution or how good the RC filter approximates the quadratic smoothness. I don't know the answer.

If your only constraint is that the change be smooth, then an RC circuit would do the trick, with the proviso that the voltage will approach 5v asymptotically but never truly get there. Are there in fact other constraints, such as you want the voltage to increase linearly, so after half the time you have half the voltage?

What kind of load will be attached to it? An RC filter will not work well with highish loads. You need to buffer it using an opamp. Alternatively add an DAC chip to your circuit.

@MarkSmith The asympotitic behaviour is not really a problem (because I think  you can use an opamp to rescale from between greater than 0 and less than 5 volts). .But I would prefer a solution without op-amps. Regarding the linear behaviour -I updated the question.

@Gerben It sounds like the answer may be in your comment (use RC filter and OP amp).

The quadratic requirement is quite significant - I can't think of any way to get that with an RC circuit, op-amp or no op-amp.

@MarkSmith  I think there got to be a way to do it -but I dont know how good my potential solution given in the question is.

Depending on the speed and power requirements, real, physical components will smooth per their equivalent RC component circuits.  If you want it smoother, or if you want control over the shape between the "digital steps", use a higher resolution DAC to minimize the deviations between your ideal curve and the output.

I'm not sure that there exists a perfect solution for what you want.  Generating the correct output voltage for time is easy.  Just keep track of time and use the formula you wrote to compute the correct voltage you should be at.  Then you can use a PWM output.  However, this isn't going to be perfect since it is made with pulses rather than a continuous output.  On the Uno the pulses are at 490Hz or 980Hz depending on which pin you use.  Use an RC filter and you can then make it continuous - when you tell it output 2.5V you get 2.5V rather than 0 then 5 then 0 then 5 in short bursts.  But, you're still going to get discrete steps based on the resolution of the ADC - for an Arduino Uno, it's 255 steps I believe.  You could get a separate DAC chip to increase this and can probably get enough steps that their small enough you won't notice.  Some versions of the arduino like the due have 12bit analog output and higher frequency, which should help.

It all depends on how literally you want to interpret the requirement of "continuous".  You could have a million-bit DAC and it'd still be discrete, but the intervals would be tiny.  8-bit might be "continuous enough", depending on the application.

@MarkSmith It all depends on how literally you want to interpret the requirement of "continuous" I wonder if that is really provably true. Because you could base an answer on the following idea- you could get a servo to turn a potentiometer to turn a cam-that encodes the shape of the quadratic functrion. And using the resistance with ohms law you can answer the question is some circumstances.

@Pete OK, I could have worded that better. You can make it continuous by putting a capacitor in to low-pass filter out the step - in fact given small-enough steps, even stray capacitances will do that. But the smoothing is just smoothing - it doesn't make the voltage equal the function. If you "zoom in" far enough, you'll see the errors. It's just a case of when it stops mattering.


text:
Arduino Web Server: Receiving response from web form
I am using an Arduino Mega and I have a basic webpage built using EthernetServer for the connection and EthernetClient to write the HTML to the client. I have a simple web form:
client.println("<form method=get>");
client.println("<input type=text name=data>");
client.println("<input type=submit value=Submit>");
client.println("</form>");

I'd like to receive any input from the form and check it against values in order to do stuff on the back end (e.g. reset certain data). How do I get the data from the web page?

Your form method is set to GET. In this case, when Submit is clicked, the client/browser sends request with values in URI:
GET /index.html?data=user_value&default_name_of_button=Submit HTTP/1.1
...more lines to follow...

These HTTP header lines will be available on your EthernetClient instance, retrieve them line-by-line using connected(), available(), read() methods. Then parse the line, find the user_value.
Please note that browser retrieves your page (to display it) using GET method too, in that case URI will be like:
GET /index.html HTTP/1.1
...more lines to follow...

It is recommended to use POST method to submit form values. Example content section (before content, server must send HTTP header - check Arduino Web Server example)
<form method="POST" action="foo.php">

First Name: <input type="text" name="first_name" />

Last Name: <input type="text" name="last_name" />

<input type="submit" name="action" value="Submit" />

</form>

In this case the values are returned in content section:
POST /foo.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 43

first_name=John&last_name=Doe&action=Submit

Tutorial on HTTP headers:
https://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039


text:
How to switch on and off an HD44780 LCD Display?
I have an LCD Display HD44780 model and I was reading his datasheets
I saw the it has the functionality to be switched on/off as stated:

Display on/off control: D = 0; Display off // C = 0; Cursor off // B = 0;
  Blinking off

and by continue reading it states:

Then he states again:
Display On/Off Control

D:  The display is on when D is 1 and off when D is 0. When off, the
  display data remains in DDRAM.

But I can't reaaly understand what I fisically need to do, can anyone help me out to better understand?
EDIT:
For better clarify myfinal goal is to completely (power OFF) the LCD screen, I have some NPN transistors and if this would be the best solution, how about the wiring? do I have only to stop suppying VDO?

At the end I manage to control the complete poweroff of the screen by connecting the pin 15 of the lcd to the Arduino and with a simple HIGH an LOW set of the arduino pin I was able to power it ON/OFF.

Assuming that display is initialized in 8-bit mode: to send command such as "Turn display on/off",

set RS to LOW first (meaning it is command, not data)
set command bits on DB7-DB0 (in your case it could be 0x08 - DB2/DB1/DB0 all LOW to turn off following: display, cursor and blinking)
make a pulse on EN pin LOW-HIGH-LOW (take a 40uS delay before further communication)

Thanks for the reply, assuming that your answer is correct how would you implement such portion of code?

There are tons of HD44780 libraries on the Internet. For example LiquidCrystal library for Arduino. Or this one - https://github.com/aostanin/avr-hd44780


text:
Unable to send serial data to XBee connected to Arduino Uno without a shield
So here are some pictures of the setup I have with an LED, 330 Ohm resistor, Arduino UNO, 2 XBee S1s, and many wires,
https://i.stack.imgur.com/QT1KF.jpg
For specifics, here is the wiring,

XBee Pin 1 (VCC) is connected to Arduino Uno Pin 3.3V
XBee Pin 2 is connected to Arduino Uno Pin 1 (TX)
XBee Pin 3 is connected to Arduino Uno Pin 0 (RX)
XBee Pin GND is connected to the minus column on the breadboard.
Arduino Uno Digital Pin 9 is connected to a 330 ohm resistor which is connected to an LED that is connected to the minus column on the breadboard
Arduino Uno Pin GND is connected to the minus column on the breadboard
And lastly I have another XBee connected to my laptop through a USB dongle

I'm trying to send data in the form of bits through my computer using a program called XCTU to turn the LED on and off. Here is the code for the Arduino,
int led = 9;
int bufferSize = 100;
byte readBuffer[100];
byte lastByte = 0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  int toRead = Serial.available();
  if(toRead > 0){
    while(toRead > bufferSize){
      Serial.readBytes(readBuffer, bufferSize);
      toRead = toRead - bufferSize;
    }

    Serial.readBytes(readBuffer, toRead);
    lastByte = readBuffer[toRead - 1]; //reads last big in serial input

    if(lastByte == '1'){
      digitalWrite(led, HIGH);
    }
    else if(lastByte == '0'){
      digitalWrite(led, LOW);
    }
  }
  delay(250);
}

However, when I send a '0' through XCTU, the LED doesn't turn off. What could be causing this? Note that I did not use a shield to connect the XBee to the Arduino Uno, I soldered the pins to the appropriate spots because I thought it was possible after watching this video,
https://www.youtube.com/watch?v=wtal7SWZek0
Also, I will be cross-posting this on arduino forums to get as much input on this as possible. I will update both topics frequently to attribute answerers for their input (https://forum.arduino.cc/index.php?topic=435027.msg2998240#msg2998240)

There's a whole lot missing here.  I'd be helpful to know what you've tried to debug it.  For instance, do you know that the xbees are talking to each other, etc.  I would start by uploading a program to the uno that prints a string and then open the serial port on your computer and make sure you're seeing that string.  That will confirm they are talking to each other and that you haven't reversed rx and tx.

@mwwalk I've tried what you suggested and I was unable to see the string. I tried reversing rx and tx many times but i haven't been quite successful. I know that both XBees are active because I was able to use the dongle to connect both of them to the computer (one at a time).

So after experimenting with the SoftwareSerial library, it seemed that all the wiring was done correctly but the original code was replaced with,
#include "SoftwareSerial.h"

SoftwareSerial XBee(1, 0); //TX is 1, RX is 0 on the Arduino Uno
int LED = 9;

void setup()
{
  // Baud rate MUST match XBee settings (as set in XCTU)
  XBee.begin(9600);
  pinMode(LED, OUTPUT);
}

void loop()
{
  if (XBee.available())
  {
    byte c = XBee.read();
    if (c == '1')
    {
      digitalWrite(LED, HIGH);

    }
    else if (c == '0')
    {
      digitalWrite(LED, LOW);
    }
  }
  delay(150);
}

and I am now able to turn an LED on or off with data sent from XCTU.
Note: I forgot to include this in my question but some configuration details were that the XBees I was working with were "XBee 1mW Wire Antenna - Series 1 (802.15.4)". Settings for each XBee configured in XCTU include,
Baud Rate: 9600
Data Bits: 8
Stop Bits: 1
no Parity nor flow control
Channel and Pan ID were identical across both XBees
For the XBee connected to the laptop,
DH = 0, DL = 2, MY = 1, and CE = Coordinator[1]
For the XBee connected to the Arduino Uno,
DH = 0, DL = 1, MY = 2, and CE = End Device[0]
*Credit to user PaulS on the arduino forum for helping me out.


text:
How to make RGB LED blink rapidly one color using FOR or WHILE loop
I found a code that turns on different RGB colors but I would like it to blink rapidly one color once called. I dont want to use void loop function to make this possible. My RGB is a cathode. Any help?
int redPin = 8;
int greenPin = 9;
int bluePin = 10;

//uncomment this line if using a Common Anode LED
//#define COMMON_ANODE

void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop()
{
    for (int j = 0; j <= 10; j++) //LED simply stays on. No blinking occuring
     {
      setColor(255, 0, 0);
      delay(100);
      setColor(0, 0, 0);
        }
}

void setColor(int red, int green, int blue)
{
  #ifdef COMMON_ANODE
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
  #endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

You need another delay as the last line in the for loop.  Currently it is turning it off and then immediately turning it on at the top of the loop.

give another delay after setColor(0,0,0).

Simply do this:
int redPin = 8;
int greenPin = 9;
int bluePin = 10;

//uncomment this line if using a Common Anode LED
//#define COMMON_ANODE

void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop()
{
  blinkLed();
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

void blinkLed()
{
  setColor(255, 0, 0);  // red
  delay(1000);
  setColor(0, 0, 0);  // off
  delay(1000);
}

This snippet will blink your led in the red color. Put it in your void loop and you are ready to go.
NOTE: Erase the rest of the void loop before putting this in. Don't delete the function though.
EDIT
FULL CODE ADDED

Is there a way to do this without using loop function? Say with a while or for loop? I'm actually using this function within a code.

Yes you can, simply insert it in whatever loop you want

I tried but the LED stays on

I've included the FULL code. If it doesn't work, describe in detail what happens.


text:
2d 3*3 LED matrix code error
I have  written a trivial code in Arduino IDE but while verifying its returning a error displaying "i was not declared in scope 12'
  int pinMatrix[i][j]= {{2,3,4},{5,6,7},{7,8,9}};
void setup() {
for (i=0;i<3;i++){
  for(j=0;j<3;j++){
    pinMode(pinMatrix[i][j],OUTPUT);
  }
}

}

void loop() {
for(i=0;i<3;i++){
  for(j=0;j<3;j++){
      digitalWrite(pinMatrix[i][j],HIGH);
      delay(1000);
      digitalWrite(pinMatrix[i][j],LOW);
  }

  }

}

Variable i & j are not declared. They should be declared as 3. Try this:
const int x = 3;
const int y = 3;

int pinMatrix[x][y] = {{2, 3, 4}, {5, 6, 7}, {7, 8, 9}};

void setup() {
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      pinMode(pinMatrix[i][j], OUTPUT);
    }
  }
}

void loop() {
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      digitalWrite(pinMatrix[i][j], HIGH);
      delay(1000);
      digitalWrite(pinMatrix[i][j], LOW);
    }
  }
}

tried it , it ain't working and is returning the same error

Try it again, the code I posted, and post the FULL eror message.

Thanks!!                                                                                yeah by mistake i wasn't reading the full error message , now i read it and i made the changes, the code is running now

Please accept the answer if this answer helped you. It means that this question is resolved and needs no further attention.


text:
Why is my class losing a field in the middle of a method
I have a class with a byte (stripLength) that seems to just disappear in the middle of the frameStep() method. I'm not especially skilled with C++ (or non-VM languages in general), but I believe it's only written or modified at the initialization of the class. What am I doing wrong?
BugFinding.ino
#define PIN 11
#define NUM_LEDS 100
#define WAIT 5
#define TAIL_LENGTH 40

#include "Libraries/Adafruit_NeoPixel.h"
#include "LightingStrip.h"

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_RGB + NEO_KHZ800);
LightingStrip lightStrip = LightingStrip(strip, NUM_LEDS, 20);

void setup() {
    Serial.begin(9600);
    strip.begin();
    strip.show();
    Serial.println("BugFinding");
    lightStrip.setColors();
}

void loop() {
    Serial.println("loop");
    lightStrip.frameStep();
    lightStrip.write();
    delay(WAIT);
}

LightingStrip.h
#ifndef LIGHTINGSTRIP_H_
#define LIGHTINGSTRIP_H_

#include "Libraries/Adafruit_NeoPixel.h"

class LightingStrip {
    public:
        LightingStrip(Adafruit_NeoPixel ledStrip, uint8_t stripLength, uint8_t lengthOfTail);
        void frameStep();
        void write();
        void setColors();
    protected:
        Adafruit_NeoPixel strip;
        uint8_t mode;
        uint8_t frame;
        uint8_t colorFrame;
        uint8_t stripLength;
        uint8_t tailLength;
        uint32_t buf[];
        uint32_t colors[7];
        uint8_t currentColor[3];

        void cycleStep();
};

#endif /* LIGHTINGSTRIP_H_ */

LightingStrip.cpp
#include "LightingStrip.h"
#include "Libraries/Adafruit_NeoPixel.h"

LightingStrip::LightingStrip(Adafruit_NeoPixel ledStrip, uint8_t length, uint8_t lengthOfTail) {
    strip = ledStrip;
    stripLength = length;
    tailLength = lengthOfTail;

    buf[stripLength] = {0};
    colorFrame = 0;

    cycleStep();
}

void LightingStrip::setColors(){
    //colors = uint8_t[8][3];
    colors[0] = strip.Color(255, 120,   0); // Orange
    Serial.println("Color 0: " + String(colors[0]));
    Serial.println("Color 0: " + String(strip.Color(255, 120,   0)));
    Serial.println("stripLength: " + String(this->stripLength));
    colors[1] = strip.Color(  0, 255,   0); // Green
    Serial.println("setColors");
    Serial.println("stripLength: " + String(stripLength));
}

void LightingStrip::cycleStep(){
    frame = 0;
    colorFrame++;
}

void LightingStrip::frameStep(){
    Serial.println("frameStep");
    Serial.println("Color 0: " + String(colors[0]));
    int16_t j;
    Serial.println("frame: " + String(frame));
    Serial.println("colorFrame: " + String(colorFrame));
    Serial.println("stripLength 1: " + String(stripLength));
    if(frame > stripLength + tailLength)
        cycleStep();
    Serial.println("stripLength 1.2: " + String(stripLength));

    for(j=0; j<stripLength; j++){
        buf[j] = strip.Color(255,255,255);
    }
    Serial.println("stripLength 2: " + String(stripLength));
    for(j=frame; j>0 && frame-j<=stripLength; j--){
        if(j>stripLength) continue;
        buf[j] = colors[colorFrame];
        Serial.print("j: " + String(j));
        Serial.print(" color: " + String(colors[colorFrame]));
        Serial.println();
    }
    Serial.println("stripLength 3: " + String(stripLength));
    Serial.println("stripLength 4: " + String(stripLength + tailLength));
    Serial.println("stripLength 5: " + String(stripLength));

    frame++;
}
void LightingStrip::write(){
    Serial.println("write");
    Serial.println("stripLength: " + String(stripLength));

    int16_t j;

    for(j=0; j<stripLength; j++){
        Serial.print(" j: " + String(j));
        strip.setPixelColor(j, buf[j]);
    }
    Serial.println();
    Serial.println(String(buf[0]));
    Serial.println(String(strip.getPixelColor(0)));
    strip.show();
}

Serial Output:
BugFinding
Color 0: 16742400
Color 0: 16742400
stripLength: 100
setColors
stripLength: 100
loop
frameStep
Color 0: 16742400
frame: 0
colorFrame: 1
stripLength 1: 100
stripLength 1.2: 100

Have you checked for memory error? You are using a lot of Strings and if you are using an Arduino Uno (Nano, etc) there might be some memory issues with only 2K byte available. Start by removing all the "literal string" + String(value) and replacing them with multiple println() lines.

It looks like you're right. I'm running out of memory in general. If you'll make this an answer, I'll mark it as correct.

At first glance this looks like a sketch with typical memory (heap) issues. When using a lot of string literals, String variables and expressions heap memory becomes fragmented or simple exhausted.
Some programming rules to avoid this:

If possible use the macro F() with string literals. Typically F() should be used when printing a string.
If possible do not use String especially when there is limited amount of SRAM. Remember that ATmega328 based boards such as Arduino Uno, Nano, etc, have only 2 Kbyte SRAM.
Avoid String expressions especially in Serial print statements. Use several print statements instead.

Applying these programming rules to some of the statements in the code above:
Serial.println("frameStep");
Serial.println("Color 0: " + String(colors[0]));
Serial.println("frame: " + String(frame));

Becomes:
Serial.println(F("frameStep"));
Serial.print(F("Color 0: "));
Serial.println(colors[0]);
Serial.print(F("frame: "));
Serial.println(frame);

With no String expressions, and a lot less memory used.
Cheers!
PS: As @MarkSmith points out there is also a pure allocation error. The statement below in the LightingStrip constructor:
buf[stripLength] = {0};

Does not mean allocate and assign. It means element stripLength is assigned the value of the pointer to an array with the single value zero. Guess that the compiler is also warning about this. The value of buf is random as it is not initiated. Assigning an element in the buf will write to a random position.

I think what you mean by stripLength "disappearing" is that your stripLength 2 trace does not appear. This is going to be because you never reach this point in the code.
Look at buf: it's defined as an array in the .h file, but you don't ever allocate any memory for it. buf[stripLength] = {0} doesn't do what you think it does. It puts a 0 into element 100, which at that point is going to trash over some memory you don't mean to write to. When you write to every element in the loop, you're going to trash over lots of memory you didn't mean to.  You want something like
buf = (uint32_t*) malloc(stripLength*sizeof(uint32_t));

Remember to free it again in the destructor.
(Full disclosure: I'm writing this on my phone and I can't remember or test whether it's legal syntax to do this with your array defined (in the .h) as uint32_t buf[]. It's more common, and certainly legal, to use uint32_t* buf.)


text:
How to use setModemRegisters in RF24
The below picture is the introduction of setModemRegisters .

First: What is the mean of ModemConfig* config? I mean: how to write the parameter. Maybe just give a example, and it will be better if it's suitable for this SO question.
Second: What is the mean of data rate? It is the speed of SPI between the SI4463 and MCU or speed of two SI4463  ?
Third, What is the mean of bandwidths? I never saw it...

Thanks for any help .

ModemConfig * config is a pointer to a ModemConfig struct.
You need to create a ModemConfig struct, populate it then pass a pointer to it in the call to the setModemConfig() function.
Something like this:
// create the struct
ModemConfig mc = ModemConfig();

... //populate the struct values

// then call the function
setModemConfig(&mc);

The datarate is the rate at which you are sending information over the radio channel (not between the MCU and the Si4463).
The bandwidth is the range of frequencies used in the radio transmission (e.g. in FSK if a low/0 is 99.95MHz and a high/1 is 100.05Mhz then the bandwidth would be 100Khz)

Thanks very much . I write a code in below . Is it right ?


text:
Having trouble connect nrf24l01 to arduino micro and arduino uno!
I'm trying to connect a nRF24L01 with my Arduino Micro and Arduino Uno. The Arduino Uno works fine, but it doesn't talk with the Arduino Micro. CE is on pin 7 and CSN on pin 8. I posted the code down below into 2 Arduino IDE screens and changed one screen bool radioNumber = 1 and bool role = 1 and the other screen bool radioNumber = 0 and bool role = 0 so that they could communicate. However, the program with the Arduino Micro doesn't seem to work with pins 7 and 8. Is it code where something is wrong or do I need to change the pins and code? How do I make them both communicate with each other?
/*
* Getting Started example sketch for nRF24L01+ radios
* This is a very basic example of how to send data from one node to another
* Updated: Dec 2014 by TMRh20
*/

#include <SPI.h>
#include "RF24.h"

/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 0;

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(7,8);
/**********************************************************/

byte addresses[][6] = {"1Node","2Node"};

// Used to control whether this node is sending or receiving
bool role = 0;

void setup() {
  Serial.begin(115200);
  Serial.println(F("RF24/examples/GettingStarted"));
  Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));

  radio.begin();

  // Set the PA Level low to prevent power supply related issues since this is a
 // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  radio.setPALevel(RF24_PA_LOW);

  // Open a writing and reading pipe on each radio, with opposite addresses
  if(radioNumber){
    radio.openWritingPipe(addresses[1]);
    radio.openReadingPipe(1,addresses[0]);
  }else{
    radio.openWritingPipe(addresses[0]);
    radio.openReadingPipe(1,addresses[1]);
  }

  // Start the radio listening for data
  radio.startListening();
}

void loop() {

/****************** Ping Out Role ***************************/
if (role == 1)  {

    radio.stopListening();                                    // First, stop listening so we can talk.

    Serial.println(F("Now sending"));

    unsigned long start_time = micros();                             // Take the time, and send it.  This will block until complete
     if (!radio.write( &start_time, sizeof(unsigned long) )){
       Serial.println(F("failed"));
     }

    radio.startListening();                                    // Now, continue listening

    unsigned long started_waiting_at = micros();               // Set up a timeout period, get the current microseconds
    boolean timeout = false;                                   // Set up a variable to indicate if a response was received or not

    while ( ! radio.available() ){                             // While nothing is received
      if (micros() - started_waiting_at > 200000 ){            // If waited longer than 200ms, indicate timeout and exit while loop
          timeout = true;
          break;
      }
    }

    if ( timeout ){                                             // Describe the results
        Serial.println(F("Failed, response timed out."));
    }else{
        unsigned long got_time;                                 // Grab the response, compare, and send to debugging spew
        radio.read( &got_time, sizeof(unsigned long) );
        unsigned long end_time = micros();

        // Spew it
        Serial.print(F("Sent "));
        Serial.print(start_time);
        Serial.print(F(", Got response "));
        Serial.print(got_time);
        Serial.print(F(", Round-trip delay "));
        Serial.print(end_time-start_time);
        Serial.println(F(" microseconds"));
    }

    // Try again 1s later
    delay(1000);
  }

/****************** Pong Back Role ***************************/

  if ( role == 0 )
  {
    unsigned long got_time;

    if( radio.available()){
                                                                    // Variable for the received timestamp
      while (radio.available()) {                                   // While there is data ready
        radio.read( &got_time, sizeof(unsigned long) );             // Get the payload
      }

      radio.stopListening();                                        // First, stop listening so we can talk
      radio.write( &got_time, sizeof(unsigned long) );              // Send the final one back.
      radio.startListening();                                       // Now, resume listening so we catch the next packets.
      Serial.print(F("Sent response "));
      Serial.println(got_time);
   }
 }

/****************** Change Roles via Serial Commands ***************************/

  if ( Serial.available() )
  {
    char c = toupper(Serial.read());
    if ( c == 'T' && role == 0 ){
      Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
      role = 1;                  // Become the primary transmitter (ping out)

   }else
    if ( c == 'R' && role == 1 ){
      Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));
       role = 0;                // Become the primary receiver (pong back)
       radio.startListening();

    }
  }

} // Loop

What's the output of .printdetails() function that exists in the library (you may need to include printf.h and also init printf)?

Use millis() and 200 or 200000L in wait for radio.available() block. Statement micros() - started_waiting_at > 200000 is not what you might think.

The output for the transmitter says, " now sending" then after that says "failed, Failed response timed out". For the receiver it just says "sent response 23424332" and then it continues to say "sent reponse" but then with different numbers after that. When I use two arduino unos with same program it works fine. But when I add an arduino micro, it just keeps saying it failed. This what I'm trying to figure out, why it works on arduino uno and not micro


text:
PCF8547 Wire.write explanations
I am using an ESP8266-12E with a PCF8547.
I have managed to turn on and turn off LEDs using these two things.
I am using these three commands to do it.
 Wire.begin(SDA_PIN,CLK_PIN);
 Wire.beginTransmission(0x20);
 Wire.write(~((uint8_t)1<<cnt));
 Wire.endTransmission();

The problem I am facing here is: I am using 4 LEDs and I am only able to turn on one LED at a time. When I turn on another, all the LEDs turn off - in short, the LEDs or the PCF8547 do not preserve the state.
I want to toggle on the LEDs without disturbing the other's state.
How can I do it?
I think, I need more knowledge about the write function, don't I?
Update:
I have already connected A0, A1, A2 to ground. This is the function I use now to toggle the LEDs.
void enlight(int cnt)
{
  if (cnt == 1)
    value = value | 1<<cnt;
    if (cnt == 2)
      value = value | 2<<cnt;
    if (cnt == 3)
      value = value | 3<<cnt;
    if (cnt == 4)
      value = value | 4<<cnt;
    value = ~value;
    Wire.begin(SDA_PIN,CLK_PIN);
    Wire.beginTransmission(0x20); Wire.write(value);
    Wire.endTransmission();
  }

but when I turn off/on any other LEDs they also toggle, which I don't want.

Please add circuit description. How have you connected the LEDs? With to low resistors the LEDs will draw to much current. Check the numbers!

Forwarded from the user Pete: Aren't the addresses of the LED's (or devices) given in the datasheet?

@MikaelPatel : i will add the circuit image that is not an issue.
what i want to achieve is just like we send HIGH and LOW signals to GPIO pins of ESP8266-12e and turn off/on the led connected to that GPIO ,  the same i want to do with PCF8547.  i want to know technique to access the address or some identification to the I/O pins of PCF8547 so that only one led at a time i can turn on/off without affecting other pins  .

Just remember the value you sent last time, and modify only the bits you want to change. Google will tell you how to change a single bit in C (or C++).

This might be of some help; https://github.com/mikaelpatel/Cosa/blob/master/libraries/PCF8574/PCF8574.hh

@MikaelPatel : The library from which you have provided the link , does not support ESP8266-12E.

The library/code was to expire you on how to write this type of code. Cosa is a totally different approach and more advanced programming of the Arduino. https://github.com/mikaelpatel/Cosa

@MikaelPatel : I appreciate the help , but the type of functions and their working in Cosa is not there for Esp8266 . Please guide me more if possible.

Thanks for your edit - it's much clearer. I've added code to my answer showing you how to modify one light at a time - you have to remember the value of all the other lights.

(I haven't used this library, but this looks like a general C(++) question...)
The important part of what you're doing is this:
Wire.write(~((uint8_t)1<<cnt));

Let's break it down.
It calculates a value by taking the number 1 and shifting it left cnt times. Then it takes the complement of that number - changes 0s to 1s and 1s to 0s.  This number is sent to Wire.write() and lights up light number cnt.
Example: Let's say you start with cnt==2, to light LED 2.  It will shift the number 1 left by two digits, giving you the binary number 00000100.  Then it will invert this, giving you 11111011.  This is given to Wire.write().
We can see from this that to light an LED, we need to put a '0' in the right place.
How can you make several numbers light up?  We need to put several zeros in, at the right places.
Here's an example of how you might like to do this - which isn't the prettiest code but I hope it shows you what's going on.
// How we would like the LEDs to appear
boolean led0 = true;    // LED 0 ON
boolean led1 = false;   // LED 1 OFF
boolean led2 = true;    // LED 2 ON
boolean led3 = false;   // LED 3 OFF

// Start with all LEDs off
uint8_t value = 0;

// Put a 1 in place for each LED we want to be ON
// The | symbol means "logical OR" (Google it)
if (led0) value = value | 1<<0;
if (led1) value = value | 1<<0;
if (led2) value = value | 2<<0;
if (led3) value = value | 3<<0;

// Invert this value
value = ~value;

// Write it to Wire
Wire.begin(SDA_PIN,CLK_PIN);
Wire.beginTransmission(0x20);
Wire.write(value);
Wire.endTransmission();

Since it appears you have to send values for all the lights every time, you need to remember the value you sent last time, and modify only the bits you want to change.  Here's a way you can do that:
void setLight(int lightNum, boolean lightOn) {
  // Remember the last state of the lights.
  // Start with all lights OFF.
  static uint8_t lightsOn = 0;

  // We only have four lights (0-3).  Only respond for lights
  // we we have.
  if (lightNum<4) {
    // Get a bitmask with a single 1 in the right
    // position for this light
    uint8_t position = 1<<lightNum;

    // Clear (to 0) that bit in the state
    lightsOn &= ~position;

    // Set (to 1) the bit if we want the light on
    if(lightOn) lightsOn |= position;

    // Write out the value of all lights
    Wire.begin(SDA_PIN,CLK_PIN);
    Wire.beginTransmission(0x20);
    Wire.write(~lightsOn);
    Wire.endTransmission();
  }
}

Call it with something like
setLight(0, true);    // Switch the first light ON
setLight(3, true);    // Switch the fourth light ON (first stays on)
setLight(0, false);   // Switch the first light OFF (fourth stays on)

totally explainable. i got how it works now.
but i am not be able to analyse what address does the pins have.
the code you have provided toggles all the other leds too.
is it possible to get the addresses of the pins on PCF8547 so that the actual led is toggled by us.

Can you experiment with the values of led0...led3 to find the addresses? They should be the same numbers you were using for cnt.

I have been doing experiments, the results are various , but not be able to trigger only one Led , its complicated for the person with non-electronics background, me.
i have managed to find what will the value of the variable value but that also not only triggering the particular pin. plus since few days my Serial monitor is not working. so cant predict the output same time.

Then I think we need a circuit diagram please.

I'd also suggest, if your serial monitor is not working, you're making things harder for yourself by working blind. Don't fall into a gumption trap https://en.wikipedia.org/wiki/Gumption_trap - get that fixed first.

hi i am using the WIFIClient , and the function client.print() , it gives me the values i want to see , but they are not helpful, is there any other way to just toggle the led on a particular pin of PCF8547. other all things i have written properly in my code , the GPIOs of ESP8266-12e i can toggle coz i have the pin no , but don't know how to access and toggle the pins on PCF8547.
Serial monitor issue i will solve afterwards i have priority to solve this first. i have added circuit diagram in question too.

awesome. answer. solved my problem.

Glad I could help :-)


text:
Arduino Uno Reading Fuses
I am trying to read the fuse values for the Arduino Uno, but keep getting the following results returned back to me:
enter code hereavrdude: Version 6.0.1, compiled on Dec 16 2013 at 17:26:24
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "/usr/local/CrossPack-AVR-20131216/etc/avrdude.conf"
     User configuration file is "/Users/hd334/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : /dev/cu.usbmodem1421
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

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

     Programmer Type : Arduino
     Description     : Arduino
     Hardware Version: 3
     Firmware Version: 4.4
     Vtarget         : 0.3 V
     Varef           : 0.3 V
     Oscillator      : 28.800 kHz
     SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0

avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: safemode: Fuses OK (H:00, E:00, L:00)

avrdude done.  Thank you.

I have tried using avrisp as the programmer too, but this reports an invalid device signature. If I override the device signature check with -F I get the same results as above.
I am using an Uno as the ISP to another uno and have connected the two together as detailed in
https://www.arduino.cc/en/Tutorial/ArduinoISP
I have boot loaded the Arduino Atmega328P boot loader and from the fuse settings given in the boards.txt file expect to see:
lfuse reads 0xff
hfuse reads 0xde
efuse reads 0x05
Another question is with the low fuse set to 0xff the CKDIV8 is programmed so won't the clock be set to 2MHz?
Please help

CKDIV should be 0 to enable the divide by 8. Since it's set to 1 the clock frequency will be 16MHz (when using a 16MHz crystal, that is).

Did you do step 5 (Note for the Arduino Uno: you'll need to add a 10 uF capacitor between reset and ground.)?

I connected a 10uF cap between rst on the board to be programmed and the GND on the ISP board

RE CLKDIV8 thanks for clearing that up

Concerning your questions about clock division settings: have a look at this pretty tool, it gives you a avrdude query for setting fuses (take care!). The CKDIV8 bit of the low fuse is set by default, so an AT328p will run at 1MHz, clearing this bit will result in 8 MHz.
When flashing you should never override any checks as this may damage/lock your chip.
I see that avrdudes states the supply voltage to be 0.3 volts which is far to low for communication. Any received bits would be low level and therefore any information read will be 0. ISPs usually provide a supply voltage which often can be selected by switches on the programmer. If you are sure your programmer is allright, check your circuit in general.
Btw, which ISP-model do you use?
Is your mcu assembled on a custom pcb (setup?)? If yes, do you have an arduino(like) board to verify this behaviour?

I'm using a stk500 (USB <> ISP programmer) to read atmega328p fuses. I use this cmd:
C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avrdude.exe -CC:"\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -cstk500 -PCOM9 -e -Ulfuse:r:-:i -Uhfuse:r:-:i -Uefuse:r:-:i

Sometime ago I had some issues with device signatures because I missed the "p" in atmega328p definition.
As a tip, you can check the Arduino verbose to help you with more information:
FILE >> PREFERENCES
SHOW VERBOSE OUTPUT DURING: [x] COMPILATION [x] UPLOAD

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


text:
Problem with sending a POST request using the WiFiEsp library
I'm using an ESP8266 version 1 with the WiFiEsp library to connect to WiFi, and that works just fine.
I'm setting up the device using the same code as in the example WebClientRepeating.
I need to send a POST request instead of a GET request, but I can't get it to work as I want. If I create my POST request like this, it works just fine:
if (client.connect(server, 3005)) {
  Serial.println("Connecting...");

  // send the HTTP POST request
  client.println("POST /open/peripherals HTTP/1.1");
  client.println("Host: 192.168.10.137:3005");
  client.println("User-Agent: Arduino/1.0");
  client.println("Connection: close");
  client.println();

  // note the time that the connection was made
  lastConnectionTime = millis();
}
else {
  // if you couldn't make a connection
  Serial.println("Connection failed");
}

I get the response like this:
[WiFiEsp] Connecting to 192.168.10.137
Connecting...
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 19
ETag: W/"13-jSAaqMh5E3R94/b2aONzvg"
Date: Sun, 13 Nov 2016 10:20:58 GMT
Connection: close

{"temp":"Testdata"}

However, if I try to send some body data in the request it fails:
if (client.connect(server, 3005)) {
  Serial.println("Connecting...");

  // send the HTTP POST request
  client.println("POST /open/peripherals HTTP/1.1");
  client.println("Host: 192.168.10.137:3005");
  client.println("User-Agent: Arduino/1.0");
  client.println("Connection: close");
  client.println("Content-Type: application/x-www-form-urlencoded");
  client.println("Content-Length: 16");
  client.println();
  client.println("temperature=22.7");

  // note the time that the connection was made
  lastConnectionTime = millis();
}
else {
  // if you couldn't make a connection
  Serial.println("Connection failed");
}

Then the response from serial output is:
[WiFiEsp] Connecting to 192.168.10.137
Connecting...
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Data packet send error (1)
[WiFiEsp] Failed to write to socket 0
[WiFiEsp] Disconnecting  0

However, the POST request including the body is received by the Web server just fine, but the response sent to the Arduino I can't read because it shows me an error instead of a proper response. From my webserver the response for the POST call that works and the POST call that fails is the same.
Does anyone knows why this fails when I add Content-Type, Content-Length and some body data?
Thanks in advance!

The first response doesn't correspond to the first code. It is hard to guess where is the problem without the full code.

Your content length is actually 18, considering the CRLF appended by println().

Your problem is the content you are sending. While this format works well e. g. in Python libraries, this library seems to have a problem with it.
I solved it this way, when I happened to face this problem:
//all your other code, including the remaining HTTP-Request
String content = "{\"temperature\":\""+String(value)+"\"}";
client.println("Content-Length: 16"); //insert, well, your content length
client.println(content);

One major problem seems to exists within the AT firmware of most ESP's. By default, the http headers it sends include "Connection: close". However, the firmware seems to be buggy and unable to cope with the server closing the connection after it sends the response. Thus, in order to be able to get a response back from the target server you need to have "Connection: keep-alive" instead. This means you must explicitly add this to your header since "Connection: close" will be added if nothing else is said.
Also to make life easier for the WifiEsp library you could make sure your server returns an already well-known status string for the library like fx "SEND OK"… I'm doing this on a barometer logger that sends data to a MVC Web Api written in C# and it works perfect...
Here's my code:
String PostHeader = "POST http://" + server + ":" + String(port) + "/api/values HTTP/1.1\r\n";
PostHeader += "Connection: keep-alive\r\n";
PostHeader += "Content-Type: application/json; charset=utf-8\r\n";
PostHeader += "Host: " + server + ":" + String(port) + "\r\n";
PostHeader += "Content-Length: " + String(jsonString.length()) + "\r\n\r\n";
PostHeader += jsonString;
Serial.println(PostHeader);
client.connect(server.c_str(), port);
client.println(PostHeader);
client.stop();

And the full log looks like this:
POST http://192.168.10.197:8001/api/values HTTP/1.1
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Host: 192.168.10.197:8001
Content-Length: 144

{"IpAddress":"192.168.10.230","MacAddress":"5c:cf:7f:d9:2f:c8","Temperature":34.6,"Pressure":1007,"Altitude":48.48573,"PressureAtSeaLevel":1007}

[WiFiEsp] Connecting to 192.168.10.197
[WiFiEsp] Disconnecting  3

In the file debug.h located in the WifiEsp library source code you could alter a define and get more output to your serial console. Open the file and change
#define _ESPLOGLEVEL_ 3

to
#define _ESPLOGLEVEL_ 4

Save the file and recompile/deploy your source code to your Arduino and you will get extensive information about all AT commands the library sends and what the library receives in return.

Connection: close tells the server to close the connection once it is done sending the response. If you can't get the response with Connection: close, that's a bug of yours: don't blame that header. BTW, header lines should be terminated with "\r\n", not just "\n".

Cool, I struggled for a long time with this and experimented with a lot of things, changing from \r\n to \n was one of the things I tried (that didn't work). Only forgot to change it back to what it should be. The only way to get it to work with the ESP8266 and the WifiEsp library was to mark the header with keep-alive though. I have debugged the library and tried to find anything that could affect this but nada, most likely it's some bug in the AT firmware... Everyone is complaining about this issue in all devsites, just wanted to add my 2 cents to it...

If that's the case, then you should rephrase your answer: “There is a know bug in the XXX library [link to the bug discussion] that prevents it to work with Connection: close, therefore...”. As it stands, your answer implies that using Connection: close is an error.

Better? I don't have any general link to any discussions around this subject because everyone, everywhere is having a wild goose chase to how to solve this issue, many blame the library but as far as I can see there's no issue with it and it seems to be doing what it is supposed to do :)

Also changed to \r\n...

It still looked like the error was the use of Connection: close, which it isn't. I took the liberty to edit the post myself to make explicit that your are accusing the firmware of a bug that prevents it to work with Connection: close.

the answer is based on unjustified suspicions. they are not true. the WiFiEsp library expects SEND OK from the AT firmware not from the HTTP response. I very very doubt that the AT firmware adds an HTTP header, since a valid HTTP request ends with an empty line and everything after that is a HTTP request body

Didn't say that either @Juraj, I said that you have to add a headervalue as a workaround since something is going wrong somewhere. The http response will not reach the Arduino or WifiEsp library properly and you get following feedback from the library:
    [WiFiEsp] Data packet send error (2)     [WiFiEsp] Failed to write to socket 3     [WiFiEsp] Disconnecting 3


text:
Compiling sketch vi command line
Since I don't like the text editor of the Arduino IDE, I decided to write a python script that I can invoke from my text editor to compile and upload my source. I program the popular esp8266 chip. So far I found that there is a python builder here. This did not work for me. So is there any way to compile my source (e.g. main.ino) via a terminal command?

In the Arduino IDE  preferences, select  external editor. Then you can write/ edit your sketches with any editor you choose. When you click compile or upload on the IDE toolbar, it will load your changes each time you compile.

I found a makefile created to compile ESP8266 sketches. You can use this makefile from command line:
cd /path/to/sketch
make -f /path/to/makefile/makeEspArduino.mk upload


text:
Atmega328P 8MHz External Clock
Has anyone experience configuring the Atmega328P to work with an 8Mhz external clock?
I want to reduce the power consumption of the device. If I just connect an 8MHz external quartz oscillator then simple programs like LED blink still work (With the time delays doubled), but if I try to use communication like UART, then I am unable to. So no programming new sketches.

Looks like you are not using the correct "board". F_CPU has to be defined as your clock frequency. You can check LilyPad as an example.

Hi could you elaborate a little more on that for me ? I'm using a UNO as an ISP to an Atmega328P.

What "board" are you selecting in the Arduino IDE? Have you checked that the definition of the board has the correct clock frequency? My guess is "no".

How do you connect to serial communication? You write communication like UART but no circuit description!

Yes I checked in the board.txt file it is set to 16000000. Which is what I'd expect. I tried setting this to 8000000 but then the boot loader no longer works. I select the Arduino/Genuino

With the UART I am using a UB232R connected to the the Atmega328 Rx Tx lines, and with a capacitor connecting the DTR and reset pin. I know it works I have a second Atmega328 chip that I use to test it.

I'd try making the arduino sleep, and turning off unused devices. That will reduce the power more that running at half speed.

It should work with any crystal speed between 1mhz and 16Mhz. The fuse values allow 1Mhz to 16Mhz. But the arduino IDE assumes that you are using 16Mhz. You can probably google around to find a setting that can be chosen from the menu for 8Mhz.

If you reduce the main clock speed by 50% then everything else is reduced by 50% as well.
The whole chip runs at half the speed. That includes things like the UART.
For example, the bootloader is set to run at 115200 baud on a 16MHz chip. If you run that same chip, with the same bootloader, at 8MHz then the bootloader will actually be running at half the baud rate, so 115200 / 2 = 57600 baud.
Unless you tell the IDE that your board is now running at 8MHz (by creating or using the correct board configuration information to set F_CPU to 8000000) then time runs at half the speed in your sketches too. So a delay of one second will last two seconds. Every two milliseconds a single millisecond will pass. And again baud rates will be wrong. If you use:
Serial.begin(9600);

you will actually be running at half that speed (4800 baud) and so you would have to set your serial terminal program to that speed instead of the one you requested.
To to do things properly you will have to:

Replace the crystal
Edit, compile, and install a new version of the bootloader that runs at 8MHz
Create (or edit) a suitable board definition (in boards.txt) to compile sketches that expect to run at 8MHz.

Hi thanks for the reply, I have replaced the oscillator, and tried to edit the uno.build.f_cpu=16000000L to uno.build.f_cpu=8000000L. But if I do this then when I try to bootload the modified file I get 'avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xff'

Paragraph 3 of my answer.

Well I tried it I halved the baud rate to 9600, on the example ISP sketch. Then edited the board.txt file. Changed the oscillator. The bootload worked. but when I try to upload a sketch I get ''avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00'. Makes me think I need to change the Baud rate of the Arduino IDE but I have no idea how to do that. Does anyone??

uno.upload.speed=115200 in boards.txt

No, if I change this then the boot load fails

And what did you change it to?

The easiest way is to use the settings:
Tools > Board > Arduino Pro or Pro Mini
Tools > Processor > ATmega328 (3.3V, 8MHz)
The problem with that is the Pro Mini bootloader is 2kB and has a bug that causes an endless reset loop if you do a watchdog reset.
The better option is to use https://github.com/MCUdude/MiniCore, which includes the Optiboot bootloader, saving 1.5kB of flash memory vs using the Pro Mini bootloader and doesn't have the watchdog bug.
After selecting the correct configuration for your hardware from the Tools menu, do Tools > Burn Bootloader, which will set the fuses on your ATmega328P and upload the correct bootloader.

That is exactly what I was working on last night after someone suggested just using a Pro Mini. It worked well with no problems. I still never figured out why is never worked by changing the CPU and Baud settings in the Boards.txt file.

Same two menu selections work for other boards too, in conjunction with model selection as a third configuration essential if it is available and not already defaulted to the desired choice.

Firstly, you can buy 8MHz Atmega328P Pro-Minis from China. They are cheap and run at 3.3V. Look at eBay.
If you want to reduce the power consumption of Arduino boards, you have three primary attack vectors:

Removing the power LED
Removing the voltage regulator
A Low-Power library

All of these have different impacts on the power consumption of your respective board.
An extensive comparison can be found here in this blog-post.

That is an answer, but the china man won't deliver on Sundays, I could also use the internal 8MHz Oscillator but it also has 10% accuracy to calibrate it I need a 28KHz Oscillator, China man dos't deliver those on sundays either

hmmmm Pro mini perhaps that may work .... Thanks :)


text:
Debugging library - Error- expected unqualified id before '.' token
I'm writing a library for my project, which interfaces sensors used and structures them in different systems.
But I'm such a noob at C++. The compiler is throwing this error:
libraries/cec-core/cec-core.cpp: In member function 'void Habitaculo::Update()':
libraries/cec-core/cec-core.cpp:15:8: error: expected unqualified-id before '.' token
_Sluz.Update();

This is the header of that class:
class Habitaculo
{
    public:
    Habitaculo(int refrate, int luzpin, int dhtpin);
    //Values from Indoor Sensors
    int temp;
    int hum;
    int luz;
    //Update Methods
    void Update();      //Updates sensors value
    void UpdateReg();   //writes to SD or enabled output method
    private:
    //Clock Managing
    long _PreviousMillis;
    unsigned long _CurrentMillis;
    int _RefreshRate;
    //Sensor instances
    class _Sluz;
    class _SDHT;
};

This are the member functions affected:
Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin){
    //Clock management
    _RefreshRate = refrate;
    _PreviousMillis = 0;
    //Systems to initialize
    LDR _Sluz(luzpin);      //analogpin
    DHT11 _SDHT(dhtpin);    //buspin
}
void Habitaculo::Update(){
    _CurrentMillis = millis();
    if (_CurrentMillis-_PreviousMillis > _RefreshRate){
        _Sluz.Update();  //unqualified-id before '.' token
        _SDHT.Update();  //unqualified-id before '.' token
        temp = _SDHT.temp;  //expected primary-expression before '.'
        hum = _SDHT.hum;  //expected primary-expression before '.'
        luz = _Sluz.value;  //expected primary-expression before '.'
        _PreviousMillis = _CurrentMillis;
    }
}

The error is thrown in every step of the Update method. But I can copy that piece of code right in the Habitaculo constructor and it works well. So I assume I'm missing something basic about language syntax, because I'm really new to all this scene.
Every class involved in this (LDR, DHT11) works fine. It's when I try to put all this together into a new class - inside an unified Update method - that everything crashes.

From what I guess in your code, here is how you want your class declared:
class Habitaculo
{
    public:
    Habitaculo(int refrate, int luzpin, int dhtpin);
    //Values from Indoor Sensors
    int temp;
    int hum;
    int luz;
    //Update Methods
    void Update();      //Updates sensors value
    void UpdateReg();   //writes to SD or enabled output method
    private:
    //Clock Managing
    long _PreviousMillis;
    unsigned long _CurrentMillis;
    int _RefreshRate;
    //Sensor instances
    LDR _Sluz;
    DHT11 _SDHT;
};

Of course, in your header file, you will have to #include the proper header files for DHT11 and LDR classes.
Then you will need to change your constructor as follows:
Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin)
:_Sluz(luzpin), _SDHT(dhtpin)
{
    //Clock management
    _RefreshRate = refrate;
    _PreviousMillis = 0;
}

Note the :_Sluz(luzpin), _SDHT(dhtpin) line before the constructor body, in C++, this is how members of your class that are instances of another class must be instantiated.
Actually, you could even empty the whole cosntructor body by also initializing _RefreshRate and _PreviousMillis in the same manner:
Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin)
:_PreviousMillis(0), _RefreshRate(refrate), _Sluz(luzpin), _SDHT(dhtpin) {}

which is a bit more idiomatic C++.

Seems like you hit the nail with what I'm trying to achieve. Is any problem if LDR and DHT11 are defined in the same header that Habitáculo?

No there is no problem here, as long as they are defined first, before Habitaculo class.

Done. So many thanks for the answer. Definitely I have to dig more in c++ and it's syntax. Thanks again!

class _Sluz;
class _SDHT;

You're forward declared two classes but I see nothing about what those classes are. You then to and use those class declarations as if they were class instances.
I think you are lacking a bit of basic syntax knowledge there. You may have meant:
Sluz _Sluz;
SDHT _SDHT;

Though not knowing what those classes are meant to be or how they are even defined I cannot know really what you think you're meaning.

I assume. It's basic knowledge lack. What I want to do is put two instances of LDR and DHT11 (defined and working) inside Habitáculo instance with names sluz and sdht

Are they instances that are defined outside the class (in your main sketch), or do you want to create two new, distinct, instances within your class?

I want to create them when I create an Habitáculo instance

So the "class" needs to be the actual class name that you are instantiating then. Like you would if you were making them in your sketch, but without any constructor arguments (those have to be in an initialization list for your constructor).


text:
Read signal from co-ax cable with ADC
I have an Arduino Uno and I'd like to read a signal from a co-ax cable with it. The cable carries 12VDC (power for other components) along with a signal (of about 1 Ghz frequency). How do I go about recording this signal with my Uno? I'm new to this field so I don't know the full capabilities of the ADC. Also, the Uno can't handle >5 VDC, so what should I do to make the signal readable?

a signal (of about 1 Ghz frequency). How do I go about recording this signal with my Uno? ... umm ... maybe with somthing that runs about 1,000 x faster than an Uno? You have zero chance of doing it.

It's not possible. To sample a 1GHz signal you need to sample at least 2 billion times per second (a sample rate of 2Gsps). You can maybe get a couple of hundred KILO samples (thousand) per second on an Arduino.
Also the 1GHz signal itself is of no interest to you. What is of interest is what is modulated on the 1GHz signal.
What is normally done is:

Down-mix (filter) the carrier signal to an IF (Intermediate Frequency) usually in the order of a few kilohertz
Demodulate the signal using whatever modulation scheme was used to encode it.
Extract the encoded information from the demodulated signal.

To do that you'd need

the precise carrier frequency (1GHz is not the same as 1.029GHz)
the modulation scheme used (there's loads to choose from)
knowledge about any data formats and encodings used in the signal

As well as the hardware to do all that.
So no, you're never going to come even anywhere close with an Uno. You need specialised RF hardware just to prepare the signal for working with.


text:
Atmega32u4 external 8MHz clock
Does anyone know how to configure the Atmega32u4 to run using an external 8MHz oscillator ?
I needs to still be responsive to the Arduino IDE
Thanks

The ATmega32U4 is configured by default to work with an external 8MHz crystal.

@IgnacioVazquez-Abrams, per Table 28-5 in Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf, the -RC models of 32U4 are configured for RC operation :)  See note 1,  “1. The default setting of CKSEL3..0 results in Low Power Crystal Oscillator for ATmega16U4 and ATmega32U4, and Internal RC oscillator for ATmega16U4RC and ATmega32U4RC.”

See §28.2 in Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf, which explains usage of various fuse bits.
Also see engbedded.com/fusecalc, which lets you easily figure out fuse settings.  Fusecalc also tells you the strings to use as part of avrdude command strings.
Once you know the fuse settings, send them to your device via a command like
avrdude -p m32u4 -c usbasp -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

or like
avrdude -p m32u4 -P $port -c arduino -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

where $port represents a port name like /dev/ttyUSB0.
Note, it makes sense to read the fuses first, and put the readings into Fusecalc to see what they correspond to.  You can read the fuses via a command like
avrdude -p m32u4 -P $port -c arduino -U hfuse:r:-:i

Hi Thanks I see your point and i thought I had to change the fuse settings too, for external 8MHz clock operation with the at328p..... but you don't. The fuse settings are the same.

Why do I know this... well I read the data sheet and the settings for the atmega328 are the same for both Uno (atmega328p, 5v, 16MHz) and pro(atmega328, 3.3v  8MHz). see the boards.txt file inside arduino application. The only difference is the High fuse which is nothing todo with clock speed

Sorry I was answering something else :/ hahaha I think you have both given me the answer I needed........ I just need to change to CKDIV8

I've been head banging all day on this. I only have at328p's to test on still waiting on my 32u4's to be delivered.

@DannyJ, re your second comment,  “settings for the atmega328 are the same for both Uno (atmega328p, 5v, 16MHz) and pro(atmega328, 3.3v 8MHz)”, right.  The same sort of thing will apply on the 32U4, with the same settings at 8 to 16 MHz Low Power Crystal, and other settings for lower frequencies, as shown in  Table 6-3 of  Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf.   Note, if by “responsive to the Arduino IDE” you mean that millis() reports correctly, that is controlled by correctly setting the  .build.f_cpu parameter in the appropriate boards.txt section.


text:
Getting data from web form
I am using an EthernetServer and EthernetClient with Arduino in order to make a simple webpage. I have a web form for a user to enter various codes that can reset data stored on the back end. However, once I enter text into the web form once, it seems to be continually being included in the HTTP header after that. I have the URL: http://192.168.1.30, which becomes (and stays at) http://192.168.1.30/?data=5935 once I enter '5935'. My code is:
void loop() {

// Listen for incoming clients
client = server.available();
if (client) {

boolean currentLineIsBlank = true;
while (client.connected()) {
  if (client.available()) {
    char c = client.read();

    if(HTTPHeader.length() < 100) {
      HTTPHeader += c;
    }

    // if you've gotten to the end of the line (received a newline
    // character) and the line is blank, the http request has ended,
    // so you can send a reply
    if (c == '\n' && currentLineIsBlank) {

      // Calcuate weather parameters for serial and web
      calcWeather(); //Go calc all the various sensors

      // Send a standard http response header
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println("Connection: close");  // the connection will be closed after completion of the response
      client.println("Refresh: 5");  // refresh the page automatically every 5 sec
      client.println();
      client.println("<!DOCTYPE HTML>");
      client.println("");

      client.println("
");
      client.println("");
      client.println("
");
      client.println("Web Server and Radio Receiver ");
      client.println("
");
      client.println("version November 14, 2016");
      client.println("
");
      client.println("");

      client.println("INSIDE");
      client.println("
");
      client.print("Temperature (F) = ");
      client.println(templm34);
      client.println("
");

      client.println("Transmission Errors: ");
      client.print("");
      client.print(numberReceived);
      client.println("
");

      client.println("Transmissions Received : ");
      client.print("");
      client.print(numberOfErrors);
      client.println("
");

      client.println("Transmission Error Rate: ");
      client.print("");
      client.print((numberReceived==0)?(0.0):(numberOfErrors/numberReceived));
      client.println("%
");

      client.println("
");
      client.println("
");
      client.println("
");
      client.println("
");

      // Display the table of illuminance values
      client.println("
");
      client.println("
");
      client.println("Illuminance	");
      client.println("Real World Light Value	");
      client.println("
");
      client.println("
");
      client.println("0	");
      client.println("Absolute Dark	");
      client.println("
");
      client.println("
");
      client.println("10	");
      client.println("Night	");
      client.println("
");
      client.println("
");
      client.println("100	");
      client.println("Dark Day	");
      client.println("
");
      client.println("
");
      client.println("1000	");
      client.println("Overcast	");
      client.println("
");
      client.println("
");
      client.println("
");

      client.println("
");
      client.println("<form action='/' method=get>");
      client.println("<input type=text name=data maxlength=4>");
      client.println("<input type=submit value=Submit>");
      client.println("</form>");

      client.println("");
      client.println("");

      break;

    }
    if (c == '\n') {
      // you're starting a new line
      currentLineIsBlank = true;
    } else if (c != '\r') {
      // you've gotten a character on the current line
      currentLineIsBlank = false;
    }
  }
}
}

// give the web browser time to receive the data
delay(1);
client.stop();
if (HTTPHeader.indexOf("5935") > 0) {
  resetData();
  Serial.print("Found!");
}
HTTPHeader = "";
}

"Found" is printed to the serial every time the page refreshes even though I have not actually pressed the submit button to submit it more than once. I've tried the temporary redirect, but the linux machine I need to use for this project already does a redirect so my redirect doesn't work. Is there a way to do this without a redirect?

(actually a duplicate of the question linked from that question, but the fool never accepted an answer on it so I can't link it as a duplicate - bit of a silly system this sometimes)

Link to linked question: http://arduino.stackexchange.com/questions/28124/webserver-on-arduino-refresh-issues

@Majenko I can't use a redirect because the server I am using already does a redirect and when I do mine I lose the webpage

Then you have a very inferior web server setup - I suggest you use a real one.


text:
Which sensor i can use to transmit some values from Arduino Uno to phone using bluetooth?
I want to transmit some values from arduino uno to my phone using bluetooth.
Which sensor i can use?I want to see some options because i'm a little bit uncertain.Thanks to all which can give me an advice !  :)

So you want to know how to send a text file from the arduino to the phone?

It's not a sensor, its a module. A quite popular module is the HC-05. It's a very simple to use module with a lot of support by the community. Cheap and great for projects.