text:
Using PROGMEM to store array of structs
I am hitting the limits of my arduino's SRAM and found that SRAM usage can be reduced by storing static stuff in flash memory instead of SRAM.
My project can (optionally) be built with an included SimulatorClass. I use this to 'playback' data at home which I gathered during real-life testing of my project. My project is based on photoelectric sensors, and it's timing-critical, so all timekeeping is done using micros(), which returns unsigned long datatype.
To simulate these photoelectric sensor triggers, I need an array containing a struct of 3 variables each:
unsigned int _iDataPos;
   struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   };

So one these structs is 6 bytes long in my counting (2x uint8_t = 2 bytes, unsigned long = 4 bytes).
A typical set of simulator records I need to use is about 25-30 records long, so worst case scenario the simulator array is 180 bytes in size.
I initialize these arrays like so:
SimulatorRecord SimulatorQueue[28] = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
      , { 1, 176848, 0 }
      , { 2, 197732, 0 }
      , { 1, 4675580, 1 }
      , { 2, 4692252, 1 }
      , { 2, 4830180, 0 }
      , { 1, 4849032, 0 }
      , { 2, 9058416, 1 }
      , { 1, 9074780, 1 }
      , { 1, 9215868, 0 }
      , { 2, 9234968, 0 }
      , { 2, 13497276, 1 }
      , { 2, 13500924, 0 }
      , { 2, 13502728, 1 }
      , { 1, 13514992, 1 }
      , { 1, 13668000, 0 }
      , { 1, 13669344, 1 }
      , { 1, 13681828, 0 }
      , { 2, 13701464, 0 }
      , { 2, 18028788, 1 }
      , { 2, 18034252, 0 }
      , { 2, 18036540, 1 }
      , { 1, 18046892, 1 }
      , { 2, 18160312, 0 }
      , { 1, 18178224, 0 }
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

In my simulator code I then loop through these arrays like so:
   unsigned int _iDataPos = 0;
   SimulatorRecord PendingRecord = SimulatorQueue[_iDataPos];

   //main simulator loop
   if (PendingRecord.lTriggerTime <= lRaceElapsedTime)
   {
      //simulate signal
      digitalWrite(PendingRecord.iSensorNumber, PendingRecord.iState);

      //And increase pending record
      _iDataPos++;
      PendingRecord = SimulatorQueue[_iDataPos];
   }

Now I've been reading various PROGMEM tutorials, and storing the SimulatorQueue array in flash seems to be piece of cake, just change
SimulatorRecord SimulatorQueue[28]

to
const PROGMEM SimulatorRecord SimulatorQueue[28]

But for the life of me I can't find out how I should change the copying of each array item to the PendingRecord variable, as my iDataPos counter increases.
Edit: I should have mentioned that this simulator class and all it's member functions & variables reside in a seperate *.cpp and *.h file.
I alreadt found out that since i'm initializing the SimulatorQueue array in the class itself, and not in the main *.ino file, I should do it like so:
constexpr static SimulatorRecord SimulatorQueue[28] PROGMEM = {<structs go in here>};

Edit2: Sample code which reproduces the problem when the simulator array is available here:
http://1drv.ms/1TRwiIB

I don't know why this only has one upvote, it's a very good question. (Ftr, I am that one upvoter).

An easy way of accessing any type of data in PROGMEM is to use this small library:
PROGMEM_readAnything.h
#include <Arduino.h>  // for type definitions

template <typename T> void PROGMEM_readAnything (const T * sce, T& dest)
  {
  memcpy_P (&dest, sce, sizeof (T));
  }

template <typename T> T PROGMEM_getAnything (const T * sce)
  {
  static T temp;
  memcpy_P (&temp, sce, sizeof (T));
  return temp;
  }

You can put that file into a new tab in your IDE, or make a library by putting it inside a folder called PROGMEM_readAnything and put that folder inside the libraries folder, which is inside your sketchbook folder.
That lets you copy from the memory in PROGMEM (using memcpy_P) into RAM. The template is used to work out how many bytes to copy.

Example, using your structure:
#include <PROGMEM_readAnything.h>

struct SimulatorRecord
{
  uint8_t iSensorNumber;
  unsigned long lTriggerTime;
  uint8_t iState;
};

const SimulatorRecord SimulatorQueue[28] PROGMEM = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
      , { 1, 176848, 0 }
 //    ...   omitted for brevity
      , { 1, 18178224, 0 }
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

// number of items in an array
template< typename T, size_t N > size_t ArraySize (T (&) [N]){ return N; }

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

  for (int i = 0; i < ArraySize (SimulatorQueue); i++)
    {
    SimulatorRecord thisItem;
    PROGMEM_readAnything (&SimulatorQueue [i], thisItem);
    Serial.print (i);
    Serial.print (F(" = "));
    Serial.print (thisItem.iSensorNumber);
    Serial.print (F(" / "));
    Serial.print (thisItem.lTriggerTime);
    Serial.print (F(" / "));
    Serial.print (thisItem.iState);
    Serial.println ();
    }  // end of for loop
}  // end of setup

void loop ()
{
}  // end of loop

I found that it decreased RAM usage by 166 bytes, which is almost 28 * 6 (a couple of bytes must have been used by something).

Reference
Putting constant data into program memory (PROGMEM)

Putting PROGMEM into a class
In response to some comments below, this explains how to put the constants into a class.
Alex originally had:
class SimulatorClass
{

...

   typedef struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   } SimulatorRecord;

   constexpr static SimulatorRecord SimulatorQueue[28] PROGMEM = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
   //    ...   omitted for brevity
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

   SimulatorRecord PendingRecord;
};

Putting aside whatever "constexpr" is, you can't put constants inside a class like that. You need to make it static, and have the actual definition elsewhere. So, change the constants to:
class SimulatorClass
{

...

   typedef struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   } SimulatorRecord;

  static const SimulatorRecord SimulatorQueue[28] PROGMEM ;

  SimulatorRecord PendingRecord;
};

Now in your main class file (Simulator.cpp in your case):
 const SimulatorClass::SimulatorRecord SimulatorClass::SimulatorQueue[28] PROGMEM = {
    { 1, 41708, 1 }
    , { 2, 60692, 1 }
   //    ...   omitted for brevity
    , { 1, 20454580, 1 }
    , { 1, 20456368, 0 }
   };

That now compiles OK.

Thanks for your answer. Unfortunately it gives me the same compiler error as I commented on Ignaio's answer below.  I believe it has something to do with these being member functions and variables of a class, in a seperate cpp/h file. However I can't find how I should initialize PendingRecord correctly so it compiles...

Can you post the exact error message please? My code doesn't have SimulatorClass in it, so that cannot be in the error. I tested my code, I didn't just write it without trying. it gives me the same compiler error - I would like you to try my exact code. If it does not give a compiler error, then the problem is elsewhere.

Nick your code works fine off course, but due to the nature of my project  I have to adapt it into my existing codebase. I committed my attempt at integrating your solution to Github, you can find it here: https://github.com/vyruz1986/FlyballSensor/tree/develop. It would be great if you could modify your answer with information on how to use your solution inside a class.

Can you modify your question to add a minimal example of what you are doing? There's a lot of code on your Github site. A Minimal, Complete, and Verifiable example would be great.

OK sorry for that. Answer updated, check http://1drv.ms/1TRwiIB. Thanks!

See modified answer.

Works perfectly, not a byte more SRAM usage compared to when I leave the whole SimulatorClass out! Thanks a million!

"whatever "constexpr" is" constexpr is a very useful feature of C++11.

Using it with heterogeneous types is trickier, since it has to be copied by hand instead of using one of the pgm_read_*() macros.
SimulatorRecord PendingRecord;
memcpy_P(&PendingRecord, &SimulatorQueue[_iDataPos], sizeof(PendingRecord));

Thanks for answering! It is compiling but my SRAM usage isn't being affected at all. I also can't test if it works or not since my program is crashing due not enough SRAM... Any idea what could be wrong?

Never mind found it: was using const SimulatorRecord SimulatorQueue[28] PROGMEM, forgot to add the static keyword. I do get a compilation error on the memcpy_P() now however: undefined reference to SimulatorClass::SimulatorQueue

Could these undefined reference to errors be related to the fact the simulator class and its members reside in seperate cpp/h files? I edited my questions to clarify this.


text:
Decoding a RS232 message in Arduino
I have an Arduino Mega with an MaxBotix (MB7066) sonar attached, the sonar has the ability to send serial data with it's reading. It uses a asynchronous RS232 format, except the voltages are 0-Vcc. The output should be a capital "R" (ASCII), followed by four digits(ASCII) and a carriage return (ASCII 13). The baud rate is 9600, 8 bits, no parity with one stop bit.
What I get from the device is as follows: (sonarSerial.read() while sonarSerial.available())
43
192
6
6
179
89
30
0

What do I have to get to the information? Or is my sensor just retuning garbage?
Please see the code below:
#include <SoftwareSerial.h>

#define pin1 3
#define pin2 5 //pwm
#define pin3 6 //analog
#define pin4 10 //RX for sonar, TX for arduino
#define pin5 11 //TX for sonar, RX for arduino

SoftwareSerial sonarPort(pin5,pin4);

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

   pinMode(pin4, OUTPUT);
   pinMode(pin5, INPUT);
   sonarPort.begin(9600);
}

void loop(){
  digitalWrite(pin1, HIGH);

  digitalWrite(pin4, LOW);
  digitalWrite(pin4, HIGH);
  delayMicroseconds(20);
  digitalWrite(pin4, LOW);

  long pulse = pulseIn(pin2, HIGH)/58;
  Serial.print("PM Result: ");
  Serial.println(pulse);

  String buffer = "";
  sonarPort.listen();
  while(sonarPort.available() > 0){
      int inByte = sonarPort.read();
      buffer += inByte; buffer += " ";
      if(!sonarPort.available()){
          Serial.print("Serial result: ");
          Serial.println(buffer);
      }
  }
  delay(500);
}

Please provide specific model of the sensor you are using.

I contacted MaxBotix with the problem and for my surprise their technical support is really great:

The Arduino is set up to natively read TTL serial data.The MB7066 outputs its serial data in the RS232 format. Do not worry; this problem can easily be fixed. You can use an inverter such as the MAX232. You can also follow the following tutorial to make your own https://github.com/simonmonk/raspirobotboard/wiki/Rangefinder-Adapter.
Another option would be to test using this code section SoftwareSerial
  sonarSerial(rxPin, txPin, true); //define serial port for recieving
  data, output from maxSonar is inverted requiring true to be set.

In the bitstream of your ASCII data the pattern for "R" (01010010b) does never occur.
So obviously something is wrong in your system and/or setup.
Have you already considered the information given here http://www.maxbotix.com/articles/034.htm?
I would connect the sensor to a PC to check whether it's working correctly using a standard terminal software.

I don't have the cable yet so no, I have not checked, will later post my code to remove the possibility of a bad setup.

source: Stack Exchange

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

sort: votes


text:
Leonardo and micro: high pitch noise when powered from Vin

I have an issue with several Leonardo and Micro boards.
On all of my boards, there is a sawtooth of about 690mV ptp @ 4kHz on the 5V supply when powered from Vin (external power).
The frequency changes slightly when changing input voltage from 7V to 12V.
C12 is a capacitor on the Leonardo board that is making the acoustic noise, it is "singing" with the frequency of this sawtooth. It follows the voltage regulator NCP1117 for the 5V power supply generation.
According to the schematics of the Leonardo and micro, the voltage regulator used on these boards should be the NCP1117, but on the boards I have, there is no number printed on this component, so I suspect an alternative was used, with these annoying results...
For a project I have for generating audio signals, this noise was unacceptable, so I cut out the regulator and powered everything with an external LM7805. One should not power the module via USB then as long as the external power is connected!!!
Anyone having the same trouble with these boards?
Other solutions?
(The Leonardo is a genuine Arduino board.)

How are you generating audio signals?  More specifically, what are you driving in the way of outputs?  Are you driving a low impedance magnetic speaker directly?  Your observed behavior strongly hints that you may be placing a high load on the regulator - normally, with only the micro as a load it shouldn't do that, unless you have a dirt cheap implementation made with substandard components.

Yes, I've had this problem on a number of boards. It seems there are some faulty units coming out of the factory. I've had them replaced by my supplier, but I end up being sent more faulty boards.
It makes any kind of accurate ADC reading impossible.
A quick way to work out if your board has this problem

Place a jumper between 3.3v and A0
Put an analogRead in a loop and println the result
When powered by 5V you'll see a fairly constant value (around 670), varying by 1 or 2
When powered by 12V, if you have a faulty board, you'll see varying values, deviating by 50 or more.

There's a couple of solutions/workarounds to the problem listed here: http://forum.arduino.cc/index.php?topic=235729.0.

It does sound like the regulator is oscillating to me.  That happens when the output capacitor is of the wrong type for the regulator - the ESR is wrong.
My Leonardo, when powered from 12V, is nice and clean.  The regulator has 7CE50Z on it.  I do notice, on the layout of the Leonardo, that the output capacitor is somewhat further away from the regulator than I like to put it - though that shouldn't cause that much of a problem.  800mV is way too much to be considered normal under any circumstances.
What is the power source you are using?

it's 12DC coming from a precision DC power supply (Thandar)

@pascalm It's unlikely to be that then.  It's probably the factory has changed regulators and they don't now have the same ESR requirements.  You can try adding a 100nF ceramic capacitor direct across the Vout / GND pins of the regulator - an 0805 would fit nicely.

just used an "ordinary" ceramic cap 104, gives no improvement :(

Next step is probably to change out the regulator - shouldn't be too hard with desolder braid, though hot air is now a very affordable and useful tool.  What is the origin of these boards?  If it is not from one of the claimants to the trademark, you probably should add "-like" in your title rather than attributing issues with some random work-a-like to the branded product.

it's original Arduino! - in original box

Do you have another power source you can try?

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


text:
Overloading function loop
I want to introduce a boolean that is the first iteration of loop and then false
every subsequent iteration. I want it invisible, so I have to modify loop in some way. Is that possible?

What do you mean by "I want it invisible"?

I use plclib to teach how to program the control system and I want it to be as much like real systems as possible,(no c-syntax) and when programming a sequence, it is standard with a variable with the property described in my question. Students can nothing about programming and must learn to program control systems in industry-standard I have managed to avoid c++ - syntax so far.
I added a function called start() to the library, but it complicated the logic of the code in a way that is not very educational.

So I have managed to get a number of funktions that allows one to program the arduinon without using anything other than the language elements that are similar to those found in industrial control systems, and to avoid the destrucktion of the illusion the variable need to be invisible

So you want a variable that is limited in scope so it can only be used within your library, and is inaccessable to other (student) code?

So you just want to redo what you already have: setup() called once the first time, and loop() called forever afterwards? What's the point? You should edit your question to make it much clearer what you really want.

The way to do this isn't to overload the loop function, the way to do this is to abuse the linker and replace main().
The main.cpp file that gets used in the Arduino make prototypes main as int main(void). On my system at least the linker prefers the longer prototype, so you can just do this:
int main(int argc, char* argv[])
{
    init();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    //The one shot loop...
    loop();
    if (serialEventRun) serialEventRun();
    //Put whatever else you need to do between before the unending loop here.

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

Both get compiled, but the int main(int argc, char* argv[]) prototyped version gets linked as the entry point, so your "invisibile" code gets executed.


text:
Soft WDT with HX711 and PubSubClient libraries
I'm using NodeMCU 0.9
My sketch crashes if the following 2 include are present in the sketch:
#include <PubSubClient.h>
#include <HX711.h>

I obtain a Soft WDT reset
If I do not use HX711 I can send message using mqtt.
If I do not use PubSubClient I can read weight values from the load cell connected to the hx711 board without problem
The code crashes at the following line:
mqtt_client.connect("ESP8266Client", mqtt_user, mqtt_password)

Actually using this debugger suggested here the line that crashes is the following and it is inside the PubSubClient class:
WiFiClient::available()

It is a function already existing at ~/.arduino15/packages/esp8266/hardware/esp8266/2.4.1/libraries/ESP8266WiFi/src/WiFiClient.cpp line 21
Here I paste my code so you can reproduce it and tell me if you have the same problem:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "HX711.h"

#define wifi_ssid "mqtt"
#define wifi_password "testmqtt"

#define mqtt_server "THE.IP.OF.MQTT"
#define mqtt_user "USER"
#define mqtt_password "PSW"

#define humidity_topic "sensor/humidity"
#define temperature_topic "sensor/temperature"
#define weight_topic "sensor/weight"

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);

  WiFi.begin(wifi_ssid, wifi_password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    // If you do not want to use a username and password, change next line to
    // if (client.connect("ESP8266Client")) {
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

long lastMsg = 0;
float temp = 0.0;
float hum = 0.0;
float diff = 1.0;

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 1000) {
    lastMsg = now;

    float newTemp = 456;
    float newHum = 123;

    temp = newTemp+1;
    Serial.print("New temperature:");
    Serial.println(String(temp).c_str());
    client.publish(weight_topic, String(temp).c_str(), true);
  }
}

It works if you comment the initial include
PS: Nothing change if HX711 is include as <...> or "..."

Have you read this?

Assuming that's the library you're using - you haven't specified - there's - https://github.com/olkal/HX711_ADC - which can be installed using Arduino IDE (whereas the one I referred to can not)

Thank you @JaromandaX Now I'm trying to use HX711_ADC. I'll try to adapt my code to this new library and update if it gives me problem

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


text:
what to write instead of delay() in interrupt function?
I was trying to develop a traffic light signal controller . when the button is pressed, the pedestrian green light will turn on faster than before . I used delay() in Interrupt function, But it is not working as expected . I am totally new in Arduino coding.
My whole code is below:
int carred = 11;
int caryellow = 10;
int cargreen = 9;

int padred = 13;
int padgreen = 12;

int padpushbutton = 3;
int buspushbutton = 2;

void setup(){
  pinMode(carred , OUTPUT);
  pinMode(cargreen , OUTPUT);
  pinMode(caryellow , OUTPUT);

  pinMode(padgreen , OUTPUT);
  pinMode(padred , OUTPUT);

  pinMode(padpushbutton, INPUT_PULLUP);
  pinMode(buspushbutton,INPUT);
  attachInterrupt(digitalPinToInterrupt(padpushbutton), padcontrol,CHANGE);
 attachInterrupt(digitalPinToInterrupt(buspushbutton), buscontrol,CHANGE);
}
void loop()
    {
     carchangeLights();
 }
void carchangeLights(){

   //turn  carred,padgreen off padred high and cargreen on for 10 seconds
  digitalWrite(carred, LOW);
  digitalWrite(caryellow,LOW);
  digitalWrite(padred, HIGH);
  digitalWrite(cargreen, HIGH);
  delay(10000);

   //cargreen off,  turn on caryellow for 4 seconds

  digitalWrite(cargreen, LOW);
  digitalWrite(caryellow, HIGH);
  delay(4000);

   // turn caryellow and padred off,turn on padgreen, turn on carred for 7 seconds
  digitalWrite(caryellow, LOW);
  digitalWrite(padred,LOW);
  digitalWrite(padgreen,HIGH);
  digitalWrite(carred, HIGH);
  delay(7000);
  //turn padgreen off and padred high , caryellow high for 3 second
  digitalWrite(padgreen, LOW);
  digitalWrite(padred, HIGH);
  digitalWrite(caryellow, HIGH);
  delay(3000);

}

void padcontrol(){

  int red = digitalRead(carred);
  int yellow = digitalRead(caryellow);
  int green = digitalRead(cargreen);

  if (red == HIGH && yellow == LOW ) {
    digitalWrite(carred, HIGH);
    delay(2000);
    digitalWrite(padred, LOW);
    digitalWrite(padgreen, HIGH);
    delay(15000);
     }

  else if(yellow == HIGH && red == LOW){
     digitalWrite(caryellow, HIGH);
    delay(2000);
    digitalWrite(caryellow,LOW);
    digitalWrite(carred,HIGH);
    digitalWrite(padred,LOW);
    digitalWrite(padgreen,HIGH);
      delay(15000);
    }
  else if(yellow == HIGH && red == HIGH) {
   digitalWrite(caryellow, HIGH);
    delay(1000);
    digitalWrite(caryellow,LOW);
    digitalWrite(padred,LOW);
    digitalWrite(padgreen,HIGH);
      delay(15000);
    }
   else{
    digitalWrite(cargreen,LOW);
    digitalWrite(caryellow,HIGH);
    delay(3000);

    digitalWrite(caryellow,LOW);
    digitalWrite(carred,HIGH);
    digitalWrite(padred,LOW);
    digitalWrite(padgreen,HIGH);
    delay(15000);
   }

}

void buscontrol(){

  int red = digitalRead(carred);
  int yellow = digitalRead(caryellow);
  int green = digitalRead(cargreen);

  if (red == HIGH && yellow == LOW ) {
    digitalWrite(carred, HIGH);
    delay(3000);
    digitalWrite(carred,LOW);
    digitalWrite(padgreen, LOW);
    digitalWrite(padred, HIGH);
    digitalWrite(caryellow, HIGH);
    delay(2000);
    digitalWrite(caryellow,LOW);
    digitalWrite(cargreen, HIGH);
    delay(10000);

     }

  else if(yellow == HIGH && red == LOW) {
    digitalWrite(padgreen,LOW);
    digitalWrite(padred,HIGH);
   digitalWrite(caryellow, HIGH);
    delay(2000);
    digitalWrite(caryellow,LOW);
    digitalWrite(cargreen,HIGH);
      delay(10000);
    }
  else if(yellow == HIGH && red == HIGH) {
   digitalWrite(caryellow, HIGH);
    delay(1000);
    digitalWrite(carred,LOW);
    digitalWrite(caryellow,LOW);

    digitalWrite(padgreen,LOW);
       digitalWrite(padred,LOW);
     digitalWrite(cargreen, HIGH);
      delay(10000);
    }
   else{
    digitalWrite(padred,HIGH);
    digitalWrite(cargreen,LOW);
    delay(10000);

   }
}

what to write instead of dely() in interrupt function?

Nothing. An interrupt service routine (ISR) should not do any things, that take long. That will block any other things from happening, for example Serial communication (which is done by interrupts in the background).
delay() does not work in an ISR, because it relies on the millis() counter to increment. But that is done in another ISR. While one ISR is running, no other can run at the same time. Thus delay() waits forever, that the millis() counter increments.
What to do instead?
Instead you should only use the ISR to set a simple flag variable, for example of type boolean (because it should be a single byte type). Then in your main code (meaning inside loop()) you check for this flag. When it is set by the ISR, you execute the corresponding code and reset the flag. Be sure to declare the flag variable as volatile, so that the compiler knows, that is can change at any time.

That said, you should really ditch all the delay() calls. Instead use a non-blocking coding style involving millis() like in the BlinkWithoutDelay example, that comes with the Arduino IDE. There are tons of tutorials and explanations about that on the web and this site. Just search for it. Using a non-blocking coding style is needed, if you want the code to be responsive while doing long timed things.
Also you should look into Finite State Machines (FSM). Thats a very powerful principle, that will come in useful. It fits exactly on a traffic light project. I have once wrote a longer explanation about FSMs in my answer to this question, though you can also google something like "Arduino fsm". You basically divide the behavior of the project into individual states. The current state is hold by a variable. By changing that variable you transition between states. For example padcontrol() could change the state variable to the state for the pedestrian light. I strongly suggest, that you learn that principle to structure your code. I can attest, that it is really helpful.

Just to add to chrisi's excellent answer, I wouldn't use interrupts at all for this project.  Imagine an impatient pedestrian repeatedly pushing the 'walk' button.  Every time this happens, the ISR fires and takes over control of the MCU, no matter what is happening at the time.  So, while the MCU is trying to respond to the pedestrian's first push, it gets interrupted and starts trying to respond AGAIN, and AGAIN, and AGAIN...  If your program isn't structured to handle randomly occurring interrupts, it can make the program behave in unpredictable (read "hard to debug") ways.

You should just use polling to check the state of the buttons.  That way the MCU is in total control, and can ignore the button states while it's busy

Thank you so much . Now I just found a way to go ahead

@SaikotDas While it is important to learn the above about interrupts, user3765883 is right in that simple button checking can be easily done without interrupts in the main code when you use a non-blocking coding style. The loop() can then easily run fast enough to catch all button presses in a timely manner. Also debouncing can be easier that way. Maybe have a look at the Bounce2 library on github

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


text:
Strings becoming empty (Arduino Uno)
I'm running a modifed code on Arduino Uno + WiFi shield (updated), and I have seen strange behaviors with String ; here is my code, the goal is to parse a HTML request to know which page was requested :
String line = client.readStringUntil("\n");
Serial.print("Line : [");
Serial.print(line);
Serial.println("]");

String cmd = line.substring(0, 3);
Serial.print("Command : [");
Serial.print(cmd);
Serial.print("]");

My problem comes from what appears in the console :
Line : [GET / HTTP/1.1
Host: 192.168.43.200
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Ac]
Command : []

I was expecting the cmd variable to contain GET, and I do not understand why it contains nothing.
I suspect this behavior comes from the lack of RAM (compiler says there are only 670 bytes available for local variables), but if it's the case, I do not know how to solve it, as I'm pretty inexperienced in C++ and I need to store a String containing the values that are sent as a reply to the HTTP request.
PS. I'm also wondering why the client.readStringUntil("\n") method sends the full request instead of only the first line.

readStringUntil Requires a char as argument, not a C string. So try changing "\n" to '\n'

https://hackingmajenkoblog.wordpress.com/2017/04/08/splitting-up-text-in-c/

In general, you don't want to be copying strings around when you don't have to because it's inefficient. For parsing things like command lines, you can often just work with the existing String (or better yet, string; see Majenko's tutorial).
In this particular example, you have a string and you want to know if it's an HTTP GET command. That's simple enough; the first four characters will be GET (we check the space on the end because we don't want to interpret GETMORE /foo as a GET command).
This is extremely easy:
String s = "GET /foo/bar";

if (s.startsWith("GET "))
    Serial.println("GET command");
else
    Serial.println("Not GET command");

For stuff in the middle of a string you obviously can't use startsWith, but there are other functions that can help. For example, once you know it's a GET command, you know that the URL starts at position 4 (the 5th character, since counting starts at 0). You could test to see if it starts with '/foo' with
if (s.indexOf("/foo") == 4)
    Serial.println("Path starts with /foo.");
else
    Serial.println("Path doesn't start with /foo.");

That said, while this kind of thing is workable for quick tests, in the long run you probably want to move towards parsing in C in the way that Majenko's tutorial above talks about, and likely parsing as much as possible as you do the reading (rather than reading everything into memory and then parsing it) due to HTTP requests being relatively large compared to the memory you have to handle them.

In the end I used your link to learn more about C-style strings, and translated my whole code to use them, so I'm marking your answer as a solution, however the bigger problem was the string litterals : replacing them using the 'F()' macro freed 40% of the SRAM, and solved this problem.

I'm glad to hear you got things worked out! I expect that the RAM being used by string literals being a problem didn't occur to anybody here because there's almost no use of string literals in the question, but that's certainly something to keep in mind if you have more than a few of them.

Well I'm coming here from Java, and I have this strange habit of using println()s to log everything instead of commenting my code :/ looks like it can backclash sometimes

I have an other problem with memory usage of growing strings here ... If you have any tips for this one, I'd be glad to hear them


text:
serial char read first letter if it is ";" print char without fists letter
I'm working on a project and I need to print serial to a LCD but only if the first letter of the serial is ":"
I have the serial being stored in a char and a if statement reading the first letter of the char to see if it is ":" From there I can't get it to print to the LCD without the first letter. I also don't know how to clear the char.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

char inData[20];
char inChar;
byte index = 0;

void setup(){
 lcd.begin(16, 2);
 Serial.begin(9600);
}

void loop()
{
  while(Serial.available() > 0)
  {
      if(index < 19)
      {
      inChar = Serial.read();
      inData[index] = inChar;
      index++;
      inData[index] = '\0';
  }
 if(inData[0] == ':') {
   lcd.print(inData);
   }

  }
 }

The answer to this question has been accepted. So what is the issue?

Tell it to print starting from the second character.
lcd.print(inData + 1);

ok seams to work but when i do ":test" in serial monitor i get "ttetestest" any ideas

That's because the rest of your code is wrong.

whats wrong with it and do u know how to fix it?

Have you looked at your output yet?

what you mean? when I type ":test" the LCD says "ttetestest"

Yes, but have you actually looked at it?

well ya it is printing the first letter than the other letter in the char. i under stand what going on with it but dont know how to fix it. i need it to be just one work "test" not print the letters in the char in order.

Consider this question: How often are you outputting?

i did some messing around with the code and fixed it but i still need to clear the char and i dont know how.


text:
How to make MEMS IR Thermal Sensor - D6T-44-L06 work with Arduino?
I am working on project that my team need to detect the presence of the people. At first, we tried with motion sensor but it wasn't the way that we want it to work. We want to detect presence of the people even they don't move.
We decide to go with Omron Thermal Sensor D6T-44-L06. However, there lacking of tutorial or simple code online that actually show how to connect that Omron thermal sensor with Arduino. How can I interface this with Arduino?

Yes should be really easy to implement, as it work like almost all i2c sensor; this manual as also some code example, the chip address, and finally the registry address; that is all you need.
http://www.mouser.com/pdfdocs/D6T01_ThermalIRSensorWhitepaper.pdf


text:
Hooking up 12v Push button to arduino uno/nano
I want to use one an push button with an led in middle, similar to this one on eBay.
The push button has a 12v input I want to hook it up to an Aduino Uno or Nano.
Is there a way to hook it up and receive the signal?
Specifications from the eBay page:

Latching type, push it—on, push it again — off
Switch Rating: 3A/250VAC
LED voltage: 12V only
Contact Configuration: 1NO1NC
Pin Number: 5

You can probably power the light using only 5v instead of 12v. The led will be less bright, but probably still visible. The button part has nothing to do with 12v so you can just use 5v like !AMADANON Inc. said.

Most likely, there will be a push button, and on separate wires, there is a light. If this is the case, you can hook the push button part up to the arduino. You can test this - find two random wires, test the resistance with a multimeter, then press the button and see if the resistance changes. Keep trying until you find two wires that change when you press the button.
Once you find the pair, you can hook one of those two to a digil pin on the Arduino, and via a resister (large, anything 10kilo-ohm or larger is fine) to ground (GND). Then, connect the other side of your pushbutton to 5V. See http://arduino.cc/en/tutorial/button for photos and a circuit diagram - their wiring is more complicated than it needs to be, and their button has 4 pins in two pairs (left pair, and right pair in the picture with the breadboard; the left-top and left-bottom are permanently connected, and the right-top and right-bottom are permanently connected). Have a look at the circuit diagram - that's a lot simpler. The zig-zag at the top is the resistor, and the disconnected looking thing is the switch (open). There is sample code there too.
Note that push buttons typically "bounce" - that is, when you push them, they will go (starting off) on-off-on-off-on-off-on, so if you're counting the number of pushes you will get a result which is way too high. If you delay long enough in between (10ms?) then you won't get these. The code I linked to already has debounce built in.
The other part is the light. This is a little more tricky. The light will probably use too much current for the arduino to supply directly. You will need a transistor and a resistor (again, at least 10 kiloOhm is good).
The transistor should be an NPN transistor, and should look like the top one in http://www.reprise.com/host/circuits/transistor_pinouts.asp. The easiest one is the base - this is the middle one. Connect this via your resistor to another digital pin on your arduino (pin 13 is great for testing this, because it will also light up the led on the Arduino). Next, connect your emitter to ground (GND). Then, IF YOUR POWER SUPPLY IS NO MORE THAN 12 VOLT! you can connect VIN to the + side of the light, and the - side of the light to the collector.
Next, load a sketch - the "blink" sketch is good to test this. Adjust the pin as necessary.
Note that, these switches have a resistor already built in to the light; if you want to do the same with an ordinary led, you will have to add one yourself. Check out http://ledcalc.com/ to tell you which resistor you need.


text:
Calling a function that is outside of a class from inside
I have an Arduino sketch with a timer interrupt class and would like to place the TIMER2Services() function in the TimerTwoTest.ino file for easy access. On compile I get a multiple definition of tmb2 error in the .ino TIMER2Services() function. I have tried all the variations I can think of but no luck. Is there a way to do this?
TimerTwoTest.cpp.o: In function `TIMER2Services()':
D:\Arduino157/TimerTwoTest.ino:41: multiple definition of `tmb2'
TimerTwo.cpp.o:C:\Users\...\build8577138580185682113.tmp/TimerTwo.cpp:10: first defined here

collect2.exe:
TimerTwo.h:
class Tmb2
{
  public:
  void initTIMER2(unsigned int Hz, unsigned int ulPeriod);
  void resetTIMER2(unsigned int Hz, unsigned int ulPeriod);
  TIMER2_TYPE getPeriodTIMER2(void);
  void activeTIMER2 (void);
  private:
}tmb2;

TimerTwo.cpp:
extern void TIMER2Services(void);

[this function is line 10 for the error]
void Tmb2::initTIMER2(unsigned int Hz, unsigned int ulPeriod){  //setperiod and enable interrupt
  if (Hz){
    ulPeriod = 1000/Hz;    //if Hz > 0 use frequency microseconds
  }
  Timer2.attachInterrupt(TIMER2Services).setPeriod(ulPeriod).start();
}

TimerTwoTest.ino:
volatile unsigned long burpCount = 0;

//This routine services the interrupt
void TIMER2Services(void){
  burpCount++;
}

Which file(s) are you including, and where? Also: it looks like you're using an external library: is this correct?

The problem is your definition of tmb2.  You're declaring the variable in the header file, and not the C(++) file.
Please try this:
TimerTwo.h
#ifndef __TIMER_TWO_H__
#define __TIMER_TWO_H__

extern void TIMER2Services(void);

class Tmb2
{
    public:
        void initTIMER2(unsigned int Hz, unsigned int ulPeriod);
        void resetTIMER2(unsigned int Hz, unsigned int ulPeriod);
        TIMER2_TYPE getPeriodTIMER2(void);
        void activeTIMER2 (void);
    private:
};

#endif // #ifndef __TIMER_TWO_H__

The #ifndef TIMER stuff saves you getting multiple definitions from header files if they're included more than once.  There's other ways to do this, but this is simple and well-known.
TimerTwo.cpp
#include "TimerTwo.h"

void Tmb2::initTIMER2(unsigned int Hz, unsigned int ulPeriod)
{
    //setperiod and enable interrupt
    if (Hz)
    {
        ulPeriod = 1000/Hz;    //if Hz > 0 use frequency microseconds
    }
    Timer2.attachInterrupt(TIMER2Services).setPeriod(ulPeriod).start();
}

TimerTwoTest.ino
#include "TimerTwo.h"

Tmb2 tmb2;
volatile unsigned long burpCount = 0;

// This routine services the interrupt
void TIMER2Services(void)
{
    burpCount++;
}

void setup()
{
    tmb2.initTIMER2(blah1,blah2);
}

For the sake of neatness, I'd move TIMER2Services into class Tmb2 as a static function... if possible.

Shouldn't TimerTwo tmb2; be Tmb2 tmb2;?

Yeah, you're right Gerben.  I've just edited it

I would also re-think the closeness of the class name and instantiation name: Tmb2 looks very much like tmb2, and could lead to errors of mistaken identity. It's certainly a personal 'good practice' for me, but there are no rules for either opinions.


text:
Button with switch timer and reset time function + LED feedback. What am I doing wrong?
Beginner here.
I´ve been trying to implement a button function timer working with millis() instead of delay as I want the button to be responsive while the timer is running.
So far I´ve managed to start the counter on the button´s state change and let it time out. Unfortunately all kind of strange behavior is coming out of my sketch and I am yet to understand why.
Help is appreciated.
This is the desired behaviour of the timer:

On startup the Arduino is ready to recieve a button push.
The relay is off (HIGH).
Once the button is pushed:
• The relay state is changed to LOW in order to turn it on
• A green LED switches on.
• A millis() based timer is switched on.
If the user presses the button while the switch is on, the timer is reset to 0 and continues counting.
If the on-time is going to end, a red LED starts blinking. Say in the last minute.
As soon as the timer reaches the specified on-time:
• The green LED switches off
• The relay switches off
• The system returns to step 1. and is awaiting a push.

In my code example the red blinking Led is not implemented yet.
The following code switches the switch and the green LED on but does not switch them off anymore.
//CONSTANTS

#define BUTTON_PIN        2  // Button
int in1 = 7;
int greenLED = 4;
int redLED = 9;

//VARIABLES

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

//MILLIS
unsigned long previousMillis = 0;
const long interval = 10000;

void setup()
{
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(BUTTON_PIN, HIGH); // pull-up
  Serial.begin(9600);

  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);

  //SWITCH HANDLERS
  pinMode(in1, OUTPUT);
  digitalWrite(in1, HIGH);

}

void loop(){

    // read the pushbutton input pin:
    buttonState = digitalRead(BUTTON_PIN);
    unsigned long currentMillis = millis();

    // compare the buttonState to its previous state
    if (buttonState != lastButtonState) {

        buttonState = digitalRead(BUTTON_PIN);

        if (currentMillis - previousMillis < interval){
        //SWITCH ON, LED ON
          digitalWrite(in1, LOW);
          digitalWrite(greenLED, HIGH);
        }

        if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            digitalWrite(in1, HIGH);
            digitalWrite(greenLED, LOW);
        }

        // Delay a little bit to avoid bouncing
        delay(50);

        // Reset buttonState:
        lastButtonState = buttonState;
   }
}

For one, you are running code when the button is being pressed, but also when the button is being released (though I don't think that effects anything here). Secondly, the code that checks if enough time has passed only runs when the button is pressed (or released). Thirdly the previousMillis isn't updated when the button is pressed.

Written and tested. I also included the red blinking led.
//CONSTANTS

const int BUTTON_PIN = 2; // Button
const int in1 = 7;
const int greenLED = 4;
const int redLED = 9;

//VARIABLES

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button
bool relayOn = false;

//MILLIS
unsigned long previousMillis = 0;
const unsigned long interval = 10000;
const unsigned long redLedInterval = 2000;

void setup()
{
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(BUTTON_PIN, HIGH); // pull-up
  Serial.begin(9600);

  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);

  //SWITCH HANDLERS
  pinMode(in1, OUTPUT);
  digitalWrite(in1, HIGH);

}

void loop(){

    // read the pushbutton input pin:
    buttonState = digitalRead(BUTTON_PIN);
    unsigned long currentMillis = millis();

    // if button is pressed, turn relay on (if it wasn't already on), and reset the timer
    if( buttonState==LOW ) // no need to check for previous state, in this specific case
    {
        previousMillis = currentMillis;
        digitalWrite(in1, LOW);
        digitalWrite(greenLED, HIGH);
        digitalWrite(redLED, LOW);
        relayOn = true;
    }

    // if relay is currently on...
    if( relayOn )
    {
        // turn red led on, if close to turning off the relay
        if (currentMillis - previousMillis >= interval-redLedInterval )
            digitalWrite(redLED, (millis()/300)%2);//blink red led; 300ms on; 300ms off

        // if enough time has elapsed, turn of the relay
        if (currentMillis - previousMillis >= interval)
        {
            // .. turn of relay
            digitalWrite(in1, HIGH);
            digitalWrite(greenLED, LOW);
            digitalWrite(redLED, LOW);
            relayOn = false;
        }
    }
}

Added advantage here is that the timer will never run out if the button is keep being pressed down.

Thanks. This is very nice from you.
Unfortunately all it seems to do is switch both, the greenLED and the relay on as soon as the Arduino is powered. Pushing the button does not sem to have any effect. Could this be a hardware problem?
I was working on a very similar approach to your bool relayOn but with an integer changing between 0 and 1. While this partially worked, I was stuck at the timer reset implementation. I will try and include your solution in my approach and post the results.

Then I think you have your button connected the other way around. Is the button connected to 5v or GND when pressed?

Try changing buttonState==LOW to buttonState==HIGH.

Halleluja! It works!
For some reason the idea that a button state change was important was stuck in my head. I thought that the buttonState==LOW and HIGH states are only working while this state is in fact present, meaning while the button is held pressed and not after that.
I have no way to express the amout of gratitude.

I also find this expression very interesting. Why does this work?
digitalWrite(redLED, (millis()/300)%2);

In that case you need to remove the line that enabled the "pull-up" resistor, as apparently you are using a pull-down resistor on your breadboard.

The state-change of the button is quite useful in a lot of cases. For example; press the button to turn on the relay, and then press the button again to turn of the relay. But in this very specific case, state-change doesn't matter,

millis()/300 gives you the number of 300ms intervals that have elapsed. %2 gives the module 2, so the remainder of /2., or in this case 1 if it's odd, and 0 if it's even. This is a very quick way of blinking a light. The only downside is that most of the time it doesn't start blinking at a millis value that is divisible by 300. So the first blink can be a lot shorter. Or it start with being off. The latter can be problematic if you use a slow blink.

You're welcome by the way. Please press the checkbox next to my answer to accept it (once you are allowed that is).

So let me check if I understand right:  millis()/300 checks "how often" the 300 ms interval fits into the current millis() value, right? Sorry for first grade language. It helps my graphical mind to understand. So (300/300) = 0; 0%2 = 0, thus LOW; (600/300)=2 %2= 0, thus LOW again. (1300/300)=4,3 and 4,3%2=0,3, thus not 0 which outputs to HIGH. Am I getting closer? I know that dividend or divisor have to be ints. Does this mean they are rounded?

1300/300=4 as the remainder is just thrown away. (4%2=0). So with dividing integers the result is rounded down. That's not what they taught us in first grade math q-;

I see. So as a proof of understanding: 1500/300=5; 5%2=1;  So the value is either 0 or 1 because every second full number divided by 2 equals 0. Now I got it.

Yep. So 0-299=>0. 300-599=>1. 600-899=>0. Etcetera

Simple and beautiful.

Would it be difficult to implement a switch everything off again when the button is pressed for 2 seconds?

Then you'd have to add the buttonSate back into the mix. I'd suggest you give it a try yourself first.

I definately will.


text:
Best way to read CSV from SD card and store values by date
I am starting a project in Arduino and I need to read data from an CSV stored in an SD card. The data is stored as the following:
id, value, date
What I want to do is read the file, filter by date and then store the values by id. Each id will correspond to different values from that same date.
Is it possible to do something like this?
Thank you very much for your advice.

Since and Arduino does not know about SDCards you will have to use an SDCard shield and that shield's library to access the card.  Once you have decided on which shield / library you are using - modify your question identifying which you picked.  Then people can answer your question specifically.

Also, most Arduinos run on embedded processors with very limited RAM.  So there is an upper limit on the size and number of variables you can keep at hand.  For example, you probably could not read and keep 100,000 of your records at hand.  But you could read 100,000 records and keep, say, 100 records or maybe even several thousands at hand.

It scarcely matters which hardware is used.  But it is true that limited RAM may mean the algorithm has to read through the source data many times, pulling out only what is of interest for one iteration at a time.  Or else, the destination data will have to be written with large gaps between each distinct set - in effect, it could be like sorting things into boxes, but having to be sure that your boxes are big enough that none of them will end up heaped aboved the rim.  Generally speaking, an Arduino is a poor  choice for data processing.

This is not arduino-specific. Have you tried searching for "parse csv c++"?

Actually, you can sort 100,000 records, given enough time, and being able to save them back to the sd-card. But it may not be as efficiënt and also wear out the sd-card raster. You could check every two records, and swap them if the second is higher than the first. If you keep doing this until nothing has to be swapped in a whole iteration, it's sorted.

I highly suggest checking out this YouTube video (https://www.youtube.com/watch?v=5v5A3j7Rrco), especially around 21:30. It goes over in detail to do exactly what you are asking for, mainly the headings with IDs for each data point. At the end of the day you are going to need something that looks similar to this:
float id = 0; //used to provide a numbered ID to each data point

void setup(){
//initialize all your once-run variables and such
}

void loop(){
  //Write Log File Header
  File logFile = SD.open("NAME.csv", FILE_WRITE);

  if (logFile){
    logFile.println(", , , ,"); //Just a leading blank line, incase there was previous data

    String header = "ID, Time, Light, Temp"; //These will be the headers for your excel file, CHANGE "" to whatevr headers you would like to use
    logFile.println(header);
    logFile.close();
    Serial.println(header);
  }

  else {
    Serial.println("Couldn't open log file");
  }
}
}

This is all code that I currently use to do the exact same thing as you, and its a small edit from what Jeremy Blum does in the YouTube video I just linked you too. This is how the header files will look on an excel sheet, I took a screenshot of an actual file I have created using this method:


text:
Esp8266 esp01 kicks other devices off tplink router
I had an Esp8266 esp01 module programmed to log onto the router and post data.  It worked fine for a few months but all of a sudden it kicks everyone else off the router.
Actually as soon as I connect the Esp and it connects to the ssid, it kicks off my laptop (laptop can no longer even see the ssid) and I see my Google home drop it's connection as well.  It's almost immediate, about 20 seconds after powering up my esp.  Seconds after I unplug the Esp google home comes back on and my laptop sees the ssid again.
What should I check for in my router?  It's a tplink tr-wl945N.

try to set RF TX power of the esp8266,

@Juraj what does that mean?  The Esp now has a dedicated power source.

in esp8266 sketch WiFi.setOutputPower(15.0);

I hope you didn't set the same IP address to the esp8266 as the computer has

I didn't set the ip, the router uses dhcp


text:
Help to decode xbee S2 API packet
I'm new at using Xbee and I would like to get some help on how to interpret API packets. Me setup consists of two arduino unos, two xbee S2, two xbee shields and a one magnetometer sensor HMC5883L.  The sensor is connected to the arduino via I2C and transmitting the data to the xbee (router) using serial communication. On the other side (coordinator) I'm reading and displaying the data on the serial monitor. I have read the data sheet of the xbee but I still can't figure how to interpret the packet. Here is a screen shot of the values that I'm getting on the serial monitor on the router and the corresponding packets on the coordinator's serial monitor.

There are four bytes that are changing each time so how can I translate them to an integer value. Any help would be greatly appreciated.

You have a bunch of "stuff", followed by the data you sent, followed finally by another bunch of "stuff".  I don't know what the "stuff" is, but I can see and decode your data easily enough.
I suspect you transmitted the data using .println(...).  That will send an ASCII representation of the data.
So to take the line: -196.88<CR><LF>, if we find the ASCII values and represent them as hexadecimal we have:

2D,31,39,36,2E,38,38,D,A

Which I am sure you can find in one of those lines - maybe this one:

0,15,90,0,13,A2,0,40,C1,A8,2E,98,8D,1,2D,31,39,36,2E,38,38,D,A,3B

So you have 14 bytes defining something interesting about the packet (I'm sure Google can tell you what - source and destination maybe, probably a packet length too), then your data, and finally what looks like it's probably a checksum.


text:
ATMEGA328 SPI MCP2515 - SPI communication freezes at certain point
I got 2 boards with an ATMEGA328 microcontroller and MCP2515 CAN Controller and I'm trying to get them communicate with each other.
To shortcut the programming a little bit I'm using the Sparkfun CAN BUS Library, but I am not using ther CanbusClass(), I'm directly using the included mcp2515.c/h
The MCP2515 drives a MCP2551. CAN_H and CAN_L of both boards are connected with each other, the line has a 120Ohm termination resistor.

Both Microcontrollers share the same code:
#include <mcp2515.h>
#include <global.h>
#include <mcp2515_defs.h>
#include <defaults.h>
#define CANSPEED_125    7
const uint8_t PIN_LED_RED = 6;
const uint8_t PIN_LED_GREEN = 7;

void setup()
{
  Serial.begin(9600);
  pinMode(PIN_LED_GREEN, OUTPUT);
  pinMode(PIN_LED_RED, OUTPUT);
  unsigned long now=micros();
  unsigned long init = 0;
  if(mcp2515_init(CANSPEED_125)) {
    init=micros();
    Serial.println("CAN Init ok");
    digitalWrite(PIN_LED_GREEN, HIGH);
    delay(500);
    digitalWrite(PIN_LED_GREEN, LOW);
  } else {
    init = micros();
    Serial.println("Can't init CAN");
    digitalWrite(PIN_LED_RED, HIGH);
    delay(1000);
    digitalWrite(PIN_LED_RED, LOW);
  }
  Serial.print("Time for init: ");
  Serial.println (init-now);
  delay(1000);
  mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);
  Serial.println("-------------------------");
  Serial.println("1. CAN - MSG1");
  Serial.println("-------------------------");
}

void loop()
{
  tCAN CANmessage;
  unsigned long tnow;
  unsigned long tsend;
  if (Serial.available() > 0) {
    char incomingByte = Serial.read();
    switch (incomingByte) {
        case '1':
            Serial.println("1. CAN - MSG1");
            tsend=micros();
            CANmessage.id = 0x01;
            CANmessage.header.rtr = 0;
            CANmessage.header.length = 8;
            CANmessage.data[0] = B01010101;
            CANmessage.data[1] = B11001100;
            CANmessage.data[2] = B11100011;
            mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);
            mcp2515_send_message(&CANmessage);
            tnow=micros();
            Serial.print("Message send in time: ");
            Serial.println(tnow-tsend);
            break;
    }
  }
  checkCANBus();
}

void checkCANBus() {
  if (mcp2515_check_message()) {
    tCAN CANmessage;
    PORTD ^= _BV(7);
    Serial.println("Has message");
    if (mcp2515_get_message(&CANmessage))
    {
        Serial.print("Message receivced: ");
        Serial.print(CANmessage.id);
        Serial.print(", ");
        Serial.print(CANmessage.data[0], BIN);
        Serial.print(", ");
        Serial.print(CANmessage.data[1], BIN);
        Serial.print(", ");
        Serial.print(CANmessage.data[2], BIN);
        Serial.print("end ");
        if (CANmessage.id==0x01) {
            Serial.println("MSG ID1 received");
            PORTD ^= _BV(6);
        }
    }
  }
}

On Serial port of both boards I get on startup:

CAN Init ok
  Time for init: 250
  1. CAN - MSG1

When I send a byte on the Serial port of one baord ('1') I get on the Serial:

Message send in time: 212

On the receiver side I only get

Has message

and the green LED on PIN7 is turned on (means mcp2515_check_message() returns that the MCP2515 has set the receive interrupt signal).
After that the program crashes in the routine mcp2515_get_message().
By toggling the LED's I figured out that the program crashes directly at the beginning of mcp2515_get_message() in the line mcp2515_read_status(SPI_RX_STATUS);
So the problem lies in mcp2515_read_status().
int8_t mcp2515_get_message(tCAN *message)
{
  // read status
  uint8_t status = mcp2515_read_status(SPI_RX_STATUS);
  ...
  ...
}

uint8_t mcp2515_read_status(uint8_t type)
{
    uint8_t data;
    RESET(MCP2515_CS);
    spi_putc(type);
    data = spi_putc(0xff);
    SET(MCP2515_CS);
    return data;
}

uint8_t spi_putc( uint8_t data )
{
  SPDR = data;
  while( !( SPSR & (1<<SPIF) ) )
    ;
  return SPDR;
}

By further toggling I figured that the last line correctly executed is spi_putc(type);
The line data = spi_putc(0xff); freezes the microcontoller! Which means the while loop in spi_putc() is endless running as the SPIF bit is not cleared.
Here is what I think I figured out so far:

The SPI bus connection is clearly working as the initialization is working!
As the mcp2515_check_message() returns on the receiver board that MCP2515_INT is set so I assume the CAN communication is working (otherwise, why would controller set the MCP2515_INT).

SPI_RX_STATUS is defined as 0xB0(original as in library).
The Datasheet of the MCP2515 controller states on page 66

The RX STATUS instruction (Figure 12-9) is used to
  quickly determine which filter matched the message
  and message type (standard, extended, remote). After
  the command byte is sent, the controller will return
  8 bits of data that contain the status data. If more clocks
  are sent after the eight bits are transmitted, the
  controller will continue to output the same status bits as
  long as the CS pin stays low and clocks are provided.

Which it clearly doesn't! But what I cant figure out is why :)

I would be tempted to find out why you only get 'Has message' which implies that if (omcp2515_get_message(&CANmessage)) is returning zero.

The code shows omcp2515... and mcp2515... functions. What's that about?

@PeterSmith thats not the case. The program freezes in that call of mcp2515_get_message(&CANmessage).

@JimmyB, thats just a copy of the function I used to toggle the LED. I didnt want to mess with the original code in the library. I edited the question!

Just try another library, like this one: https://github.com/Seeed-Studio/CAN_BUS_Shield just be careful as this library does not implement atomic SPI transaction.

There is one huge pitfall in Master Mode in this ATMega - Select Slave pin (/SS - active low). If it's configured as input, SPI is switched to Slave Mode by low level on this pin. And /SS is on pin PB2 (used as CAN_INT).
In the library defaults I can see: #define    MCP2515_INT D,2. PD2 is also INT0 external interrupt pin, so it does make sense to be here and it can be used with attachInterrupt. PB2 is used as an output for selecting slave device, so it's ok too.
Schematics corresponds with that defaults:

In OPs schematics there are slight changes. Interrupt request CAN_INT is located on /SS pin (PB2, arduino pin 10). CAN_CS was moved from PB2 to PB1 (arduino pin 10 -> pin 9)
And in Mega328 datasheet is section: 19.2 SS Pin Functionality:

19.3.2 Master Mode
  When the SPI is configured as a Master (MSTR in SPCR is set), the user can determine the direction of the /SS
  pin.
  If /SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically,
  the pin will be driving the SS pin of the SPI Slave.
If /SS is configured as an input, it must be held high to ensure Master SPI operation. If the /SS pin is driven low by
  peripheral circuitry when the SPI is configured as a Master with the /SS pin defined as an input, the SPI system
  interprets this as another master selecting the SPI as a slave and starting to send data to it. To avoid bus
  contention, the SPI system takes the following actions:
  1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a result of the SPI becoming a Slave, the MOSI and SCK pins become inputs.
  2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit in SREG is set, the interrupt
  routine will be executed.
  Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a possibility that SS is
  driven low, the interrupt should always check that the MSTR bit is still set. If the MSTR bit has been cleared by
  a slave select, it must be set by the user to re-enable SPI Master mode.

Conclusion: If you are using HW SPI in master mode, you can't just use pin 10 (PB2) as general input.

Could you possibly clarify this answer more, it is really vague and short. Also the connections of the OP's circuit is basically the same as the schematic from Sparkfuns shield

I think you are on the right track. Dont know, why I missed that in the datasheet... Let me quickly cut the track of PB2 and connect a botch wire to PB0 to test it.
Btw. if I understand it correct, actually I would only need to change CAN_CS (which is an output) with CAN_INT (which is an input) in my final layout and everything should be ok, right?

Yes, you can switch these signals. But if you dont use D10, it must be set eiter as output (and used for another signal) or input pullup (and left unconnected). However i'd recommend to use PD2 (INT0) or PD3 (INT1).

Just tested it and it works! Thank you very much for helping me out! Finding this cost me days :)

So what is the conclusion? What should be done? Can you make it clear (by editing your answer)?

Turns out this applies for other Atmel products, including the ATiny1627, too.  Very useful answer!

@hegel5000 However in the ATtiny1617 you can disable this functionality and use SS pin as IO: "If SSD in SPIn.CTRLB is ‘1’, the SPI does not use the SS pin, and it can be used as a regular I/O pin, or by other peripheral modules.". This is not possible in the older AVRs

@KIIV well, not general I/O.  If you leave the SS pin as input, even with SPIO.CTRLB = SPI_SSD_bm, SPI can still hang!  But it seems to work fine as output; no need to pull high.  (Or I'm getting (un)lucky.  Whether it hangs due to SS is somewhat random.)

@hegel5000 Right, at least Atmega4809 has this mentioned in Errata document - even if you configure it, it won't disable it


text:
Standalone Arduino with ATMEGA328P / Serial working, but serial programming not (only once after buning bootloader)
For my master thesis I've designed a board with an ATMEGA328P-AU as micro controller.

As I want to use some libraries and I like the simplicity, I want to use "Arduino" to program it.
Everything works fine to a point:
I took an Arduino Uno and uploaded the "ArduinoISP" sketch.
I connected the ISP pins and burned the bootloader with board set to "Arduino Duemilanove / Diecimila" - got the message, bootloader burned.
I disconnected the ISP pins, took the ATMEGA out of its socket on the UNO board and connected the serial pins.
Here comes the problem I cant figure out:
Once I have done a above procedure I can upload a sketch and Serial communication is working. But I can only upload it once! The second time (no matter if during the same power-up or at another time) I push the upload sketch button, I get no response for several minutes (I once waited up to 10min to confirm there is nothing coming anymore :)). If I unplug either USB or the TX/RX cables I get the error (or for the USB cable something similar):

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

When I upload the bootloader again I can once again upload a sketch same as before. Then the same problem happens again.
I checked several question on Stackexchange already (specially all points in this one here) and googled the problem, but until now I am not able to find a solution.
As you can imagine it is quite annoying to always unplug the RX/TX cable and hook up the ISP cable again and burn the bootloader.
So my question: What could cause this problem and how can I solve it?
Btw. I am using the Arduino software version I'm using is 1.6.9

Did you change the fuses? What bootloader did you use?

I didn't change any of the fuses. What do you mean, with "what" bootloader? Are there different ones? I burned the bootloader with the board set to "Arduino Duemilanove / Diecimila" in the Arduino 1.6.8 environment.

How is your serial connection wired up? It's missing from that schematic.

The 2 lines RX and TX just go to a 4pin pin header (for a cable with 4 wires, 5V, TX, RX, Gnd)

There is a problem with your circuit and the way you have it wired when programming. You have failed to use the RTS line for Serial programming. You need to have that line connected to the RESET of the ATMega328, this is as the bootloader for programming ove rserial will not start if the IC is not reset. Also you should burn the Arduino UNO bootloader rather than the one you chosen.
Seems you clarified you were using the diode as ESD protection, thank you. It is the recommended arrangement if you have a capacitor attached to the reset line in noisy environments.
The circuit between the RTS signal and the Arduino RESET pin needs to be this:
            C
 RTS >>----||------->> RESET(PIN1)
           0.1µF

From the same "Have I bricked my Arduino" that you linked, about 3/4 down Nicks post he mentions the use of serial programming of an Arduino
FTDI    Arduino Uno

GND       GND  (black wire on FTDI cable, blue jumper wire)
CTS       not connected
VCC       5V
TxD       D0 (RX)
RxD       D1 (TX)
RTS       To RESET with a 0.1 µF capacitor in series with it (green wire)

What you can do if you don't have the proper serial programmer with an RTS output, you will have to manually reset the microcontroller to enter the bootloader just as the IDE says "Uploading...".

Doh, how did I miss this... Let me give it a try.

The diode is correct.
Please see this application note, its for ESD protection. http://www.atmel.com/Images/Atmel-2521-AVR-Hardware-Design-Considerations_ApplicationNote_AVR042.pdf
Also the Arduino boards are using it.
http://arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

@KarlKarlsom    I know its ESD protection but why. Have you got it in a ESD prone environment. I would possibly choose a diode then with a larger pulse current for the ESD protection.

sorry for the late reply and acceptance of your answer. I just now had the chance to test it! The missing reset connection solved the problem! However your suggestion using the UNO bootloader is not working. It says it burned the bootloader. But then I get a timeout when uploading a sketch. With Duemilanove selected as bootloader it is working!

Replying to an old post:  The Reset diode is not really ESD protection, it is there to shunt any high voltage spikes to Vcc to keep the chip from reacting to a high voltage and going into High Voltage programming mode, and then acting hung when there are further control signals to complete the sequence.


text:
Possible ArduinoJson bug on ESP8266?
I'm making a small IOT project using the ESP8266 in which I make 2 API calls:

api.openweathermap.org for weather data
api.timezonedb.com

The request logic is the same for both calls, the only difference being how I parse the response string. The first response is parsed fine, while the other isn't.

I print the String responses to Serial, they look fine.
Tried both Dynamic and Static buffers to no avail.
Making the request only to the second API, still not being parsed.
If I make a test and just make the response a String, char[] or char*, it parses fine.

Parsing logic [works]:
StaticJsonBuffer<1000> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(response);
float raw = root[String("main")][String("temp")].as<float>();

Parsing logic: [does not work]
StaticJsonBuffer<500> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(response);

String data = root[String("formatted")].as<String>();

The response object looks like this:
{
  "status": "OK",
  "message": "",
  "formatted": "2017-06-30 11:34:13"
}

Request logic:
String RequestAPI::performRequest(String url, char* host){
WiFiClient client;
if (!client.connect(host, port)) {
    lcd -> clearScreen();
    lcd -> drawText("Failed to connect to API", 0, 0, this -> randomUint16());
    delay(5000);
    return "";
}

char endOfHeaders[] = "\r\n\r\n";
client.print(
String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n"
);
// Skiping HTTP headers from the response
client.find(endOfHeaders);

unsigned long startTime = millis();
while(client.available() == 0){
    if(millis() - startTime > this -> timeout){
        lcd -> clearScreen();
        lcd -> drawText("API request failed", 0, 0, this -> randomUint16());
        delay(5000);
        return "";
    }
}

String response = "";
while(client.available()){
    response += client.readStringUntil('\r');
}
Serial.println(response);

return response;
}

Now I'm thinking, could the empty message be causing a bug? Or am I doing something wrong?

You say that the 2 responses are parsed differently, but only show one method.  Also the line  String data = root[String("formatted")].as<String>(); doesn't look right. From the examples I think it should be String data = String(root["formatted"]);

@CodeGorilla Updated answer with the working parser.

@CodeGorilla Your suggestion ends up with: 'String(ArduinoJson::JsonObjectSubscript<const char*>)' is ambiguous

Strange - I was just looking at the examples, https://github.com/bblanchon/ArduinoJson/blob/master/examples/JsonParserExample/JsonParserExample.ino, sorry I couldn't help.

very helpful, I'm working a similar problem. Any chance you could share your entire code? Especially more details on the section on handling the Get request timeout. unsigned long startTime = millis(); while(client.available() == 0){ if(millis() - startTime > this -> timeout){ lcd -> clearScreen(); lcd -> drawText("API request failed", 0, 0, this -> randomUint16()); delay(5000); return ""; } }

@micromet am planning to create a repo for this, don't have the time to refactor out my hardcoded API string and passwords. The timeout handling seems pretty self explanatory.

The issue was caused because of: https://en.wikipedia.org/wiki/Chunked_transfer_encoding
Was not obvious as the data printed to the serial looked completely fine. Fixed with the below code:
client.print(
  String("GET ") + url + " HTTP/1.0\r\n" +
  "Host: " + host + "\r\n" +
  "Connection: close\r\n\r\n"
);

Dunno why it worked for one API but not the other though.


text:
Not in sync: resp=0x00
I had problems with Arduino uno and reseted firmware. Followed this tutorial. Now I can't upload my code Arduino IDE says:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

I tried loop-back mode, everything is fine.
Firmware was located in this location:
/usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

It looks like you changed the bootloader which would change the behaviour of arduino ide (ie there is no arduino bootloader to connect it to). You might want to look into reflashing the bootloader.

Can't you tell me how to do that?

Writing bootloader from Arduino IDE throws the same error

I was talking about the actual software that arudino uses to load up the code see here http://arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader  It would help if you have another arudino to work with

There are two processors on the Uno board.

The Atmega328P which is the "main" processor with your sketches on it
The Atmega16U2 which handles the USB interface

Firmware was located in /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

Hopefully you reflashed the Atmega16U2 with that file. Did you?

I tried loop-back mode, everything is fine.

Therefore the Atmega16U2 is OK. The problem may be with the Atmega328P.

I had problems with Arduino Uno and reseted firmware.

You shouldn't need to do this, I never reflash the firmware on my Atmega16U2.
What problems did you have? Did it involve motors? LEDs? High voltages? Sparks? Flames? Screaming?
Please see the steps described here, run through them, and see if that fixes the problem: Have I bricked my Arduino Uno? Problems with uploading to board


text:
How Do I Properly Ground my Arduino Leonardo using Capacitive Sensor?
Hi we are using Arduino Leonardo with some electric paint and Capacitive Sensor Libraries. We have a lot of variance in our Serial output from our sensors, we believe if we grounded the Arduino we would have more concrete values.
On the Capacitive Sensor doc, it reveals to use a small capacitor to put on one of the pins. More details!
Another guide somewhere says to wrap the Arduino in plastic and tin foil. These are vague, and we have not landed success when we tried.
Has anyone had success grounding Arduino Leo? Thank you.

Can you please link the datasheet of the sensor? Thanks!

@AnnonomusPenguin - the sensor is typically homemade, just some "plates" or in this case it seems areas of conductive paint.  There's an edit in the queue to add a link to http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense

The documentation for that library is recommending that you place a 100 pF capacitor between the sense pin and ground.
However, I personally suspect you will get the best results when the user's presence affects at small mutual capacitance between a sense surface and a ground surface.
One idea could be to have a large ground plane, and on it a smaller insulated "sense" plate.
Another could be to run two parallel traces in a spiral filling a large area
Do take care to secure you wires - they are part of your sensor too, and if they move relative to each other they will alter the baseline.  Any other mobile cables in the vicinity can have the same effect, especially if they contain a ground that can exhibit capacitance to the sense node.

The simplest way to ground an Arduino is to attach the ground pin, found on the power header, to a grounded surface, like a metal pipe. As for the capacitor you mentioned, that is called a smoothing capacitor. It is a small capacitor, about 1microfarad, and goes between the supply of the sensor and the ground line.

Actually, no - the recommendation is for an approximately 100 pF cap across the sensor surface (surfaces?).  You are speaking instead of a power supply capacitor, but there isn't really any applicable place to add that except on the Arduino board itself, which would normally be well bypassed.

It might help if you follow the diagram for connecting a button, that way the value of the capacitor sensor wont fluctuate...
Photo from http://arduino.cc/en/tutorial/button

Huh?  Yes, you could use a button as an input sensor instead of cap sense.  Or you could use a button to trigger a calibration routine but it's very clear how you meant this to answer the question?


text:
Adapt program to suit Arduino UNO
I am trying to use a program that has been written for  STM32 microprocessor for interfacing with a Time to Digital Converter TDC GP22 via SPI interface. I would like to use the same program and adapt it to suit Arduino Uno for interfacing with TDC GP22. This would really help save a lot of time.
Can someone please suggest me the most effective way to do this ?

Read the code. Write high-level pseudocode. Translate the pseudocode.

@user18197 - Do you know how to use programming languages other than the Arduino's? Specifically, do you know languages that are good at text processing using regular expressions? For example, Perl, Python, Rubu, Go, awk, etc?

You'll be wasting your time tring to convert the code on a procedure by procedure basis.  Arduino has different libraries, different clocks, different pins, etc.
I suggest you flowchart the code, and then work out which of the Arduino libraries (SPI, LCD, etc.) you can use to achieve the flow.  You'll be able to drop some of the initialisation code probably as Arduino is easier to run "out the box".
There's no quick-and-easy solution here - it's a re-write... as you'll find is often the case migrating code from one MCU to another.


text:
How to send multi variable information over serial?
I would like to send information between my Arduino and my computer. Is there a way to send multiple variables from one Arduino? If so, how would I go about separating the variables?

This may help: http://electronics.stackexchange.com/a/79321/8627

You have three options for what you want to achieve (if I understand it right):

Have a fixed length for each variable: If I know each number is going to be two digits, I can send "1234" and the other side can figure out the numbers are "12" and "34".
Have a delimiter character: Have a character that signals a new variable. For example: "213|1234" would translate into "213" and "1234". You could even use the newline character to signal a new line (with Serial.println();).
Do some sort of validation to separate the data: If sending a favorite number and favorite color, I can send "12RED345BLUE" and the other side it can find that it's "12" (both numbers), then "RED" (all letters), then "345" (three numbers), and finally "BLUE" (again, all letters).

♦ can we do this like this as well? 'LI5' or something like this? 'LA4|LI5' or something like Serial.println('LA4|LI5'); Serial.println('LT2|LP3|LM5|LR4|LI6'); //close reverse will open thanks in advanced.

@Frank'sDesig'Nature there's no reason you can't do that; you would just have to have the appropriate processing on the other side to handle that

im not being allow to comment or edit so this is the only way for me to input my next comment "i really hate how this website works" Ok so now if i was to flood the serial with something like this: `gfhvfglfngvern98t34u05u305v4up0653utvp53t4t56526vgf5gvsd4gv6h4d65h4d63hbd4hb354g35gb435vb4zf35gdf35gb4d3v5h4vg3v5hb4fg6z24gv6dfgv4fd65vg2652f6g5hb74ki6k57n6v54sh64yul6oh4;g6fjd4g6wr5cg4yrdb68oin7n6ubj84g6jnujg4hm;l62g4kn6gfj42mjh6l54g6k5gf4dbhv16d5sg41tb6uh541jh1j34nfj35ffff4n4j2h3n14b5jgn352ghj3kj18hbuni5dj6tui5dty32hf3h1bgh3gfhvfglfngvern98t34u05u305v4@p0653utvp53t4t56526vgf5gvsd4gv6h4d65h4d63hbd

@Frank'sDesig'Nature (when I converted this into a comment some of your message got cut off) I'm not sure exactly what you're saying. Can you clarify?


text:
Measure square wave frequency
I'm working with the Arduino Due ans I used the following code:
// period of pulse accumulation and serial output, milliseconds
#define MainPeriod 100
long previousMillis = 0; // will store last time of the cycle end
volatile unsigned long duration=0; // accumulates pulse width
volatile unsigned int pulsecount=0;
volatile unsigned long previousMicros=0;

void setup()
{
  Serial.begin(19200);
  attachInterrupt(6, myinthandler, RISING);
}

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= MainPeriod)
  {
    previousMillis = currentMillis;
    // need to bufferize to avoid glitches
    unsigned long _duration = duration;
    unsigned long _pulsecount = pulsecount;
    duration = 0; // clear counters
    pulsecount = 0;
    float Freq = 1e6 / float(_duration);
    Freq *= _pulsecount; // calculate F
    // output time and frequency data to RS232
    Serial.print(currentMillis);
    Serial.print(" "); // separator!
    Serial.print(Freq);
    Serial.print(" ");
    Serial.print(_pulsecount);
    Serial.print(" ");
    Serial.println(_duration);
  }
}

void myinthandler() // interrupt handler
{
  unsigned long currentMicros = micros();
  duration += currentMicros - previousMicros;
  previousMicros = currentMicros;
  pulsecount++;
}

to measure the frequency.
I can measure frequencies higher than 1.5kHz accurately, but I can't seem to measure lower frequencies.
How can I measure lower frequencies, say 400Hz and above?
Thanks.

What is the output on a 400mHz wave? Just 0 and 0? Or wildly varying results?

It seems you have a problem of concurrent access to duration and pulsecount variables which are inter-related; with your code, it is possible that (and I guarantee that it will):

loop() reads duration value (in line unsigned long _duration = _duration;) but gets interrupted before executing the next line
myinthandler() changes both duration and pulsecount (it cannot be interrupted as it is already triggered by an interrupt)
loop() proceeds to where it was interrupted (after myinthandler() returns) and executes line unsigned long _pulsecount = pulsecount;: the values in _duration and _pulsecount do not match anymore!

To protect the access to pulsecount and duration variables, you have to disable interrupts inside loop() just for the time you get their values:
void loop() {
    ...
    // Disable interrupts while we get and reset duration and pulsecount
    cli();
    unsigned long _duration = duration;
    unsigned long _pulsecount = pulsecount;
    duration = 0; // clear counters
    pulsecount = 0;
    // Now we can re-enable interrupts again
    sei();
    ...
}


text:
Can I use the SVG headers on the SainSmart Uno to drive servos?
I am working with a Sainsmart Uno with SVG header pins.  This header is really convenient for hooking a servo to directly, so I have two servos connected to it on D9 and D10 and a 9v battery supplying power via the power jack.
Everything seems to work fine at first, but eventually (sometimes quickly), the board becomes unresponsive.  If, instead, I wire my servos to use the 5v pin on the Arduino (not from this SVG header), I don't run into this trouble.
Does anyone know if I am running into a limitation of this header Voltage pin?  Has anyone had any success using this mechanism to drive servos?  Certainly, I don't NEED to do it this way, but it sure is convenient.

Do you have a multimeter? Can you check where the voltage on that pin comes from? Looking online it seems there is a 5V and a 3.3V regulator. The 5V can supply 500mA, but the 3.3V only 50mA. Therefore it is the 3.3V going to the servos it is not enough. There is a switch on the front of the board that looks like it may change the voltage over.

Yes.  Good question @geometrikal.  I have the board switched into 5v mode, and the "V" pin on the header is reading as 5v.  But this pin switches based on the board voltage setting, which is different from the specific 5v and 3.3v pins on the other side of the board. Perhaps, because the SVG pins can switch between 3.3v and 5v dynamically, they could have limited it to 50mA.  That is my working hypotheses right now :)

It's probably best not to power your servos from the Arduino's regulator anyway, as servos are both power hungry and notoriously noisy.  Give them there own 5v regulator, and connect the grounds in common.

@ChrisStratton Yeah, that makes sense.  I just wonder what the utility of these SVG-style headers are if you can't plug a servo into them... but what you say makes sense.  That is how I have it wired right now anyways.  I was just hoping to use these headers.  They are sooooo convenient.


text:
Dimming 6W (24V DC 0.25A) LEDs using Arduino
I want to dim 24 LEDs which are powered by a transformer outputting 24V 6W at 0.25A
I am worried about temperatures, especially considering the circuit has to stay on for several hours keeping the LEDs off.
Would a TIP122 transistor be ok?
Any tips for keeping the transistor off until the dimming process starts?

I'd suggest using MOSFETs. The TIP122 has a 2V drop, so it will dissipate 0.5W worth of heat. MOSFETS will only dissipate a few milliwatts. To turn of the leds set the output pin to low. To make sure the led stays off on powerup, add a pull-down resistor to the PWM output-pin.

I would suggest using the CAT4101 constant current sink PWM LED driver.  It can handle up to 1A at up to 25V and deals with the constant current regulation for you - just provide at least the 24V you need and enough current capacity and connect the correctly calculated current setting resistor and the CAT4101 will do the rest for you.  You can then control it through the PWM input pin direct from the Arduino.

very interesting option, thanks! Would the NCP3065PG work as well? http://pdf1.alldatasheet.com/datasheet-pdf/view/196869/ONSEMI/NCP3065PG.html It's just because it would be easier for me to source it

I have not used that chip and not in a position to look right now.

just got the CAT4101 but I am a bit confused about how to calculate the resistor setting. The datasheet states that the LED current is mirrored from the current flowing from the RSET pin and then there's a table listing a few values matches. So I guess having 250 mA means I need a resistor around 2000 Ohm. Is there anyway to calculate the exact resistance?

I use 1.2 / (led current / 400) - it's not exactly like the table but close enough.  I have it as an online calculator: http://majenko.co.uk/?page=cat4101 The 400 comes from the datasheet: "RSET to LED Current gain ratio" on page 2.

All working pretty good. I just get a minuscule amount (almost of light from LEDs when the PWM is set to LOW. Could this mean that I need a slightly bigger resistor?
Also, having a problem of Arduino freezing after a short time, http://arduino.stackexchange.com/questions/18307/arduino-is-freezing-after-a-10-15-minutes could this be due to CAT4101?


text:
TMP36 probe reading 0 on analog
I've designed this system which is supposed to turn on the LEDs when the temperature of a particular probe exceeds 32 degrees. From what I can tell, this should be functional but the analog sensor is always reading 0 when calling analogRead() on the pin.
Here is an image of my circuit:

and my code:
int length = 5;
float airTemp = 32;

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

void loop()
{
  // loads current temperature into array
  int reading;
  float voltage;
  float temp[length];
  for (int i = 0; i < length; i++)
  {
    reading = analogRead(i);
    Serial.print(reading);
    voltage = reading * 5.0;
    voltage /= 1024;
    temp[i] = (voltage - 0.5) * 100;
  }

  // turns on/off fans based on current temperature
  for (int i = 0; i < length; i++)
  {
    pinMode(i, OUTPUT);
    if (temp[i] > airTemp)
    {
      digitalWrite(i + 8, HIGH);
    }
    else if(temp[i] <= airTemp)
    {
      digitalWrite(i + 8, LOW);
    }
  }
  delay(1000);
}

I learned how to read the temperature from here. It's probably a dumb mistake, but I just started working with Arduino yesterday and I couldn't find information anywhere so thanks in advance.

Nice example @user2985955. Did you know you can improve the precision of the analog readings by using an aref voltage? See http://tronixstuff.com/2013/12/12/arduino-tutorials-chapter-22-aref-pin/ and https://123d.circuits.io/circuits/1147792-simple-temperature-sensor/

The image on the linked tutorial has the middle pin of the TMP036 going to the analog input, whereas you have it going to 5V, so that is not going to help one bit.
In other words, it is wired wrongly.

Thanks. I realized this just before you answered and posted some pictures to help anyone else.

I figured it out. I had the temperature sensors wired wrong.
Old (Bad):

Good:

Make sure your breadboard isn't one of the ones with split power rails.  If the coloured lines on the + and GND rails have a break in them you will need to bridge that break with wire.
Solid rail:

Split rail:

Right now I've only designed the circuit online in an emulator which has a solid rail. I'm pretty sure it is a programming problem on my end.

@user2985955 It would have been nice to know that little nugget before...  Have you considered that the simulator you're using doesn't work?  Try it on real hardware and then come back with your real results.


text:
HTTP Post not working
I am wanting to POST some data from Arduino to WebService (written in .NET), intending to save some temperature data to MS SQL Server.
My code in arduino is:
void PostarDados(String dados, String chamador) {
  if (client.connect("mysite.com.br",80)) {
    client.println(chamador);
    client.println(F("Host: mysite.com.br"));
    client.println(F("Content-Type: application/x-www-form-urlencoded"));
    client.print(F("Content-Length: "));
    client.println(dados.length());
    client.println();
    client.println(dados);
  }
  if (client.connected()) client.stop();
}

When sending to Serial instead of client, I am obtaining the following text:
POST /webservice.asmx/SetValoresTempUmidade HTTP/1.1
Host: mysite.com.br
Content-Type: application/x-www-form-urlencoded
Content-Length: 39

Chave=1&Temperatura=23.30&Umidade=42.20

I have enabled HTTP POST in web.config to make HTTP POST possible (I can successfully invoke webservice from browser):
  <location path="Webservice.asmx">
    <system.web>
      <webServices>
        <protocols>
          <add name="HttpGet"/>
          <add name="HttpPost"/>
        </protocols>
      </webServices>
    </system.web>
  </location>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

I have also set ScriptMethod to my webservice functions:
<WebMethod()> <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Sub SetValoresTempUmidade(Chave As Integer, ByVal Temperatura As Double, ByVal Umidade As Double)
    Dim ctx As New DataClassesDataContext
    Try
        Dim A As New TBL_DADO
        A.CHAVE_INICIO = Chave
        A.DATA = Now
        A.TEMPERATURA = Temperatura
        A.UMIDADE = Umidade
        ctx.TBL_DADOs.InsertOnSubmit(A)
        ctx.SubmitChanges()
    Catch ex As Exception
    End Try
End Sub

Finally, I am trying to get some response from server using the following code (not receiving anything):
while (client.connected()) {
  while (client.available()) {
   buffer[counter++] = client.read();
  }
}

Explained that, I have two questions:

What am I doing wrong?
How could I debug this?

I think PostarDados() is missing to \r\n\r\n at the end of the HTTP message

Thanks, but it didn't work

You're hiding any errors  in your webservice method as there is nothing between your Catch and End Try. My first action would be to add logging in there to see if anything is going wrong there.

I would also try to code up a simple GET request webservice - just to simplify things and to make sure the requests are getting to the webservice at all...

Using
byte server[] = {XX, XX, XX, XX}; //IP
if (client.connect(server,80)) {

instead of
if (client.connect("mysite.com.br",80)) {

worked


text:
How many clients can connect to an ESP32?
I am using an ESP32 as my master and 10 ESP8266-07s are connected to the master that is in AP mode.
But I need at least 12 clients.
Please help me to increase the number of clients the ESP32 can handle in AP mode.
I have read this article but it did not help me
ESP32 AP max connections: 4 or 10?

have you considered ESP-NOW? it can handle more clients and traffic since it has lower overhead than wifi

esp-now is not secure to me.i think the better way is mesh.but its too force for me right now.so i add aother esp32 in my master and then connect both esp32 by serial to together.and then any of them can conect to 10 client and 1 on the esp32 control and calculate every thing

The max number of stations for SoftAP is a runtime setting available in Arduino.
ESP32 arduino WiFi library and esp8266 ESP8266WiFi library have it as last parameter in softAP() function which starts the SoftAP.
bool softAP(const char* ssid, const char* passphrase = NULL,
    int channel = 1, int ssid_hidden = 0, int max_connection = 4);

esp8266 arduino doc

max_connection - optional parameter to set max simultaneous connected
stations, from 0 to 8. Defaults to 4. Once the max number has been
reached, any other station that wants to connect will be forced to
wait until an already connected station disconnects.

ESP32 SDK doc

uint8_t max_connection   Max number of stations allowed to connect in,
default 4, max 10

this code is in the 254 i think,i changed it also.no result!!!

The SDK API documentation from Espressif directly notes:

uint8_t max_connection
Max number of stations allowed to connect in, default 4, max 4

EDIT
However, another area of the API documentation (The API Guide) notes:

max_connection
Currently, ESP32 Wi-Fi supports up to 10 Wi-Fi connections. If
max_connection > 10, soft-AP defaults the value to 10.

strange. I do not believe this. it must be a copy-paste error (from esp8266 doc?). it has two processors

Perhaps so. I found another place in the API Guide which implies that 10 is the max.

If you use softAP, you can set the max number of connections to 16 I believe.
WiFi.softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden, int max_connection);

i use soft ap ,and realy thiscode,and changed the code  max connection to 16,but didnt worked.is the chanel numer important?

i should do it,so i must try any idea which everyone suggest me