text:
How to determine the minimum time for a servo to reach its destination?
We all know servos don't move instantly, which is why it is common to put a delay or a millis() loop whenever you issue a servo.write() command to give it time to reach its target before moving on to the next thing.
What irks me though is that this could be inefficient in situations where the last servo position might be close to its target - you might only need a very short delay in those cases, whereas if it has to sweep the full 359 degrees, you might want more time.
I was disappointed that servo.read() is completely useless for this task (why even include it in the library?) as the following code illustrates:
#include <Adafruit_TiCoServo.h>
Adafruit_TiCoServo servo;
const uint8_t PIN_SERVO = 9;

void setup() {
  servo.attach(PIN_SERVO);
  Serial.begin(9600);

  Serial.println("start");
  servo.write(180);
  delay(1000);

  int pos;
  while(pos != 0){
    pos = servo.read();
    Serial.println(pos); // because it only returns what the last write() operation
                         // was sent, it immediately thinks it's at pos 0 and exits.
    servo.write(0);
  }

  Serial.println("Done");
}

So that sucks. It seems that my options are:

just use a long delay that accommodates the worst-case scenario. I hate this.
add a limit switch at the final target position and just read the state of that switch
build some kind of elaborate encoder that you can read an absolute angle from or buy a more expensive servo that can tell you this info

For reference the servo I'm playing with is a hobby servo: MG90S
Specifically my question is to confirm that there are no other options available for the MG90S other than what I've listed above.

What exactly are you trying to achieve? Which solution is the best depends on the actual target of your project. If you only want to wait for the servo to finish moving before continuing with your code, how about scaling the delay linearly with the angle difference? You can find the factor by testing it yourself. Also keep in mind, that this is also dependent on the load on the servo axle.

@jsotola sure fair enough, but I'll leave it to you to skip the parts you consider offensive and focus on an answer. And to you other comment, fair point - I have attempted to make it more obvious what I'm asking. You know how these questions go - you start to write them and end up writing more of a solution than you expected to. But I still want to know from others whether there are other approaches.

I regard servo.read() as a convenience function. I do not need to remember the last target position, I can ask the object, across other functions and methods. No hobby servo I know feeds back the actual position, because they are usually used in radio-controlled models, which have no feedback path.

in this case there is mostly one simple solution, and there are some better ones.
the problem you faced with the method:
First of all, the read() function indeed only returns what you send to it, it mostly is useful for if you want to know what position you send it to in some other part of code(for example can be used to plan what way to go first if you need to go to many points, or if you already are going to the desired position).
but since the rc servo has only one signal wire and that wire sends no signals back you don't know what state they are in, rc servo's are mostly for ease of use and not for accuracy and speed, if you need that you can look into a real servo(stepper motor).
so yes that function doesn't return the actual position, it returns the desired position.
Solution1: the easy software based method: to do this you can either read the datasheet to read the speed in duration per degree or measure it, and then use that to calculate the time it would take.
actually here the Servo.read() function really comes in use, so this is a perfect example of why you would actually sometimes need or want it.

save the duration in miliseconds per degree in a variable.
next just before you write to the servo use Servo.read() to get the current theoretical position and use that combined with the position you want to go to calculate the difference in dergees (for example 100 and 40 results in a difference of 60), then multiply that with the duration per step. and you will have the answer of how long a change would take.

Example1 warning, untested, might contain spelling mistakes and such
    /* tuned delay Sweep
  This example code is in the public domain.
  No warranty

  modified 27 March 2023
  by Daan V.Loon
*/

#include <Servo.h>
#define DELAYPERDEGREE 2 //this is the value for the sg90 servo from the datasheet(0,12s(120ms)per 60degrees.
#define SAFETYMARGIN 110 //this is to add 10% extra time to wait, to make sure it finishes in time even under load.
//# define is used kind of like a variable that doesn't need to change, purely in code and not in ram
unsigned long waitDuration=0;//variable that shows how long to wait.

Servo myservo;

unsigned long CalcWait(Servo s,int desiredPosition)//method to calculate and return duration to wait in ms 1000ms is 1 s.
{
  int spos=s.read();
  if(spos>desiredPosition){return (((spos-desiredPosition)*DELAYPERDEGREE)*SAFETYMARGIN)/100;}
  else{ return(((desiredPosition-spos)*DELAYPERDEGREE)*SAFETYMARGIN)/100;}
}//end of method

void ServoAndWait(int pos){
  //insert range limiting code here if needed, warning this method doesn't check if you try to use numbers bigger or smaller than your servo or the servo library can actually handle.
  waitDuration=CalcWait(myservo,pos);//call method to update how long to wait, needs to be done before telling the servo to move.
  myservo.write(pos);//tell servo to rotate
  delay(waitDuration);//blocking wait for servo to complete
}
void setup() {
  myservo.attach(2);
  ServoAndWait(180);//rotate to 180 degrees and wait until it should be there+10% with the safetymargin of 110
}

void loop() {
    ServoAndWait(0);
    ServoAndWait(180);
    //this should reult in the famous sweep example, however then at the max speed of your servo, this way you can test it.
    //to optimize speed use a safetymargin far over 100(like 200 or such) then reduce it until you see it just stop or just not stop anymore at the edges.
    //also make sure to first test if your servo can actually handle 0 and 180 degrees, for example first test if it moves if you tell it to go from 10 to 0 and from 170 to 180, not all servos reach the full 180 degree range.

  }

Example2:(no comments)
/* tuned delay Sweep
  This example code is in the public domain.
  No Warranty

  modified 27 March 2023
  by Daan V.Loon
*/

#include <Servo.h>
#define DELAYPERDEGREE 2
#define SAFETYMARGIN 110
unsigned long waitDuration = 0;
Servo myservo;

unsigned long CalcWait(Servo s, int desiredPosition)
{
  int spos = s.read();
  if (spos > desiredPosition) {
    return (((spos - desiredPosition) * DELAYPERDEGREE) * SAFETYMARGIN) / 100;
  }
  else {
    return (((desiredPosition - spos) * DELAYPERDEGREE) * SAFETYMARGIN) / 100;
  }
}

void ServoAndWait(int pos) {
  waitDuration = CalcWait(myservo, pos);
  myservo.write(pos);
  delay(waitDuration);
}
void setup() {
  myservo.attach(2);
  ServoAndWait(180);
}

void loop() {
  ServoAndWait(0);
  ServoAndWait(180);
}

Example3: Shorter and more stack overflow alien themed for people who just copy paste or find this clearer
/* tuned delay Sweep
  This example code is in the public domain.
  No Warranty

  modified 27 March 2023
  by Daan V.Loon
*/

#include <Servo.h>
#define DELAYPERDEGREE 2
#define SAFETYMARGIN 110

Servo myservo;

unsigned long CalcWait(Servo s, int desiredPosition)
{
  int spos = s.read();
  return (spos>desiredPosition?((spos - desiredPosition) * DELAYPERDEGREE * SAFETYMARGIN) / 100 : ((desiredPosition - spos) * DELAYPERDEGREE * SAFETYMARGIN) / 100);
}

unsigned long waitDuration = 0;
void ServoAndWait(int pos) {
  waitDuration = CalcWait(myservo, pos);
  myservo.write(pos);
  delay(waitDuration);
}

////---code you would see below, headers and functions and variables above---////
void setup() {
  myservo.attach(2);
}

void loop() {
  ServoAndWait(0);
  ServoAndWait(180);
}

These above should be fully functional codes that should work for you, they all work the same. I didn't test it with a servo however, but the logic worked when I tested that. also make sure to change the delay per degree to whatever your datasheet says, in this case the datasheet said 0.12s/60 degrees sg90(very common servo for arduino) so I turned seconds into miliseconds and divided it by 60, so 120/60=2, if you have a much faster servo or need more accurate results for different servos you can use the safety margin to tune, or you can use microseconds in the calculations or such, or just multiply the numbers by 10 and then at the end of the calculations divide it by 10 before returning.
Then here is also the more difficult hardware version
to do this you can either try to use the servo's buildin hardware and modify the servo with a 4th wire, either add it to the rotation sensor/potentiometer, or add it to the chip if it has a place where you can read it directly, with this you are on your own however since it is very speciffic for every servo.
a more easy way to do this is to use a compactor(or something else that gives you one digital output(typical rc servos will always keep the motor on,and just very rapidly change direction once they are on position, if it actually stops you might just want to read it like a normal digital signal(perhaps do something to protect against motor spikes), and read the wires both standalone instead of comparing them to each other) to compare the voltages on the wires to the motor in the servo, since when it moves one side has a higher voltage than the other side, when it stops, they either are equal or rapidly change to keep position. so you just check for whenever it changes. or if you know the direction you can be even more accurate and fast. this ofcource requires you opening up the servo.
or you can indeed add something like a rotary encoder, no need for a complex one, since you can just count the stripes and if you suddenly don't get changes anymore the servo is also stopped in case you missed some, or you can use something like a small microphone or vibration meter since the servo when it moves, this however may become inaccurate under higher load.
just try to avoid reading it with analog signals, since for what you want to use it for analog signals can be really slow.
also
you might want to look into non blocking delays, it won't make the servo's faster, but it allows you to do other things while the servo is moving so you won't have to wait until it is finished.

Re solution 1: I would expect the servo speed to depend on the load, which would invalidate any computation based on a fixed speed.

Thanks for this detailed answer. The project is long over (I can't remember which workaround I ended up using), but I'll definitely be looking this up the next time I'm playing around with RC servos!

@EdgarBonet partly yes, depends on the servos partly how much so, but in typical loads where the servo isn't really overloaded it should behave similar to what is stated in the datasheet, when it is overloaded you might want to measure it instead(also mentioned that), but I also speciffically added the SAFETYMARGIN to the code for hat speciffic thing, it allows you to set a safety margin or finetune code so that it works well. most cases where a servo needs to move and all else needs to stop then would be a quite controlled proces, so less expectations for strange behaviour.

but indeed when a servo is constantly under different load it might have slightly different speeds, so you will need one of those hardware modifications like the ServoMotorWireReadWires method I added below the code, but software is almost always a tradeoff compared to hardware. but as long as the servo isn't overloaded or close to it it should typically be around the speed in the datasheet, or faster. since often for the speed in the datasheet they take the speed under load(even though that differs per manufacturer and the amount of load as well.
reading motor wires instantly shows changes.

Yes, normally servo.read() is pretty useless.
First, check your library with a sketch like this
void setup() {
  servo.attach(PIN_SERVO);
  Serial.begin(9600);

  Serial.println("start");
  servo.write(180);
  delay(1000);
  unsigned long start = millis();
  servo.write(0);
  unsigned long duration = millis() - start;
  if (duration <= 1)
     Serial.println("servo.write() returns immediately");
  else {
     Serial.print("servo.write() takes ");
     Serial.print(duration);
     Serial.println(" ms for a 180° move");
  }
}

If it returns immediately, you have to really measure somehow the actual speed and eventually follow chrisl's comment.


text:
Why doesn't this debounce function work?
Edit 2
I made a function that works, but I'm still confused about just one thing...
I'm very confused about how variables work in C++.
In this program...
  boolean debounce(void)
{
  static boolean buttonState=LOW;
  static boolean lastButtonState;
  boolean currentState = digitalRead(4);
  static unsigned long lastDebounceTime;
  if (currentState != lastButtonState){ //if the button state has changed
    lastDebounceTime=millis();  //reset timer
    }

  if ((millis()-lastDebounceTime) > 50)  //if 50 milliseconds has passed since last bounce
  {
    buttonState = currentState;  //read value again now that bouncing is over

    }
  lastButtonState = currentState;
  return buttonState;
}

Why does changing this
lastButtonState = currentState;

To this
lastButtonState = buttonState;

Make any difference in the program?
When I try the latter line of code, the whole function stops working and I don't understand why.

What happens if 50ms haven't passed?

Using the same name for globals, locals & function parameters is just begging for confusion.

@uint128_t - Why do you say: "debounce() function is only being called every 500ms" ? I don't see that, what have I missed?

@gbulmer he edited his question

at least: static boolean buttonState;

You have declared a global 'const int buttonVal = LOW' but then using this same name to get a parameter from a function. I would suspect that the global declaration is what you are getting. At the very least, use a different variable name within the local scope of the loop function.

This probably won't answer your question completely, but here are some notes from me:
buttonState = current ;  //read value again now that bouncing is over

This won't read the value again, it just copies current into buttonValue.
What you wanted is:
buttonState = digitalRead(BUTTON); // read value again now that bouncing is over

You have multiple issues with your debounce call:

lastTimeDebounce is never used by your code, so it is always zero.
lastButtonState will be always buttonVal making the debounce function useless.

Some other tips:

Don't use the same names for parameters as for global variables:
boolean debounce(boolean lastButton, long lastDebounce, int BUTTON)
The global variable BUTTON will be shadowed by int BUTTON, essentially overriding it.
Don't use global variables (unless you have a very good reason)

EDIT
I would strongly recommend writing a function that debounces only one pin.
Because if you want a function which can debounce any pin you would need a state variable for each pin (which needs arrays hence a lot of space).
EDIT2:
Here is a debounce function that should work:
const uint8_t PIN = 13;

/*
 * Returns debounced value for `PIN`
 */
boolean debounce(void)
{
    // Current state of the pin
    boolean currentState;
    // Last state of the pin, initial value is zero
    static boolean lastCurrentState = 0;
    // Timer
    static unsigned long debounceTimer = millis();
    // Debounced value, initial value is zero
    static boolean debouncedValue = 0;

    // We first read the current state of the pin
    currentState = digitalRead(PIN);

    // Then we look if the state has changed
    if (currentState != lastCurrentState) {
        // If it has, we need to reset the debounce timer
        debounceTimer = millis();
    }

    // Then we check if the timer has expired
    if ((millis() - 50) > debounceTimer) {
        // The timer expired so we update the value
        debouncedValue = currentState;
    }

    // Save the latest state
    lastCurrentState = currentState;

    // We always return a debounced value:
    return debouncedValue;
}

But always test such things with an oscilloscope, no guarantee. FYI: this is not an ideal debounce function, but it should make the idea clear.

"buttonState = current ;
This won't read the value again, it just copies current into buttonValue." I'm not questioning that your right, but I actually copied the official arduino website when I did this. https://www.arduino.cc/en/Tutorial/Debounce

The Arduino site does not make the statement that it is actually reading the pin again.

Ok I understand now. I made my code look like yours, and my function works now. Thanks for the help. Quick question though, why does "lastCurrentState = currentState" have to go outside of the if statement?

You could add an else and add it there and it won't affect the debouncing. I just put it there for convience.

Sorry maybe I'm still a little confused... The second if statement will be executed no matter what right? ( because the program can't exit the function unless 50 millis have passed). If this is true, why can't I put "lastCurrentState = currentState" within the second if statement?

The body of the second if statement will only be executed if the button state has not changed over the last 50 milliseconds. I'm not sure what you are asking but you always want the latest state in a variable to check on it later.

Glad to hear :) no problem.

"It worked perfectly" is probably an overstatement. Yes, you saw the LED change when you pressed the button, but that doesn't mean it was getting debounced.
The problem is that you are trying to use global variables to remember the internal state of the debouncer function, and you're passing those variables into the function as parameters. In C (or C++, which is the underlying language that you're using), an assignment to a function parameter does NOT update the corresponding variable in the caller's environment. Therefore, lastDebounceTime never gets updated, and your debounce() function always just returns the current state of the button.

Beat me to it! +1 for "It worked perfectly" is probably an overstatement. Yes, you saw the LED change when you pressed the button, but that doesn't mean it was getting debounced.. A quick (possible) fix is to remove the parameters to debounce() and keep the state in global variables. A bit messy, but more useful than broken.

Thank you for your answer @Dave, I think I'm starting to understand. But quick question, what do you mean by "an assignment to a function parameter does NOT update the corresponding variable in the callers environment"? Does this mean assigning a variable to a function parameter is pointless?

No, it isn't entirely pointless, because you can use it as an additional local variable inside the function. You can think of it as the caller initializing that variable for you, but then you can update it as needed while the function executes.

@gbulmer or use static variables private to debounce()

@Jasen - Yes, that would be better. C++ classes are a bit verbose (I like to write Go) but a simple class would do, or a struct if there were several buttons to handle.

Im not an expert of C programming, but I can see lot of troubles in your programming, because you do call a function debounce(), but it is not a function that does a complete task, so you set additional variables outside of it. This is a bad practice, because you can't call the same function to compute multiple keys, that's what functons are for - make one function and call multiple times with different parameters. You should switch to pointer orented parameters for lastButtonState.
    boolean LastButton_1; // global or static variable
    long LastDebounce_1;
    int BUTTON_1;
        ... and so on

    boolean debounce(boolean *LastButton, long *LastDebounce, int BUTTON)
        {
          //your code here, where you read and write to variables located at pointer
           boolean something, new_value;
           something = *LastButton; //read value at pointer address
           *LastButton = new_value; //store the value at pointer address
        }
//now you call this
debounce(&LastButton_1, &LastDebounce_1, BUTTON_1)

Perhaps it is not correct, since I know only very basic C, but the way is the right one

If you only have one button to debounce, you can store it's state as
static variables in the debounce() function itself, like:
bool debounce()
{
    const int pin = 4;
    static bool last_state;
    static unsigned long last_change;
    unsigned long now = millis();

    if (now - last_change > 50) {
        bool state = digitalRead(pin);
        if (state != last_state) {
            last_change = now;
            last_state = state;
        }
    }
    return last_state;
}

If you may have to debounce more than one button, the cleaner way would
be to store the state inside an object, and have the debounce function
be one of its methods. That's what the
Bounce library does.

Strictly speaking, digitalRead() returns an int not a bool.

source: Stack Exchange

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

sort: votes


text:
Simple GET request is failing silently
I'm trying to make a simple GET request to a server (which has a static IP but does not have a name). I'm using EtherCard library and a cheap ENC28J60 Ethernet Module. The basic configurations are OK (I can get DHCP assignment and DNS lookup), but when I try to make a simple GET request with the browseUrl method, nothing happens. I've tried to call the page from the browser and everything works fine, so it's not a server issue. The code is the following:
#include <EtherCard.h>

// ethernet interface mac address, must be unique on the LAN
byte mymac[] = { 0x54, 0x55, 0x58, 0x10, 0x00, 0x24 };

const char website[] PROGMEM = "http://10.10.10.10"; // my server
const char dnsLook[] PROGMEM = "google.com";

byte Ethernet::buffer[700];
uint32_t timer;
Stash stash;

// called when the client request is complete
static void requestCallback (byte status, word off, word len) {
  Serial.print(">>>");
  Serial.print(status);
  Serial.print("-");
  Serial.print(status);
  Serial.print("-");
  Serial.print(status);
  Serial.println("<<<");
}

void setup () {

  Serial.begin(9600);
  delay (10000);
  int res = ether.begin(sizeof Ethernet::buffer, mymac, 8);

  if (res == 0)
    Serial.println( "Cannot access ethernet interface");

  const static uint8_t ip[] = {192,168,1,117};
  const static uint8_t gw[] = {192,168,1,1};
  const static uint8_t dns[] = {8,8,8,8};

  if (!ether.staticSetup(ip, gw, dns))
  {
      Serial.println("Cannot set static parameters");
  }

  // manually set netmask
  ether.netmask[0] = 255;
  ether.netmask[1] = 255;
  ether.netmask[2] = 255;
  ether.netmask[3] = 0;

  // dns lookup
  if (!ether.dnsLookup(dnsLook))
    Serial.println("DNS failed");
}

void loop () {
  ether.packetLoop(ether.packetReceive());
  if (millis() > timer) {
    timer = millis() + 10000;
    ether.browseUrl(PSTR("/page.php?"), "var=value", website, requestCallback);
  }
}

run example code first

I recommend you to use my EthernetENC library

@Juraj I'll give a try

I made it by using EthernetENC library, as suggested by @Juraj.
To install the library, simply use the library manager and search for EthernetENC.
For those in need, below is a working code
#include <SPI.h>
#include <EthernetENC.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };  // ethernet module MAC address
IPAddress server(10,10,10,10);                        // server IP address, without DNS
//char server[] = "www.site.com";                     // if your server has a DNS name, use this variable for connection

// static configuration variables
IPAddress staticIp(192, 168, 1, 217);
IPAddress staticDnsServer(8, 8, 8, 8);

EthernetClient client;                                // ethernet client object

void setup() {
  // configure CS pin
  Ethernet.init(8);

  // begin serial connection
  Serial.begin(9600);

  // wait some seconds to let the module start
  delay(5000);

  // initialize ethernet module with static configuration
  Ethernet.begin(mac, staticIp, staticDnsServer);

  // wait to let the module properly initialize
  delay(1000);

  // connection to the server
  Serial.print("Connecting to: ");
  Serial.print(server);
  Serial.println("...");

  // notify successful connection
  if (client.connect(server, 80)) {

    Serial.print("Connected to ");
    Serial.println(client.remoteIP());

    // simple GET request
    client.println("GET /page.php?var=test HTTP/1.1");
    client.println("Host: 10.10.10.10");
    client.println("User-Agent: Arduino/1.0");
    client.println("Connection: close");
    client.println();

  } else {
    // connection failed notifiation
    Serial.println("Connection failed");
  }
}

void loop() {

  // if I got a response from the server, read and print to serial
  int len = client.available();
  if (len > 0) {
    byte buffer[80];
    if (len > 80) len = 80;
    client.read(buffer, len);
    Serial.write(buffer, len);
  }

  // disconnection
  if (!client.connected()) {

    Serial.println();
    Serial.println("Disconnected");
    client.stop();

    // stop execution
    while (true) {
      delay(1);
    }
  }
}

at this link, you can see how to properly connect this module to Arduino UNO.

you can lower the flash and memory usage with settings in utility/uipethernet-conf.h https://github.com/jandrassy/EthernetENC/wiki/Settings the most interesting setting is UIP_CONF_UDP

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


text:
Impossible to connect ESP32 with Mosquitto on Raspberry using certificates
I installed Mosquitto broker in Raspberry in my local network.
I generated certificates in Raspberry as follows:
sudo openssl genrsa -out ca.key 2048
sudo openssl req -new -x509 -days 3600 -key ca.key -out ca.crt
sudo openssl genrsa -out server.key 2048
sudo openssl req -new -out server.csr -key server.key
sudo openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 3600

I modified the Mosqutto configuration file (.conf) as follows:
allow_anonymous false
cafile /etc/mosquitto/certs/ca.crt
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
tls_version tlsv1.2

I restarted Mosquitto everything ok
I downloaded the ca.crt file from Raspberry to my PC with Filezilla
from my PC I use MQTT.fx to connect I set the certificate.
WORKS WELL
The problem:
with ESP32 I can't connect when I set the certificate with espClient.setCACert(ca_cert);
MQTT connecting ...

[E] [ssl_client.cpp: 33] handle_error (): X509 - Certificate
  verification failed, e.g. CRL, CA or signature check failed

Someone can help me, I can't understand if something is missing in the code or there is some error in generating the certificates
Please help
many thanks Michael
this is my code:
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ESPmDNS.h>

/* change it with your ssid-password */
const char* ssid = "XXXXXX";
const char* password = "XXXXXXX";
/* this is the MDNS name of PC where you installed MQTT Server */
const char* serverHostname = "home";

const char* ca_cert = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIDmDCCAoCgAwIBAgIJAKV4GE+4y/G4MA0GCSqGSIb3DQEBCwUAMGExCzAJBgNV\n" \
"BAYTAlRWMRAwDgYDVQQIDAdUcmV2aXNvMRUwEwYDVQQHDAxDYXN0ZWxmcmFuY28x\n" \
"DDAKBgNVBAoMA1BTUzEMMAoGA1UECwwDUFNTMQ0wCwYDVQQDDARob21lMB4XDTE5\n" \
"MDkwODE3NDIzOFoXDTI5MDcxNzE3NDIzOFowYTELMAkGA1UEBhMCVFYxEDAOBgNV\n" \
"BAgMB1RyZXZpc28xFTATBgNVBAcMDENhc3RlbGZyYW5jbzEMMAoGA1UECgwDUFNT\n" \
"MQwwCgYDVQQLDANQU1MxDTALBgNVBAMMBGhvbWUwggEiMA0GCSqGSIb3DQEBAQUA\n" \
"A4IBDwAwggEKAoIBAQC2rPN7VQXtzLCl1LufJkzLK9xedrbW72K2vBZ34VNOl+tG\n" \
"ffNx2QQLQC0Jh5GzB79dZweqAjCRBbIEpx0IGvHWrHDUQMJrvg4BcmDr0eqNCup/\n" \
"tBItlEcCdvmWFfm3IBezOVBDFiQWmC4jvAC/G3DPlftHiPI1k3cDewKNJEJykxeD\n" \
"8H/4KTAz+wJXyGZiviZYv8OYOTRMa3nEhg1vaQTMgCwEVBavg5fsEQkZLArBNJQM\n" \
"Gmw0qDdJEMDGOGWPogxRAKrxvNnXr4mIebzPj9/UTrJnfzVOPEHZ9Uz5BU/psGCL\n" \
"cnMkBeNEa/JyLR14Hu8e+xa/pOCpJ9Dqhi/BTji5AgMBAAGjUzBRMB0GA1UdDgQW\n" \
"BBRIz+15SpOBqo0O+vOtgYvPj4LqWDAfBgNVHSMEGDAWgBRIz+15SpOBqo0O+vOt\n" \
"gYvPj4LqWDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQC08Crs\n" \
"w7LPX+Bd80NwPuxgBmMU4U/pCw8AyzzSgckHmay0K8KuHXhSvZjdl6i0gjG/2xLa\n" \
"ghCtfFGIXPu1Lu226bhTWigmuFLYasG1MivTDz2LeUTFPQrtEO8KdsRUarPZW3Fj\n" \
"nOMyVDdzE4+HxvzvARDc1QbE9SX2ozQcNKQp4oRpunfT2+/OyzYgfMVA7MVKvehX\n" \
"VH49fRF1P1Ajizqr2eHDFImcMQTzepRT7IjfOiQ/8PoqrZGvGenMj5so1I9MtgyK\n" \
"gVUf1ZWPBgxmhVfla6vYBZiTGuZMHSDuF6/yFC1QnoXVq7K+bbIhAE8lsPNuOY7V\n" \
"dKidKIfBJiN378CC\n" \
"-----END CERTIFICATE-----\n";

/* create an instance of WiFiClientSecure */
WiFiClientSecure espClient;
PubSubClient client(espClient);

/*LED GPIO pin*/
const char led = 5;

/* topics */
#define COUNTER_TOPIC    "smarthome/room1/counter"
#define LED_TOPIC     "smarthome/room1/led" /* 1=on, 0=off */

long lastMsg = 0;
char msg[20];
int counter = 0;

void receivedCallback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message received: ");
  Serial.println(topic);

  Serial.print("payload: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  /* we got '1' -> on */
  if ((char)payload[0] == '1') {
    digitalWrite(led, HIGH);
  } else {
    /* we got '0' -> on */
    digitalWrite(led, LOW);
  }

}

void mqttconnect() {
  /* Loop until reconnected */
  while (!client.connected()) {
    Serial.print("MQTT connecting ...");
    /* client ID */
    String clientId = "ESP32Client";
    /* connect now */
    if (client.connect(clientId.c_str(),"XXXXX","XXXXXX")) {
      Serial.println("connected");
      /* subscribe topic */
      client.subscribe(LED_TOPIC);
    } else {
      Serial.print("failed, status code =");
      Serial.print(client.state());
      Serial.println("try again in 5 seconds");
      /* Wait 5 seconds before retrying */
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(9600);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  /* set led as output to control led on-off */
  pinMode(led, OUTPUT);

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  /*setup MDNS for ESP32 */
  if (!MDNS.begin("esp32")) {
      Serial.println("Error setting up MDNS responder!");
      while(1) {
          delay(1000);
      }
  }
  /* get the IP address of server by MDNS name */
  Serial.println("mDNS responder started");
  IPAddress serverIp = MDNS.queryHost(serverHostname);
  Serial.print("IP address of server: ");
  Serial.println(serverIp.toString());
  /* set SSL/TLS certificate */
  espClient.setCACert(ca_cert);
  /* configure the MQTT server with IPaddress and port */
  client.setServer(serverIp, 26391);
  /* this receivedCallback function will be invoked
  when client received subscribed topic */
  client.setCallback(receivedCallback);

}
void loop() {
  /* if client was disconnected then try to reconnect again */
  if (!client.connected()) {
    mqttconnect();
  }
  /* this function will listen for incomming
  subscribed topic-process-invoke receivedCallback */
  client.loop();
  /* we increase counter every 3 secs
  we count until 3 secs reached to avoid blocking program if using delay()*/
  long now = millis();
  if (now - lastMsg > 3000) {
    lastMsg = now;
    if (counter < 100) {
      counter++;
      snprintf (msg, 20, "%d", counter);
      /* publish the message */
      client.publish(COUNTER_TOPIC, msg);
    }else {
      counter = 0;
    }
  }
}

See https://github.com/espressif/arduino-esp32/issues/2875 and https://github.com/TwilioDevEd/sync-for-iot-examples/blob/master/Espressif_ESP32/Quickstart/certificates.hpp. Does it work when adding R in front of the string constant for the ca_cert?

Hi Maximilian,
I tried as recommended but I get the same error even with the R     -
MQTT connecting ...[E][ssl_client.cpp:33] handle_error(): X509 - Certificate verification failed, e.g. CRL, CA or signature check failed
[E][ssl_client.cpp:35] handle_error(): MbedTLS message code: -9984
[E][WiFiClientSecure.cpp:132] connect(): start_ssl_client: -9984     -
do you have any suggestions for me?

Do you have a full mbedtls log for the whole session? You might need to set debug level to the most verbose in the Arduin IDE then.

I found the solution, the problem was related to the generation of certificates.
The OU must be different for each file generated. SUBJECT_CA="/C=SE/ST=Stockholm/L=Stockholm/O=himinds/OU=CA/CN=192.168.0.11"
SUBJECT_SERVER="/C=SE/ST=Stockholm/L=Stockholm/O=himinds/OU=Server/CN=192.168.0.11"
SUBJECT_CLIENT="/C=SE/ST=Stockholm/L=Stockholm/O=himinds/OU=Client/CN=192.168.0.11"

Good morning, first I would like to say that I am Brazilian, so I'm using the translator, if something goes wrong please do not care. Come on, I have the same problem, I believe it is problem in the certificate rsrs, could you tell me please, how did you solve your problem? thanks.

@Michele You can post that as an answer

Thanks for your help, but can you please tell me which folder I create this script in? I still have the same problem.
thanks

Hi, it is not important which script you create, however
from home of raspberry,
mkdir test,
cd test,
sudo nano test.sh and paste the script and save.
chmod +x test.sh
then run the script with ./test.sh

@sempaiscuba and Bruno I solved by regenerating the certificates in this way
you have to do this comfortably script in Raspiberry
#!/bin/bash

IP="192.168.0.11"
SUBJECT_CA="/C=SE/ST=Italy/L=Roma/O=himinds/OU=CA/CN=$IP"
SUBJECT_SERVER="/C=SE/ST=Italy/L=Roma/O=himinds/OU=Server/CN=$IP"
SUBJECT_CLIENT="/C=SE/ST=Italy/L=Roma/O=himinds/OU=Client/CN=$IP"

function generate_CA () {
   echo "$SUBJECT_CA"
   openssl req -x509 -nodes -sha256 -newkey rsa:2048 -subj "$SUBJECT_CA"  -days 365 -keyout ca.key -out ca.crt
}

function generate_server () {
   echo "$SUBJECT_SERVER"
   openssl req -nodes -sha256 -new -subj "$SUBJECT_SERVER" -keyout server.key -out server.csr
   openssl x509 -req -sha256 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365
}

function generate_client () {
   echo "$SUBJECT_CLIENT"
   openssl req -new -nodes -sha256 -subj "$SUBJECT_CLIENT" -out client.csr -keyout client.key
   openssl x509 -req -sha256 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365
}

function copy_keys_to_broker () {
   sudo cp ca.crt /etc/mosquitto/certs/
   sudo cp server.crt /etc/mosquitto/certs/
   sudo cp server.key /etc/mosquitto/certs/
}

generate_CA
generate_server
generate_client
copy_keys_to_broker

as you see OU changes for each file.
Remember to restart Mosquitto
sudo systemctl stop mosquitto.service
sudo systemctl start mosquitto.service

let me know how it goes
bye
Michele

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


text:
Arduino to Arduino Communication using HC05
I have been working on a project for work ( I'm a waiter :/ ) I was tasked to build a food wait time display that receives input from the kitchen and echoes the time via bluetooth to another display.
So that we are all on the same page I will describe what I have built and where I am stuck.
Before I do, I would like to state that I have:

been planning and prototyping this thing for over a month
googled/crawled all over the web looking for answers
read the entire manual on the HC05 module
Bound both of the bluetooth modules via AT commands One as Master the  other as Slave

Now with that out out the way here is what I have so far:

2x Arduino uno R3
2x 16x2 LCD Display
2x HC05 Bluetooth Modules (1 set as Master the other as Slave & bound using AT Commands)
2x 10K Potentiometers for adjusting the contrast
3x Momentary push Button switches on Master with pull-up resistors (timeUp, timeDown, sendButton)

Here is where I am stuck. UPDATE
I was able to get the master and slave to communicate. RX and TX on master were crossed... SMH! However now the issue is that the slave is writing both digits it receives on top of itself. First writing one digit then clearing it and then the second digit...
Enough with the prologue here is the a code:
Master
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //sets up LCD pins
int waitTime = 10; //if food comes quicker than there is no need for a display ;)
const int timeUp = 6;
const int timeDown = 7;
const int sendButton = 8;
int timeUpState = 0;
int timeDownState = 0;
int sendButtonState = 0;

void setup() {
  Serial.begin(115200);
  pinMode(timeUp, INPUT);
  pinMode(timeDown, INPUT);
  pinMode(sendButton, INPUT);
  lcd.begin(16, 2);
  lcd.print("  Sam Kullman's"); //Splash screen on start up
  lcd.setCursor(0,1);
  lcd.print("      Diner"); //Splash Screen
  delay(2000);        // Delay intended to allow the device to pair prior to use.
  lcd.clear();
  lcd.print("Essen Dauert:"); //German for "Food takes":
  lcd.setCursor(0,1);
  lcd.print("   Minuten"); // xx minutes
  }

void loop(){
  lcd.setCursor(0,1);
  timeUpState = digitalRead(timeUp);
  timeDownState = digitalRead(timeDown);
  sendButtonState = digitalRead(sendButton);
  if (timeUpState == LOW) {
  waitTime += 5;
  delay(500);  //debounce button
  lcd.print(waitTime);
  }

  if(waitTime > 90){ // Max limit for wait time
    waitTime = 10;   //default wait time
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.print("   Minuten");
   }

 if (timeDownState == LOW){
  waitTime -= 5;
  delay(500);
  lcd.print(waitTime);
  }

  if(waitTime < 10){ //Min value waiting time
    waitTime = 10;
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.print("   Minuten");
   }

  if(Serial.available()){  // **This is where I am stuck**
   if(sendButtonState == LOW){
   Serial.write(waitTime);
   delay(500);
  }
 }
}

Slave
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  Serial.begin(9600);
  Serial.flush();
  lcd.begin(16, 2);
  lcd.print("  Sam Kullman's");
  lcd.setCursor(0,1);
  lcd.print("      Diner");
  }

void loop(){

  if (Serial.available()) {
   int waitTime = Serial.read();
    delay(200);
    lcd.clear();
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.write(waitTime);
    lcd.print(" Minuten");
     }
  }

Thanks in advance,
Jonathan

You'll might need debouncing here...

@AnnonomusPenguin Is the delay(500); after the state change not enough or in the wrong place? After some web crawling on "debouncing" I'm pretty sure I have denounced the buttons, or are you suggesting I take a hardware approach to denounce the buttons? I don't have an oscilloscope so I can't see exactly how the buttons are behaving.

no need for a hardware approach not a scope. If someone is trying to add 20 minutes, they are going to push it very fast, not every half of a second. You're going to miss some of the presses. There are some software libraries that I would consider if that's too big of an issue. Yes, it helps with debouncing, but it isn't the most ideal situation.

What libraries are you referring too?

something like Bounce

any reason NOT to use the I2C bus for master/slave communication?

The problem was how I was reading the incoming serial data.
After changing int waitTime = Serial.read()
to int waitTime = Serial.parseInt()
the code works.
Thanks to everyone for all your help and tips!

lcd.write(waitTime);

This line prints a single byte, whose (ASCII) value is the number in waitTime. You probably should write:
lcd.print(waitTime);

instead, which prints the number in waitTime using one ore more digits as needed.
This doesn't 100% explain the "both digits end up in the same place" symptom, since I'd expect random junk to be printed instead. But I'm pretty certain this is a problem, perhaps there's more problems :-)

Thanks for the tip, however when I use lcd.write(waitTime) I get the DEC value and lcd.print(waitTime)gives me the ASCII i.e.. 49 for 1 etc.

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


text:
split serial.readString() output
I'm trying to read a string like this one:
2;12;42;43;34

over a serial connection and split this string afterwards by a ";".
So the output would be this array:
(2,12,42,34)

All the stuff runs on an arduino uno. So I made some code:
String read_input;
char read_input_char[20];
char *read_values;

void setup() {

  Serial.begin(9600);
  Serial.setTimeout(10);

}

void loop() {
  if(Serial.available()){
    read_input = Serial.readString();
    read_input.toCharArray(read_input_char, 20);

    read_values = strtok(read_input_char, ";");
    Serial.println(read_values[2]);
  }
}

However now instead of outputting the 3rd array element it outputs only an '1'. What's wrong?

strtok() doesn't do that.  And the characters available to Serial.readstring() may not have the full string in the buffer when loop() first calls it.

This is a C question, not an arduino question, but anyway:
From the man page:
DESCRIPTION
   The  strtok()  function  breaks a string into a sequence of zero or more nonempty tokens.  On the first call to strtok() the
   string to be parsed should be specified in str.  In each subsequent call that should parse the  same  string,  str  must  be
   NULL.

You are only calling strtok() once, so it only parses the first value. You need to keep calling it until there is nothing left to parse.

Your code as is checks for a non-empty Serial buffer (the Serial.available() bit), and then reads it all into a String. Be careful doing this, as if this happens to execute part-way through the data arriving, you will get a partial data String. This may be cut off part way through one of your integers.
Also, the String object is very memory-intensive. Maybe not an issue for you, but try to use char arrays, or read directly from the Serial buffer.
In your case, there is a great function that you could use; parseInt().
Details are at; https://www.arduino.cc/en/Serial/ParseInt
More or less, this reads successive chars from the serial buffer, and once digits are encountered, forms an int. This continues until a non-digit char, or a (configurable) timeout. Something like this might do the job for you;
int data[10]; // Or however long you need it to be!
int arrayPointer = 0;

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

void loop() {
  if (Serial.available()) {
    int incomingInt = Serial.parseInt();
    Serial.println(incomingInt);
    data[arrayPointer] = incomingInt;
    arrayPointer++;
  }
}

Hope this helps!


text:
Use an Arduino to "intercept" transparently serial communication to Grbl?
I need to have an Arduino "spying" on communications between the PC and another Arduino with GRBL. The goal is to intercept a couple of GCode commands and act on them instead of Grbl.
My first step is to attempt to be as transparent as possible, but so far, I am not getting from Grbl the clear answer I expect. For example, I get Grbl 1.1d [?2???B???u5 instead of Grbl 1.1d ['$' for help]
Here is my code so far.
#include <SoftwareSerial.h>

int PortOneTX = 10;
int PortOneRX = 11;

const String USB = "USB";
const String GRBL = "GRBL";

char endOfLine = '\n';

SoftwareSerial portOne(PortOneRX, PortOneTX);

String grblBytes = "";
String USBBytes = "";

void setup()
{
    Serial.begin(115200);
    while (!Serial)
    {
        ; // Do nothing, just wait till we are connected through USB
    }
    portOne.begin(115200);
    portOne.write("\r\n");
    delay(2);       ;
}

String stringtoWrite = "";

void loop()
{
    if (portOne.available() > 0)//while (portOne.available())
    {
        stringtoWrite = portOne.readStringUntil(endOfLine);
        for (int i = 0; i < stringtoWrite.length(); i++)
        {
            Serial.write(stringtoWrite[i]);
        }
        Serial.write(endOfLine);

    }
    if (Serial.available() > 0)//while (Serial.available())
    {
        stringtoWrite = Serial.readStringUntil(endOfLine);
        for (int i = 0; i < stringtoWrite.length(); i++)
        {
            portOne.write(stringtoWrite[i]);
        }
        portOne.write(endOfLine);

    }
}

I feel that I should be using events instead of if (serial.available) in the loop, but I am not sure how to go about it. I thought it would be easy!
Anyway, as I want Grbl-Panel to work totally transparently, I need this first step to be Ok before doing anything else.
Thanks for your help.

First, you shouldn't connect the TX. Having two arduino driving a single line could cause some serious problems, when one tries to drive it HIGH, and the other LOW. Secondly, there is no need to buffer the serial data coming in, till you read a newline. Just see if there is a byte available, and if so send the byte forward using Serial.write. This will also negate the need for String which is very inefficient.

Sorry, but how can I initialize SoftwareSerial without a TX pin?
In previous tests, I did as you say, just send every received byte, did not do any better.

You can specify a pin in software. Just don't connect a wire between pin 10 and the TX pin on the target board. As the the other part. I though there could have been a speed issue, but that's apparently not it.

A diagram of how you have it all connected would be useful. I think @Gerben is assuming you have the device connected to the existing serial lines (sniffing them), but I think you've got it connected like a man-in-the-middle... Right?

I guess I could make quickly a fritzing picture, bu I don't think it's needed:
I have one Arduino with GRBL on it, let's name it 'GRBL'
I have a 2nd Arduino, with the code shown on it. Named 'USB'
The USB Arduino is linked to the computer, and after flashing my code to it, I connect to it via a serial terminal. USB is also connected, via Pin 10 on grbl Pin 0 (TX on RX) and Pin 11 on grbl pin 1 (RX on TX). Both are also connected by a GRND wire. I have also connected USB +5 to GRBL VIN, but it seems it's not really required.

@BernardG I suspect nobody is going to bother to decode that block of text. It's clear to you because you have it all in front of you and you've designed it. It's not very clear to me. A diagram would really help.

@MarkSmith - I added a schema as you asked for. Hope it makes it clear.

SoftwareSerial at 115200 is optimistic.

@MikaelPatel - I was starting to think along this line. I will change the parameter in GRBL to 57600, and do the same in my code. Eventually go lower if needed. I'll report here my findings.

I just switched to 57600, as I said earlier, and without changing anything in code, it start to be much better. For example, Grbl welcome message is now correct, without garbage. There is still work to be done, but it seems I am on the right track now.

@BernardG, please forgive my ignorance, I am new to Arduino. In your first comment, you mentioned just forwarding each byte, not waiting until end of line. How would you intercept commands without buffering them? Perhaps you could "start" to buffer, until such a point in time that the input can't match any of the commands to intercept, then forward byte-by-byte until next new line? Otherwise it seems that you would need to buffer? But I agree that this would get in the way if throughput...

@AndrewP. You are right, doing so would not allow me to intercept commands. It was just for testing if I could have an Arduino "in-between" transparently. Ince sure of that, I would have wrote the code needed to buffer.
But I am not sure to continue in that direction, as it really looks like the normal speed of 195200 is way too high for SoftwareSerial.

@BernardG, Ah, cheers for that :) good luck with the build!

I finally solved my problem by buying an Arduino Due! It was a problem of speed, not of code. The Uno is just not powerfull enough to read an write to Software Serial at 115200 Bauds, or even 9600, which I tried.
The Due has absolutly no problem. I made a small code test to intercept "words" coming form "USB" To "GRBL", and it works just as expected, while GCODE is send (using Grbl-Panel on the PC) through the Due (USB) to the Uno (Grbl).
It's the very first time I solve what I thought to be a code problem by an hardware solution.
BTW, in case anyone wonder, yes, I am using a level shifter between the 2.

Hi, Bernard, thanks for sharing the code example and the answer to your original question. I just got Arduino Due and trying to use your example. However, I get "SoftwareSerial.h: No such file or directory". I wonder which software serial library you used that worked with Arduino Due?

authors: Марк Якимчук


text:
fatal error: ESP8266WiFi.h: No such file or directory
I used platformio IDE
I did "platformio lib install 1101"
(http://platformio.org/lib/show/1101/ESP8266wifi),
I installed this: http://platformio.org/lib/show/549/WebSockets (follow instructions)
I did similar things to other libraries.
When I click the platformio:build button, it still complains:

fatal error: ESP8266WiFi.h: No such file or directory fatal error:
ESP8266WiFiMulti.h: No such file or directory fatal error:
ESP8266Webserver.h: No such file or directory

While Bhushan Patil's answer should work, it would still make future projects tedious. Instead you can add the header files to the hardware library, and use them at will, with the #include <library> syntax every other library uses in C/C++.
The PlatformIO IDE has a config file you can modify that tells the IDE where to look for libraries. You could read this file, and determine where to put your header files, such that PlatformIO could find them, or add a location to look for header files in. See this page from the PlatformIO documentation:
http://docs.platformio.org/en/latest/projectconf.html
Beyond that, you could also use the absolute path for the header file (library) you are trying to use, by doing something like
#include "/home/user/path/to/user/library.h"

Have you overridden lib_dir in platformio.ini? If yes, please remove it.

Make sure ESP8266WiFi.h, ESP8266WiFiMulti.h, ESP8266Webserver.h files are located in the same directory where your *.uno file present.

I symbolic link them. It seems getting over compiled errors. Do you know how I can install arduino into platformio ide? Currently, I git clone: https://github.com/esp8266/Arduino and symbolic link in my project. Not a good idea.

Note the different capitalization: ESP8266wifi vs ESP8266WiFi. Confusing as it may be, these are actually two completely different libraries.
ekstrand/ESP8266wifi is a library that is to be used when you are controlling an ESP8266 running the AT firmware over a serial connection from another microcontroller board such as a more traditional Arduino. The code does not run on the ESP8266.
ESP8266WiFi is a library bundled with the ESP8266 core for Arduino. It is used for controlling the WiFi functionality of the ESP8266 when you are directly programming the ESP8266.
The WebSocket sketch you were attempting to compile was written for use with the latter library. The WebSockets library can not be used with the ekstrand/ESP8266wifi library or generally any configuration that uses the ESP8266 as a WiFi module running the AT firmware.


text:
Cheat Sheet for interruption
Just read a post about timers and there was a timers cheat sheet posted there. It has been very helpful and I wonder if there is one for interrupts as well?
The post with the nice timer cheatsheet was this one Arduino constant clock output

Wouldn't make much sense. Must peripherals can generate interrupts, and each has it's own semantics. An interrupt cheat sheet would have to cover the workings of most of the MCU peripherals: to much material for a “cheat sheet” format.

The "cheat sheet" is more commonly known as the datasheet.


text:
Adafruit Huzzah espcomm_open failed
I recently bought an adafruit huzzah as well as a serial to usb cable to connect it to my computer running windows 10. I was able to get the board set up in arduino following the directions found here. I copied and pasted this sketch:
void setup() {
  pinMode(0, OUTPUT);
}

void loop() {
  digitalWrite(0, HIGH);
  delay(500);
  digitalWrite(0, LOW);
  delay(500);
}

into the arduino 1.8.2 IDE, followed these instructions:

Hold down the GPIO0 button, the red LED will be lit
While holding down GPIO0, click the RESET button
Release RESET, then release GPIO0
When you release the RESET button, the red LED will be lit dimly, this means it's ready to bootload

and tried to upload only to get an error:
In versions 1.6.5 and 2.0.0 of the esp library I get these errors:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_open failed

In versions 2.1.0 - 2.3.0 of the esp library, I get these errors:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I've tried switching the tx and rx leads, I've tried versions 1.6.5-2.3.0 of the esp8266 library. I've also tried it on the other board that I ordered and got the same errors. Any ideas on what could be the problem?
EDIT: I've now tried it on a generic esp-01 board and am having the same issue

in Arduino IDE, open the serial monitor, click the reset button on the huzzah - do you see anything in the serial monitor - if nothing at all (no text or even garbage characters) then you either: a) have tx/rx connected incorrectly, or b) haven't selected the correct COM port, or c) have a defective huzzah (or you killed it)

aside: if you like the huzzah, checkout the wemos D1 mini (1/2 price) and the nodeMCU (1/3 price)

You may find this helpful: https://github.com/esp8266/Arduino/blob/master/doc/faq/a01-espcomm_sync-failed.md. If it solves your problem please come back and write an answer to your question to help others who have the same trouble.

@per1234 I followed the guide and noticed that in my verbose upload output, it's setting the board to nodemcu. Is that normal for a Huzzah?

I had to install the SiLabs CP2104 drivers and reboot.
Make sure you don't have 2 connection (Arduino IDEs, VS Code with PlatformIO, ...) open. Also, I kept pressing the reset button the first time.
https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/using-arduino-ide


text:
Serial is freezing arduino
I'm using a LinkIt ONE Arduino-like to send sensor data via MQTT.
It always worked very well, then out of the blue, it stopped printing anything using Serial.print();
But if I ommit the "Serial.begin(9600);" line, the code runs normally, sending sensor data via MQTT, even if I can't see debug output.
This shows the problem is on the Serial handling.
Since I can't show the entire code here, here's two test cases:
1.
void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
  while(!Serial); //Wait until Serial is ready before printing
}

void loop() {
  Serial1.println("This came from serial 1"); //does nothing
  Serial.println("This came from serial 0");  //works
  delay(1000);
}

It shows me the following output:

This came from serial 0
This came from serial 0
Thi

Looks like the module freezes before the third iteration.
But if I omit the lines that aren't printed, from Serial1:
2.
void setup(){
  Serial.begin(9600);
  while(!Serial);  //Wait until Serial is ready before printing
}

void loop() {
  Serial.println("This came from serial 0");  //works
  delay(1000);
}

No output is shown on Serial monitor.
What is the reason behind this? Since Serial1 prints nothing, why can't I remove it?
Observations:
I tested the code in two LinkIt ONE modules of the same model.
I tested it in Arduino SDK 1.6.8, 1.5.6r2 and 1.6.5.
Edit:
Just made another test using the code below. It blinked two times showing that
Serial.begin(9600); runs
while(!Serial); runs (it didn't freeze the module waiting for Serial to initialize)
But Serial.println(); freezes
void setup(){
  pinMode(13, OUTPUT);
  blink();
  Serial.begin(9600);
  blink();
  while(!Serial); //Wait until Serial is ready before printing
}

void loop() {
  Serial.println("This came from serial 0");  //works
  blink();
  delay(1000);
}

void blink(){
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);
}

If the test code you posted is truly failing, you either have some external problem, or you have an issue you need to take up with the vendor of this non-Arduino board.

@ChrisStratton I have another friend that has the same board and will make a test using the same code, this is extremely weird because I tested it in two different boards and 3 different versions of Arduino IDE. Anyway, I'll keep you posted.

@ChrisStratton I reinstalled arduino IDE from scratch on version 1.6.9 and installed the lastest firmware version available 1.1.21, from board manager, that solved the problem. Should I put this as an answer to my own question?

If the problem is solved, then by all means post an answer.

The problem was solved by:

making a clean install of Arduino IDE 1.6.9
uploading the LinkIt SDK on board manager from version 1.1.17 to 1.1.23.

Then the Serial function returned back to normal.

I have bit similar problem. I thing, this is arduino bug.
When start serial port, must be take out data from Rx. When read buffer overflow my arduino freeze. I can't run delay because when arduino wait, serial port can receive lot of data -> overflow -> freeze. Instead of delay I use own function wait(milis):
void wait(unsigned long wait_time){
  unsigned long start_time;
  start_time=millis();
  while ( millis() < (start_time+wait_time) ){
    if (serial.available() > 0) serial.read();
  }
}

Not true.  See http://arduino.stackexchange.com/questions/1726/how-does-the-arduino-handle-serial-buffer-overflow

This shows the problem is on the Serial handling.

The problem isn't actually in Serial, it's somewhere else.  Many things are able to make the Arduino hang in mid-write.  Show us the any code that you have written, plus links to the libraries you are using, and you'll have your answer in short order.
I will guess that you have a low-RAM condition, perhaps exacerbated by heap usage.  Do you use String?  I notice you're not using the F macro to save RAM.

You seem to be overlooking the fact that the code is not running on an Arduino.  It is running on an entirely different, marginally source compatible board with orders of magnitude more resources.  The F() macro exists in response to the ATmega's unusually pure Harvard architecture.

@ChrisStratton, Right, this board doesn't need F.  However, I will stand by the guess (low RAM) and the request for the whole program.  I hope you aren't suggesting that "more resources" keep him from using RAM poorly?  Or that his trivial excerpt contains the problem?  Seems like an XY question to me...

You really should look up how much ram the board has before you make such extremely unlikely guesses and then insist on "standing by" them - debugging is about facts and evidence not unfounded guesses.  Also keep in mind that we have code in the question that can allegedly cause the problem.

A made a test using the F macro, and it did not work. Then, I made another test using the following code:

Nevermind, I will edit the question.


text:
Handle reading timing in Python using pySerial
I'm not sure about how to properly handle timing readings from serial inside a Python script. I need to read a value every 5 seconds.
From Arduino I could do,
Serial.println(value);
delay(5000); // should I wait here?

Inside Python script I could do,
import serial
import time

arduino = serial.Serial('/dev/ttyACM1', 9600, timeout=5) # should I set timeout?

while True and arduino.isOpen():

    try:
        value = arduino.readline().strip()
        print value

        time.sleep(5) # should I wait here?

    except KeyboardInterrupt:
        print "\nClosing..."
        arduino.close()

EDIT: Apart from that, the first reading is always wrong, like if there was something in the reading buffer.
I've found out that to solve that I should add arduino.flushInput() just after opening the port.

Do you need to "read a value every 5 seconds" or "transmit a value from the Arduino to the host every 5 seconds"?

Arduino is writing values to the serial, and I'm reading the serial inside my python script.

Yes, we all get that. What we need to know is which one needs to be in control of the timing.

Sorry, thanks for replying. I'm not sure which, what is the proper way to do this simple stuff? I mean, my sketch just sends temperature values, it's the only thing it does. My python script would read those values and print them every 5 seconds.

Does it just keep sending them as quickly as possible, and the Python program is supposed to only display the ones that show up every 5 seconds?

Well, that should be an option. Another I think would be that Arduino sends every 5 seconds and Python is always listening, waiting for that value. Which one should be better?

The answer is that it depends on what you are actually trying to accomplish. If there is nothing else to be done on the Arduino then it is fine to have it sit and wait; on the other hand if there is nothing else for the python script to do then it is fine for it to sit and wait, but there is no reason for both of them wait.
Arduino delays
You don't need to deal with the timing delay in python if the Arduino is delaying. According to the documentation readline will wait until it has received a value or until the timeout is reached. That said, I would make the timeout slightly longer than the delay on the Arduino side of things.
Note that readline will block your program from doing anything else while it waits. As such, It is pretty useful to explore python threading when you are writing a program which collects data over a serial stream unless the program is only collecting data.
Python sleeps
If there is other stuff to be done on the Arduino (perhaps if you are doing some filtering of the temperature data using the Arduino so as to reduce noise) then it might make more sense for it to push data to the serial stream at the end of each loop, and for the python script to only read the data every 5 seconds. In this case you could have python sleep and use no delay (or a shorter delay) on the Arduino. You can achieve this behavior without resorting to using sleep by using a timer object to periodically call a function that opens the serial stream (possibly flush it), reads the data, processes it, and closes the serial stream.

Thanks! There was another factor in my Python script, and that was the while True statement. In this simple example, it doesn't matter what timeout value is because readline would be called again on the next loop. However, I guess I should notice that readline is blocking everything else in my script, if there was another thing to do.

I was considering the (remote) possibility of your Arduino and computer being perfectly synchronized, such that the readline times out after reading half of the line, and then immediately reads the second half of the line on the next iteration of the loop. This is an admittedly far-fetched possibility, but by making your timeout longer than 5 seconds you limit the likelihood of it.


text:
Using Intel Galileo Ethernet Port
Is it possible to use the galileo's ethernet port through arduino IDE? Or should I buy an arduino ethernet shield? Will I be able to use galileo as a server to which arduino board can send data to?

Welcome to Arduino SE! Do you mean sending traffic through the USB port to the computer to use the computer's internet connection?

Considering that the Galileo is basically a small embedded linux system, you could also evaluate the option of using it as such, meaning using your programming language of choice directly inside linux.

I suppose you mean the "Galileo integrated Ethernet port" (the on-board RJ45). Then the answer is "no, not directly". The whole code provided by Intel in Arduino 1.6 IDE applies to the W5100 based shield, not the integrated Ethernet interface (which is a bit stupid, imho...)
Technically, however, this is possible, but you will need to create a library in C/C++, which interfaces with the system lib (the Linux one). You can then access the wonderful world of BSD sockets (much more powerful than the sockets within the W5100).
Note however that the configuration of the integrated Ethernet board is not very easy with the Galileo, because the default Yocto image does not allow you to change default IP parameters (the Yocto image uses DHCP by default). So technically, you need then to deal with a startup script that changes the IP parameters at startup, but it's pretty heavy to do.

The Galileo board is Arduino compatible; meaning that you can run Arduino sketches on it, and use its I/O pins the same way you would with, say, Arduino Uno.
Therefor you can communicate between Galileo and Arduino the same way you would with two Arduino devices. This can be done using your favorite communication channel - Serial, I2C, OneWire, RF or even Infrared - it all depends what exactly are your needs, knowledge and timing requirements. Of course, doing it this way, would require you to have code running on both the Galileo and the Arduino, in charge of the inter-communication.
By doing so, you could utilize the Galileo as a 'server' as you say, that will receive commands from the Arduino, send them over the network and reply to the Arduino with the response.

Yup - the Galileo Ethernet port works the same way as any other Arduino. For some sketch examples have a look at

File > Examples > Ethernet

Wrong, the Ethernet library is for use with W5100 Ethernet controller, as used on the Arduino Ethernet shield, not the Galileo's onboard Ethernet.


text:
Feeble click in relay but it doesn't get activated when connected to Arduino circuit
I have an Arduino uno board and I have a soil moisture sensor

connected the digital output pin of the sensor to Arduino input pin
connected an output pin of Arduino to the INPUT pin of the relay board
programmed the Arduino such that if input is HIGH then the OUTPUT should be HIGH as well
connected 5 v pin of Arduino to vcc of the relay board
connected gnd pin of Arduino to gnd of the relay board

When my sensor outputs a HIGH DO (digital output), the relay only creates a feeble click sound and does not get activated. The Relay board LED does light up but the relay itself does not work (NC remains closed and NO remains open).
Do I need to supply an external VCC to the relay board? If yes then how should I set up the circuit?
A picture of the relay board is attached. You are right ... it is a 12 v relay. Do I need a 12 v external power source with IN1 coming from Arduino? Any help will be much appreciated.

What relay do you use? if this one http://www.hobbyist.co.nz/sites/default/files/pictures/dancing-lights/dancinglights_step2.png then yes you need to add power to the board. There are GND and VCC pins. Ground and +5V

Yes. The relay is the one that you have shown except that it is single channel. So instead of connecting the VCC of the board to the 5v from the ARDUINO, I should connect the VCC of the board to an external 5v source and similarly I should connect the GROUND of board to GROUND of the external source?

no. Realy shield Vcc > Arduino +5V. And IN1 to arduino digital pin. If this not works, provide the code. Also, one of the gold rule, 99% there is no connection where it should be, or there is a connection where it shouldnt :) Check the wiring. Check this http://www.hobbyist.co.nz/?q=interfacing-relay-modules-to-arduino

Sounds like you are using a 12v relay. Can you provide a link to where you bought it, or a part number?

40mA (max output current for arduino port) isn't a lot for a relay. Obviously we can't see what you're using to check that - but I would expect you to need a transistor for reliable operation.

Mark and Gerben ... Please see the picture of the relay board I am using. You were right ... it is a 12 V relay ... should i simply use IN1 from arduino and VCC and GND from an external power source? Or do I need to somehow connect the external power source with Arduino?

You need to join the ground of the external supply to the ground being supplied from the Arduino.  The 12V supply must be capable of at least 100ma
There appears to be a transistor and resistor on the board.  This is probably to drive the relay coil from the Arduino.  However, I would need to look at the circuit diagram of the board to be certain.  Can you supply images of the copper side and component side of the board to see what the connections are.
Ideally the circuit diagram from the manufacturer would be even better.


text:
RFID RF522 kit for access control
I am trying the RFID RC522 reader kit with an Arduino UNO to built a controlled access system for a door.
Using the code below, I am able to read the UID of my card and light up an LED when the reader detects the card or the badge, however it will light up whatever card is presented to it even if the UID of this card is not entered as a String in my program.
My question is how can I enter hundreds of cards (depending on memory) that will unlock the door and have all the others set as unknown if not in my program.
Thank you very much for your help
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         //(or SDA) Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
// ===========================================================================
String read_rfid;
String ok_rfid_1 = "C5 12 E3 52"; // for the badge
String ok_rfid_2 = "9A 48 3A D5"; // for the card
// ==========================================================================
int led = 3;
// ===========================================================================
void setup() {
 Serial.begin(9600); // Initialize serial communications with the PC
 //while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
 SPI.begin(); // Init SPI bus
 mfrc522.PCD_Init(); // Init MFRC522
 mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
 Serial.println(F("Scan PICC to see UID, SAK, type, and data bleds..."));
  pinMode(led, OUTPUT);
}
// ===========================================================================
 void dump_byte_array(byte *buffer, byte bufferSize) {
  read_rfid="";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
 }
// ==========================================================================
void unlock() {
  digitalWrite(led, HIGH);
  delay(2000);
  digitalWrite(led, LOW);
}
// ======================================================================
void loop() {
 // Look for new cards
 if (! mfrc522.PICC_IsNewCardPresent())
 return;
 // Select one of the cards
 if (! mfrc522.PICC_ReadCardSerial())
 return;

  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println(read_rfid);

  if (read_rfid == ok_rfid_1 || ok_rfid_2) {
    Serial.println("Open");
    unlock(); // turns LED on
  }

  else {
    Serial.println("Stay Closed");
  }
}

Your IF statement is the problem. if (read_rfid == ok_rfid_1 || ok_rfid_2) always evaluates to True. Your condition should be:
if (read_rfid == ok_rfid_1 || read_rfid == ok_rfid_2)

You also need to remove the spaces in the string literals if you want this condition to have the desired effect.
This approach isn't very good though, since you have to add more comparisons to the IF condition if you want to match more cards. You should use the byte arrays as they are, without converting to Strings; it can actually be a lot simpler to compare as well as memory-safe. Store all your allowed card UIDs in a 2-D array:
#define ALLOWED 2   // no of allowed cards
byte read_card[4];   // same purpose as before
bool found = false;  // to know when a valid card match occurs
byte cards[ALLOWED][4] = {{0xC5, 0x12, 0xE3, 0x52},
                         {0x9A, 0x48, 0x3A, 0xD5}};

Then you should get rid of dump_byte_array() and compare cards like this:
memcpy(read_card, mfrc522.uid.uidByte, 4); // copy UID into array with shorter name ;)

for (int i = 0; i < ALLOWED; i++){
  if (memcmp(read_card, cards[i], 4) == 0){

      found = true;
      break;
  }
}

if (found){
  Serial.println("Open");
  unlock(); // turns LED on
  found = false;
}
else {
  Serial.println("Stay Closed");
}

Thanks TisteAndii, I will give it a go, byte arrays is defenitely what I should use. cheers.


text:
Adafruit GPS module with SoftwareSerial affecting servo signals
I'm having a bit of an odd problem here. I'm programming a self-built quadcopter using an Arduino Uno for control. One of the sensor's that I'm using is Adafruit's GPS breakout. The motors are controlled with electronic speed controllers (ESCs) that controlled identically to normal servo motors. Everything is connected together with a custom Arduino shield. The GPS is using SoftwareSerial on pins 3 and 4, and the ESCs are connected on pins 5-8. Most of the GPS code is directly copied from Adafruit's documentation.
What I've found is that even when the throttle is held steady (at any power level), the motors experience quick bursts of power far beyond normal whenever there is communication between the GPS module and the Arduino. For example, the GPS updates on 1Hz intervals and so the motors get a burst of speed about every second. Has anyone else experienced something like this or could someone at least point me in the right direction?
Here's an abbreviated version of the code that I'm currently using:
#include <Servo.h>
#include <Wire.h>
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

Servo ESC1;
Servo ESC2;
Servo ESC3;
Servo ESC4;
const int maxThrottle = 2000;
const int minThrottle = 1000;

SoftwareSerial softwareSerial(4, 3);
Adafruit_GPS GPS(&softwareSerial);
// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences.
#define GPSECHO false
bool usingInterrupt = false;
uint32_t timer = millis();

void setup() {
    ESC1.attach(5);
    ESC2.attach(8);
    ESC3.attach(6);
    ESC4.attach(7);
    setThrottleAll(minThrottle);

    GPS.begin(9600);
    GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
    GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
    GPS.sendCommand(PGCMD_ANTENNA);
    useInterrupt(true);
}
int throttleCommand = 20;
void loop() {
    // Map throttle command percentage to raw throttle values that are sent to the ESCs
    int throttle = map(throttleCommand, 0, 100, minThrottle, maxThrottle);
    setThrottle(1, throttle);
    setThrottle(2, throttle);
    setThrottle(3, throttle);
    setThrottle(4, throttle);
}

// GPS interrupt
SIGNAL(TIMER0_COMPA_vect) {
    char c = GPS.read();
    // if you want to debug, this is a good time to do it!
    #ifdef UDR0
        if (GPSECHO)
            if (c) UDR0 = c;
                // writing direct to UDR0 is much much faster than Serial.print
                // but only one character can be written at a time.
    #endif
}
void useInterrupt(boolean v) {
    if (v) {
        // Timer0 is already used for millis() - we'll just interrupt somewhere
        // in the middle and call the "Compare A" function above
        OCR0A = 0xAF;
        TIMSK0 |= _BV(OCIE0A);
        usingInterrupt = true;
    }
    else {
        // do not call the interrupt function COMPA anymore
        TIMSK0 &= ~_BV(OCIE0A);
        usingInterrupt = false;
    }
}

void setThrottleAll(int throttle) {
    setThrottle(1, throttle);
    setThrottle(2, throttle);
    setThrottle(3, throttle);
    setThrottle(4, throttle);
}
void setThrottle(int index, int throttle) {
    if (index == 1)
        ESC1.writeMicroseconds(throttle);
    if (index == 2)
        ESC2.writeMicroseconds(throttle);
    if (index == 3)
        ESC3.writeMicroseconds(throttle);
    if (index == 4)
        ESC4.writeMicroseconds(throttle);
}

SoftwareSerial combined with a real time flight controller sounds like a bad idea.  You may also have areas in the message code that can block.  This project requires careful engineering from one end to the other.

@ChrisStratton Is there a different way of communicating with the GPS module that doesn't block? Would the hardware serial pins 0 and 1 be a better choice?

Servo.h uses a timer and will experience glitches if interrupts are disabled frequently/for a long time.

Realistically, an Arduino is not an appropriate platform for a flight controller - pretty much all projects have long abandoned them, and even if you are going to use an ATmega you really need to use only code specifically written for this purpose rather than typical Arduino libraries.  For example, you want to make sure that you are using hardware PWM channels for all outputs and you want to make sure that your control loop cannot under any combination of circumstances get stuck anywhere.  Speaking of loops, a lot more is needed than throttling the motors.

Ah, I understand. The reason I thought it was possible was because of other projects like AeroQuad and BlueCopter. Some people have even gotten quads to fly with a Raspberry Pi as the flight controller (and a totally non-realtime stock Raspbian OS). On the last point, my actual code is much more complex. I just kept the relevant parts because I've narrowed down the issue to the GPS module. The rest is much more than just throttling motors!

Quickly looking at AeroQuad it seems they may not support GPS on anything less than a Mega, moved heavily into 32 bit ARM alternatives to the AVR platform, shipped their own libraries for the key functionality... and don't appear to have touched the code in 3 years.  Which mostly reinforces the sense that while flying something with an ATmega328p is possible, few would bother today, or when using stock libraries that hide many of the critical details to which attention is required.

The bad news is that you are using the absolute worst libraries (SoftwareSerial and Adafruit_GPS), and your program structure is based on the awful Adafruit_GPS example.
The good news is that there are much better alternatives: NeoSWSerial and NeoGPS.  Still, there's no doubt that you are near the limits of this processor, especially with Wire and timer-based Servos.  It can be an "interesting challenge" or a "beginner's nightmare."
Suggestions:
1) Consider using the HardwareSerial object, Serial, for the GPS interface.  Your excerpt does not show what Serial is currently used for, but if it's debug print statements... don't.  Instead, use a software serial port for debug statements (use a serial-to-USB adapter on those pins to connect it to your PC).  This would have a tremendous impact.
2) If you really really can't use Serial for the GPS (are you sure???), consider using an AltSoftSerial instance on pins 8 & 9, as this is much better than the dreaded SoftwareSerial.  Next best is NeoSWSerial on any pins, including 4&3 that you are using now.  There is absolutely no reason to shoot yourself in the foot with SoftwareSerial.
3) As other's have commented, use HW PWM... let the machine do the work for you.
4) Consider using the faster and smaller NeoGPS library.  And restructure your program to look like the NeoGPS example programs, because their sequencing is much more efficient.  The Adafruit_GPS example uses a timer interrupt... to read a character from the input buffer... that was stored by a SoftwareSerial interrupt... that was on for the entire character time of ~1ms.  What a phenomenal waste!
5) Use interrupt-driven GPS parsing.  All three Neo__Serial libraries (HW, IC and SW) allow NeoGPS to handle the GPS characters during the rx interrupt, avoiding character loss because the port was not read in time (input buffer overflow).  And because just a little work is performed on each character, there is no big chunk of processing when a sentence is complete.  This also uses half the interrupts and saves copying the characters multiple times, in and out of the serial input buffer... into the Adafruit double-buffered sentences, where it gets searched multiple times with strcmp and strchr.  Ugh.  No, I meant to say UGH!
6) NeoGPS will also free up hundreds of bytes of RAM, which you may be able to trade for some more speed, elsewhere.
It's definitely a tight squeeze.  Either reallocate your pins and use better libraries, or get a bigger hammer.      :-)

Wow, thank you so much for that thorough answer! I had no idea that there were alternatives to the stock Adafruit libraries for their hardware. I'll definitely take a look at it.


text:
Convert uint8_t array to ascii character for serial transmission
I am trying to send packets of via bluetooth data that include 6 bytes read from a sensor and stored in a uint8_t array. Instead of sending over the data as numerical digital, I would like to send the ASCII character of each of the bytes. I am doing this to reduce the size of my data packets and make it easier to interpret the incoming data.
uint8_t* temp = readBufferData(FIFO);

for (int i = 0; i < 6; i++)
{
    Serial.write(temp[i]);

}

Read buffer data returns a pointer to a uint8_t array read from a FIFO buffer.
When I use Serial.print, I get the following output, which makes sense.
22163226094255
One question is, when I use Serial.print on a single character, is it transmitted a single byte, or is it actually sending the decimal digital of the number, anywhere from 1-3 bytes?
When I use the Serial.write, however, I get something like the following
DÿÂ?ÁÏ?ÌÆ?Ûµ?Ë½?ÔÀ?Ð¿?ÃÕÓÑËÐTÿÀ?Ï3ÿÉ?¹4ÿÐ?Ê<ÿ½?µfÿ¼?ìNÿÐ?×Â?ÊÚ?×¿?Å
Also, these data display much more slowly on the screen, than normal.
How can I send each uint8_t value by sending over the corresponding ASCII character for serial transmission?
Thanks!

try with this in the loop: Serial.print("Hex: 0x"); Serial.print(temp[i],HEX); Serial.print(" - Char: "); Serial.write(temp[i]); Serial.println(""); and then post some of the lines you get

You could look at base64 encoding the data if you want to go hardcore, there are libraries out there.  If you just want something you can read then the best solution is to convert each uint8_t to two hex numbers and send them, it will double the amount of data you transmit but I don't know if that's important to you.

Why do you want to send your data as ASCII? Binary writes are much faster and of a vastly smaller size.

Possible duplicate of What is the difference between Serial.write and Serial.print? And when are they used?

You don't "convert" anything. A character is just a human representation of an 8-bit value.
Instead you just need to change what the compiler thinks the data represents (from a human perspective).  The simplest way of doing that is to either cast the uint8_t values to be char values, or to write each one individually as a raw value.
The latter way:
myBluetoothSerial.write(myData[0]);
myBluetoothSerial.write(myData[1]);
myBluetoothSerial.write(myData[2]);
myBluetoothSerial.write(myData[3]);
myBluetoothSerial.write(myData[4]);
myBluetoothSerial.write(myData[5]);

Or, with a loop:
for (int i = 0; i < 6; i++) {
    myBluetoothSerial.write(myData[i]);
}

or using a built-in variant of write that does the loop for you:
myBluetoothSerial.write(myData, 6);

Thanks for the comment. I just tried this and got the following characters out on my serial monitor. These characters should represent 6 bytes worth of data. ÆúÂÊàDÿÜ?²Nÿª?È{ÿ¹?×CÿŒ?ä`ÿà?Ïkÿð?ÿ

Are you sending the 6 bytes repeatedly over and over again?

Yes, but in between each transmission I have some other text printing to the serial monitor. E.G. a Count for ISR operations and Number of samples Below is a larger sample of the output
@¾@ÀÂ?Ç¯?¹ßßÂÄÑQÿ¿?Ë5ÿ¸?ÒGÿÐ?ÆYÿÉ?±CÿÊ?»#ÿÐ?ÔÊ?ßÑ?Øã?ÙÖ?ÜÜ?¸Û?OÿÍ?ISR Count: 84
Number of Samples: 1
ÙÎÜÍÂMÿê?¾GÿÔ?Òvÿ¤?ÍPÿÔ?æAÿÜ?áMÿÌ?:ÿISR Count: 117
Number of Samples: 1
Û?Ñ¯?ÄÄ?¹×?ÆÔ?ÑÁÄÍÇÁ¾aÿ·?ÝMÿÁ?ÔAÿË?àRÿÌ?ã0ÿÆ?ËÁ?ÃÄ?ÒÄ?ÇÄ?¸Å?ÅÅ?ÂÀÔÕÁÐAÿÂ?ÊGÿÐ?ÇEÿÛ?Ì8ÿÄ?Ç?ÿÌ?ÈUÿÕ?ÁÉ?ÐÄ?ÒÔ?ºÇ?ËÓ?ÝÌ?MÿË?ISR Count: 234
Number of Samples: 1
ÎÓæë†úþì? Cÿú?³<ÿÓ?¥'ÿÑ?Ø:ÿÚ?Ö,ÿÓ?EÿISR Count: 267
Number of Samples: 1

It is most likely correct. You won't be able to understand the data since it's no longer as numbers but ASCII characters. Without seeing your code I can't know what to expect from the output.

I added some code and details to my question above. The readBufferData function works as expected by returning a pointer to a uint8_t array. It's just the Serial output that is behaving strange. I used the software Serial output for testing purposes, but I wouldn't think that matters.

As I said, you won't be able to understand the output. It may be that the serial terminal is trying to interpret the seemlingly random data as UTF-8 and giving you all sorts of gibberish. Instead you are going to need to write the corresponding receiving software to interpret it and see if it is correct or not.

Let us continue this discussion in chat.

Try changing Baud Rate. Most of the time garbage like this happens because of difference in baud rates of transmitter serial device and receiver serial device.

Both are set to 9600, I only get this when I use Serial.write instead of Serial.print.

oh, these two are different. Have a look at this question to understand HOW.


text:
How fast is a SD page read from a file?
For a project I would like to do, I asked a question about whether to use SD or EEPROM (see Question
I checked how much memory I would need without any restrictions which is like 2 MB (or more) so a SD card seems the best solution.
However, I'm a bit worried about the speed. In one of the answer comments is mentioned that 20 ms is an eternity for a microcontroller. However, I might need to do the following within 20 ms:

Parse a MIDI event (CPU power only, does not take long)
Read one or two SD pages (1/2 times block of 512 bytes)
Change/add/remove the MIDI event (CPU power only, negligible)
Send out MIDI data (barely no time, mostly hardware)

In worst case I can get like 10-20 MIDI events I need to handle within 20 ms. Especially for step 2 I don't know how much time it will.
My plan is to create a big file with a PC program to be stored on the SD card. Than I can let the Arduino read pages of 512 bytes from predefined places (with seek in a file).
I'm intending to keep the file open at all times and use seeks to go to the right place and read 512 bytes every time (assuming it doesn't matter to read 1 or 512 bytes since the page size is 512 bytes anyway).
So my question: is 20 ms enough to read like 50 pages of 512 bytes from an SD card which are located on different (but known) file offsets within a 2+ MB file?
(btw, I want to try first on an Uno, but probably I will later go to a Mega (or add more SRAM to store temporary data).

So my question: is 20 ms enough to read like 50 pages of 512 bytes from an SD card which are located on different (but known) file offsets within a 2+ MB file?

Let us do the numbers: 50 * 512 = 25 Kbyte in 20 ms is 1.25 Mbyte/s. As the max speed for SPI is 1 Mbyte/s (on Arduino AVR, 16 MHz) we do not have to go any further. The answer is: No.
Cheers!

Thanks for this answer, although the answer is no, still 40 pages per second is feasible which still is ok (but not optimal). Just hope it doesn't matter to read non-contiguous blocks for the max spee of 1 MB/s and the seeks don't take too much time.

No, there is much more going on when accessing an SD. You should count on 200-300 Kbyte/s max substained. The SD SPI protocol requires both synchronization and addressing so the effective bandwidth is lower. High speed SD uses multiple data pins (and additional hardware support).

that would mean a page read of 512 bytes would take 2.5 ms? And 512 bytes is the minimum amount to read I read somewhere.

@MikaelPatel: would it be possible to use 2 sdcards and 2 SPI buses to (almost) double the throughput?

Just for reference for others:
I received my micro card reader (from Catalex, v1.0, 11/01/2013) today and used a 1GB micrSD card.
The times measured ar at 4 addresses (2000, 120000, 40000 and 12000) again and are a seek to the address, and the reading of the bytes mentioned before the colon and the time after the colon in micros.
Result: Seek is 25..2500 micros depending on the file position, reading below 256 bytes is approx. 2-3 ms, reading 256 bytes 4-6 and 512 bytes 7-8  ms.
Initializing SD card...card initialized.
---------
Address: 2000
seek    : 24
read   1: 2276
read   2: 2308
read   4: 2344
read  10: 2380
read 256: 4780
read 512: 7328
-----------
Address: 120000
seek    : 2536
read   1: 5008
read   2: 5040
read   4: 5084
read  10: 5120
read 256: 5312
read 512: 7888
---------
Address: 40000
seek    : 2468
read   1: 4940
read   2: 4972
read   4: 5016
read  10: 5052
read 256: 5252
read 512: 7828
---------
Address: 120000
seek    : 2504
read   1: 4992
read   2: 5024
read   4: 5060
read  10: 5104
read 256: 5296
read 512: 7864


text:
Communicating Via Serial1 on Arduino Mega
Apologies if this a relatively simple question, but I am rather new to Arduino's and cannot seem to find any concise information on the topic.
This is my XBee, mounted on a shield and placed onto a MEGA 2560. I want to leave Serial for USB debugging and use the Serial1 for XBee communication.

Just to confirm, the two XBee's do communicate if I use SoftwareSerial.   This is the code that works using SoftwareSerial:
#include <SoftwareSerial.h>

// XBee's DOUT (TX) is connected to pin 10 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 11 (Arduino's Software TX)
SoftwareSerial serial1(10, 11); // RX, TX
boolean nextLine = false;
void setup()
{
  Serial.begin(9600);
  serial1.begin(9600);
}

void loop()
{
   while(serial1.available()){ // there is data being sent from the xBee
    char read = char(serial1.read());
    if(read == 'A'){
      //Where ~ is the EOT character
      serial1.write("55.134~");
    }
  }
}

How do I communicate using Serial1?

If you take a look at the headers on the Mega, you'll notice that one of them has labels of "RX1" and "TX1" through "RX3" and "TX3". You'll also notice that the XBee shield does not connect to that header, therefore you cannot use Serial1 through Serial3 with the shield. Either switch to a breakout board that you can connect manually or stick to software serial.

Or pop off the jumpers on the shield and use a couple of jumper wires to connect the right pins of that header to the RX1 and TX1 pins on the Mega.

Thanks, I think I will do as Majenko has suggested and connect it through to Serial1 with some wires.

There is a good example on the Arduino site, but in short, you'd use the Serial1 (or -2 or -3) object the same way you use the Serial object:
Serial1.begin(9600);
if( Serial1.available() ){ ... }

etc.


text:
Decoding IR codes with IR sensor rather than IR receiver module
I'm looking for a library to decode RAW IR signals from an IR sensor (looks like a black LED, two legged) rather than an IR module (3 legged, rated for a particular frequency - such as 38kHz).
Is there a library that supports IR sensors?
A picture of the two possibilities can be seen here
EDIT: This isn't a duplicate of my previous post, it is related to the same project however.
On my previous question I asked what could be the cause. I've found out what it is - frequency. My previous IR detector was an IR module and not an IR sensor. The difference could be seen here

What difference does the sensor make? That is just a hardware issue. The incoming pulses will still be the same.

@NickGammon The difference is how the pulses are presented - a receiver amplifies and filters the signal, so you get a sequence of simple on-off pulses.  With a detector you get whatever IR light is coming in. It's then up to you to filter out the light that is pulsing on and off at the carrier frequency to determine when the on is and when the off is.  That could be done in software, or it could be done in hardware. Best to do it in hardware and use a matched receiver for your transmitter.

@Majenko exactly. I didn't elaborate on the problem I want to solve: I have an IR module which decodes my remote as NEC. Retransmitting it with the same library doesn't work.
Debugging a bit more shows that the remote sends pulse modulation at 830Hz. Could a 38kHz module decode this?

That's a whole different question. Better post a new question instead of adding this in the comments.

@Gerben seems too technical to be over here. Posted on electronics

Possible duplicate of A/C doesn't detect IR codes sent from Arduino

This seems related to your question about A/C doesn't detect IR codes sent from Arduino. Although in that post you seemed confident you had detected the codes. Now you are not? Please explain why you are opening another question about your air conditioner and the IR remote, without referencing your earlier question. This helps see the project in context.

This question also seems very similar to control air conditioner using arduino - in itself double-posted.

@NickGammon in the previous question I was looking for what's causing it not to work, now that I've found out (it's the frequency). The reason I found out is by using an IR sensor rather than an IR module. What I'm looking for now is an IR library that works with IR sensor and not IR module, to make sure the codes were decoded properly. See my other question in electronics.

@NickGammon also, I just answered my previous question

No, you posted a mistaken analysis of your other question.  You need to stop posting new questions and concentrate on understanding the actual problem.  This question is based on fundamentally mistaken ideas and should be deleted.

Several cars and universal remote controls have this feature of autolearning sender codes by pairng keys in the learn mode. Why not do the same?

IRremote (already recommended) - but to save you some time, use the IRRecvDump example to grab the raw codes you need for sendRaw(). They need to be averaged out across 10-20 reads. I log the output to a file, and use a perl script to do it for me, since it is painful to type this into a calculator a million times. The resistor you connect to the sensor affects its sensitivity - I used 330ohm, and have ~10 metres range from a 3V3 remote inside, 4-5 metres outside in sunlight. I would give you the script, but it's on my desktop. Let me know if you need it - or just use python, which is so popular nowadays (indent-or-fail... feh. what about people who don't like setting up the tab-space continuum, and don't have fancy editors...mumblemumble)
Edit: my raw codes absolutely needed to be averaged out, or they were useless. Any negative values in the array can just be made positive, don't fret.

I had a similar project a few months back and spotted this Arduino Library:
https://github.com/z3t0/Arduino-IRremote
and it is invaluable.
For your instance, you want the RAW Data which you can achieve using an Example included in the Library named: IRrecvDemo.
The wiring is easy and straight forward

An IR detector/demodulator must be connected to the input RECV_PIN.

Which is 11 by default but you can definitely change it :3
and the other two Legs of the IR detector/demodulator go to the power source.

OP said he doesn't have the 3 legged module but just a raw sensor (2 legs).

I'm looking for a library to decode RAW IR signals from an IR sensor

AGirs includes a comprehensive library designed to work with raw IR signals. I've used GirsLite in an Arduino and IrScrutinzer in Windows to do advance IR protocol snooping.

authors: Рауль Алимбеков