text:
Arduino Micro serial communication is not working after wake from power down
I'm trying to use the power down state for a battery application, but I'm having issues with the serial communication.
I'm using the lowpower.h library to put the Arduino Micro into power down mode.
When it wakes I flash an LED, which is working, so I know it's is waking up. And I also re-establish serial communication and send a message. This is not working. I receive nothing on the serial monitor, however the TX LED does flash.
I think the Arduino may be working correctly, but for some reason the serial monitor can't handle it. Perhaps there is a better serial monitor application?
#include "LowPower.h"

void setup()
{
    //20sec delay added to make uploading easier (cant upload in power down state)
    Serial.begin(115200);
    Serial.println("20");
    delay(5000);
    Serial.println("15");
    delay(5000);
    Serial.println("10");
    delay(5000);
    Serial.println("5");
    delay(5000);
    Serial.println("START");
    pinMode(LED_BUILTIN, OUTPUT);
    delay(1000);
    Serial.end();
}

void loop()
{
    // Enter power down state for 8 s with ADC and BOD module disabled
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

    Serial.begin(115200);
    delay(100);
    Serial.println("BLINK");
    digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(5000);                       // wait for a second
    Serial.println("BLINK_stop");
    digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
    delay(5000);                       // wait for a second

    Serial.end();

}

Serial monitor output:
20
15
10
5
START

and then nothing...

There may not be a lot of point to the operation behind this question: if the device is connected via USB, what do you gain by putting it into a low power mode?   Theoretically, with a lot of care to fully implement all specifications you could have the host computer and the device both enter low power mode, but it isn't really apparent that you are doing that here.  Perhaps it only makes sense for your device to enter a lower power mode when not connected via USB.  If you need brief debug messages between intermittent sleep, consider an external USB UART that remains powered.

I found the answer on this related question: Starting usb on pro micro after deep sleep (ATmega32u4)
Which itself was a link to a sparkfun forum
Note: it requires you to close and open the serial monitor at proper timings.
// disable the USB prior going to sleep
USBCON |= _BV(FRZCLK);  //freeze USB clock
PLLCSR &= ~_BV(PLLE);   // turn off USB PLL
USBCON &= ~_BV(USBE);   // disable USB

// and wake it up after
//routine to properly wake up
sleep_disable();
delay(100);
USBDevice.attach(); // keep this
delay(100);
Serial.begin(9600);
delay(100);

Can you accept your own answer please, so that the system here recognizes that the question has a valid answer?


text:
OLED on Hardware SPI, on DUE
I want to use an OLED with DUE.
I plan to connect it via hardware SPI.
The Due has a 3X2 pin connector labeled SPI. Is it here where i connect the SCK and MOSI?
If indeed, i connect it here, then which one is SCK and which one is MOSI?
Most importantly, i saw somewhere that in the DUE, hardware digital pin 13 is SCK and pin 11 is MOSI?
Is this true? Because if it is, i can simply hook it up to these pins and get rid of the confusing 3X2 pin connector.

It doesn't look like it's true. There is only one SPI module and it has fixed pins which are not duplicated anywhere.
However there are three instances of USART which can be used in synchronous mode as SPI:

USART0: RXD0(PA10) / TXD0(PA11) / SCK0(PA17)
USART1: RXD1(PA12) / TXD1(PA13) / SCK1(PA16)
USART2: RXD2(PB21) / TXD2(PB20) / SCK2(PB24)

Whole table from SAM3X datasheet:

But I'm not sure if the Arduino IDE supports this mode, or you'll have to do it from scratch by yourself.
You can even use RTS as select slave signal:

source: Stack Exchange

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

sort: votes


text:
BMP 280 exact Altimeter readings
I was just going through this pressure sensor tutorial.
What I want to know is how can I set the exact altimeter in my readings depending upon my different geographical place ? or may be if I am attaching the sensor to my balloon.

If you can know an exact height at the start of the sketch (or maybe just assume 0m for start), you could save the starting pressure in setup(), then use that pressure (converted from Pa to hPa) to calibrate the loop() altitudes.

The tutorial sample source code has the line:
Serial.print(bmp.readAltitude(1013.25)); // this should be adjusted to your local forcase

That 1013.25 value should be the local pressure at sea level in hundreds of Pa. If want to show altitude above ground level, you will need to know that for your location and write your code to calculate the altitude offset.
The sensor can't know location -- it only measures pressure. The AdaFruit library provides the altitude conversion, but being generic, it relies on several assumptions.

The baromic pressure is at sea level. Every wheather station compensates the measured value. First of all, you have to know the height of the sensor. Start with a height map: http://www.ahn.nl/index.html and add something for how high the sensor is in your house. The Adafruit library https://github.com/adafruit/Adafruit_BMP280_Library/ does not have a function to correct the height. This is too complex: https://en.wikipedia.org/wiki/Barometric_formula This is simple: http://www.engineeringtoolbox.com/barometers-elevation-compensation-d_1812.html It is +7hPa for 61 meters.

What units is the output given as?

@DavidGlass Again, the Adafruit library example source code has a following line that indicates the unit is Meters.

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


text:
How can I wire a 12V LED switch so that it is powered, but my Arduino only receives a 5V signal?
My arduino is powered by 12V.  I am getting some cool looking 12V led switches from amazon, but they need 12 volts to light up. My arduino will perform an override function when it detects the switch is closed. the digital pins can only handle 5V. How can I step down the 12V signal that powers the switch to the 5V that the pin can handle.
12V supply -> 12V led switch -> reduce 12V to 5V -> arduino digital pin

What is a "12V led switch"?

Could you provide a link to the switch in question, please? Depending on how it's made, you may not need to do anything.

you can power the switch's LED with only 5v, it will be dimmer but should work.

You need a voltage divider:
The formula is:
V1 = 12V
R2 = 5V max
R1 = The rest (V1-R2)
And then you have to calculate max current. If you use 1/4watt resistors, you have to convert watt to current, P = U x I.
Pmax = 0,25W
R1volt = 7 volt
Imax for R1 = P/U = 0.25/7
Imax for R2= P/U = 0.25/5
Now you have the current and voltage for R1 and R2
And the relation between R1 and R2 is:
R1 = 7/12 x Rtotal
R2 = 5/12 x Rtotal
Rtotal = R1 + R2

simulate this circuit – Schematic created using CircuitLab


text:
Power Measurement
I am trying to develop a system that reads the amount of power consumption from my load. Here is how my setup looks like;

The led represents a 5W and 12V light bulb(I was unable to get this in my simulator) and the battery i am using is 9 volts
Here is my code;
 sens = analogRead(A0);
 vol = sens * (2.0) * ( 5.0 / 1024.0);
 tot_vol = 5 - vol;
 current = vol / 10;
 power = current * tot_vol;
 Serial.print(power);
 Serial.print ("\n");
 delay(1000);
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
state = Serial.read(); // Reads the data from the serial port
}
if (state == '0') {
 digitalWrite(ledPin, LOW); // Turn LED OFF
 state = 0;
}
else if (state == '1') {
 digitalWrite(ledPin, HIGH);
 state = 0;
 }
}

I am trying to calculate the voltage drop across my resistor and then get the current and then power from that. This data is sent to an android app via the bluetooth module. However, here is the output i am getting;

What am i doing wrong?

Question: why are you powering a 12V bulb with a 9V battery?

A number of things wrong:

You have no ground connection to the Arduino. It can't work out what the voltage you are measuring is relative to.  (Read this)
You should have the shunt resistor as the absolute last item in your chain of components so it is connected directly to ground (V+ -> LED -> LED's Resistor -> Relay -> Shunt Resistor -> GND
Your shunt resistor should be as low as you can get away with - low enough that it doesn't affect the circuit, yet high enough that you can measure a voltage drop. For that you need to first have a good idea about what level of current you will be measuring.

simulate this circuit – Schematic created using CircuitLab

Hi, i have updated the question with 2 images that represent my current situation(after following your instructions). I am getting roughly 0.48 watts per second for a 5w and 12v light bulb. Kindly advice if the power readings i am getting are accurate.

Your analog input is connected to the wrong side of the relay.

Where should the analog input be connected?

To the high side of the resistor.  I will draw a circuit.

Normally the shunt resistor (in you schema 220 ohm) is way lower than the load it should measure, 12volt/5Watt = 0.42 Amp and R = U/I, 9V/0,42A = 21ohm. So your 220ohm's shunt is inflicting on the measurement value.
So to change the current measurement circuit you have to use a low ohm resistor and since the voltage drop over a shunt/low ohm resistor is small you need a amplifier.
Here is a page about how to calculate a shunt and use it with Arduino:
http://www.vwlowen.co.uk/arduino/current/current.htm
If we use a simplified version, 8v over the lamp and 1volt over the shunt.
U = I x R
Rlamp = 21 ohm
Ilamp = 8 volt/21 ohm
Rshunt = U/I = 1 volt/0.42 Amp

Thank you. Even if i change the resistor to 10 ohms, the output does not really change

Yes, you need to be below the resistant of the light bulb (0,42 ohm). I will modify my answer with the formula.


text:
Unable to connect ESP8266 to WPA2+Enterprise network
I am trying to connect ESP8266 module to WPA2+Enterprise network with my ssid, username and password and the latest version supports such connection. I followed this link, and the code:
#include "ESP8266WiFi.h"
extern "C" {
  #include "user_interface.h"
  #include "wpa2_enterprise.h"
}

static const char* ssid = "ssid";
static const char* username = "username";
static const char* password = "password";
const char* host = "host_ip";

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

  Serial.print("Connecting to ");
  Serial.println(ssid);
   // Setting ESP into STATION mode only (no AP mode or dual mode)
  wifi_set_opmode(0x01);

  struct station_config wifi_config;

  memset(&wifi_config, 0, sizeof(wifi_config));
  strcpy((char*)wifi_config.ssid, ssid);

  wifi_station_set_config(&wifi_config);

  wifi_station_clear_cert_key();
  wifi_station_clear_enterprise_ca_cert();

  wifi_station_set_wpa2_enterprise_auth(1);
  wifi_station_set_enterprise_username((uint8*)username, strlen(username));
  wifi_station_set_enterprise_password((uint8*)password, strlen(password));

  wifi_station_connect();
  Serial.print("Wifi station connect status:");
  Serial.println(wifi_station_get_connect_status());

  // Wait for connection AND IP address from DHCP
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println(WiFi.status());
    delay(2000);
    Serial.println("Not connected");
  }

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

void loop()
{
  delay(2000);
}

OUTPUT:
Connecting to ssid
Wifi station connect status:1
6
Not connected
6
Not connected
.....

Status 6 is  WL_DISCONNECTED,i.e., module is not configured in station mode. I am not able to figure out what is causing the problem.

The clear commands are not useful until after you have connected.
I use these commands just before setting user ID and password:
wifi_station_set_enterprise_identity((uint8*)username1, strlen(username));
wifi_station_set_enterprise_ca_cert(ca_cert, sizeof(ca_cert));

It is necessary that the radius server have default_eap_type set to TTLS or PEAP for username/password authentication. Perhaps there is another possibility, but there is a bug in ESP8266 so it does not properly search for supported EAP types.
const char* username1 = "anonymous"; //works for me

u8 ca_cert[] = "-----BEGIN CERTIFICATE-----\n"
"MIIFETCCA/mgAwIBAgIJAO0ntD34r/+QMA0GCSqGSIb3DQEBCwUAMIGiMQswCQYD\n"
"VQQGEwJVUzEXMBUGA1UECAwOTm9ydGggQ2Fyb2xpbmExDzANBgNVBAcMBkR1cmhh\n"
"bTEeMBwGA1UECgwVTWl0Y2hlbGwvVHJhbXBlciBJbmMuMR8wHQYJKoZIhvcNAQkB\n"
"FhBidXJ0bXNAZ21haWwuY29tMSgwJgYDVQQDDB9CdXJ0IFNlbGYgQ2VydGlmaWNh\n"
"dGUgQXV0aG9yaXR5MB4XDTE4MDEyMzE1NTgxOFoXDTE4MDMyNDE1NTgxOFowgaIx\n"
"CzAJBgNVBAYTAlVTMRcwFQYDVQQIDA5Ob3J0aCBDYXJvbGluYTEPMA0GA1UEBwwG\n"
"RHVyaGFtMR4wHAYDVQQKDBVNaXRjaGVsbC9UcmFtcGVyIEluYy4xHzAdBgkqhkiG\n"
"9w0BCQEWEGJ1cnRtc0BnbWFpbC5jb20xKDAmBgNVBAMMH0J1cnQgU2VsZiBDZXJ0\n"
"aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\n"
"AQC2O2m4JCmqimeztaZ8JasIuZqksrxvCjyWpkykoGzoR6v1/kDSuLgdp7EmtLKN\n"
"vOJPQ2ea0yVvkFf0dQYcgDhNdAsXcqskMOprS+jefzlLQUbU1jTk+AOSiOcmxWT1\n"
"H8uYhSp/1TkkWDM8dVO9RRIQyigVinsJNhdPyUVsTaQh3s29AL8CboixUNZWngOo\n"
"d1+66lwy4N+3hXACJWlurgvc0q7RfqSqfJY/+lugfID0ANpGQqqu1Dq2IXZbLyx9\n"
"roOPpC+fqX2wn5g9+RuA18OY/GPtkHc6clAoiJDGXsTRpffgsI5spdJ26WknbhO/\n"
"3Q2vQJ2Q5m/QvSp55qOM5nevAgMBAAGjggFGMIIBQjAdBgNVHQ4EFgQUT3hChU84\n"
"EEXHesDdKOtPqfhrg68wgdcGA1UdIwSBzzCBzIAUT3hChU84EEXHesDdKOtPqfhr\n"
"g6+hgaikgaUwgaIxCzAJBgNVBAYTAlVTMRcwFQYDVQQIDA5Ob3J0aCBDYXJvbGlu\n"
"YTEPMA0GA1UEBwwGRHVyaGFtMR4wHAYDVQQKDBVNaXRjaGVsbC9UcmFtcGVyIElu\n"
"Yy4xHzAdBgkqhkiG9w0BCQEWEGJ1cnRtc0BnbWFpbC5jb20xKDAmBgNVBAMMH0J1\n"
"cnQgU2VsZiBDZXJ0aWZpY2F0ZSBBdXRob3JpdHmCCQDtJ7Q9+K//kDAPBgNVHRMB\n"
"Af8EBTADAQH/MDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly93d3cuZXhhbXBsZS5v\n"
"cmcvZXhhbXBsZV9jYS5jcmwwDQYJKoZIhvcNAQELBQADggEBADNmDxddEh1XSo8J\n"
"fanCRuYqngpVFtKCzRNCtQ7aOAPrj6gRMtMAqQhlYmcbxjaVOCboAvJ8evY8x5We\n"
"YU6eIAmg95PlDws8EvcVQhO2ZYcuOHTvdu5Q4Ior0oXaCfqdS35YcPW7pRGprY/x\n"
"w7kbG84FFatpXPuDGQB65haqQ2KXPrILiE/jAKpTu9EBLEEN4uIAuxbB6unARovX\n"
"YoXIQHFc32bZAjihquvs4J7FNkcSr3lJpuv03dryqMB+Qn3G8yM7PFLNL2QyS0Zu\n"
"UbS5kDO7UqbTjtrUDolp5sUNvyrkX5ILYfZeEeaHqAlA20SFqNG7BcTY222NsCft\n"
"yNXqX1c=\n"
"-----END CERTIFICATE-----";

works for me. I have to go back and check whether those \n's are needed.
I think I found the enterprise_identity command important for both TTLS and PEAP, and I found I needed a ca_cert to do PEAP but not necessary for TTLS. I am not certain why.


text:
How to do with fzz file
I have a file YunConfig.fzz file for arduino yun for map maker project with ultrasonic sensor.
How can I open or do with that file?
please answer me.

That's a fritzing drawing.

Have a look at Fritzing.org.  With most unknown files you can use a text editor (Notepad) to look at the file.  Sometimes the file will be text and you might be able to read it.  The rest of the time it will be binary and it will look like garbage, however there might be some strings in there that give you a clue as to what application the file is for.

BTY, the Fritzing CAD software is not free. it is 9$ US.

Download and install the open-source, Fritzing CAD software for electronics hobbyist and open the .fzz file with that.
Versions are available for Linux, Mac, and Windows.
Installation instructions are on the downloads page.

Fritzing does no longer seem to be free (as in beer) and it's quite hard to compile the sources, IMHO

You can get the latest version here:
fritzing(dot)org/download/api/1.0/update/344
or find a version on softpedia

The Fritzing download is no longer available. Softpedia Link: https://www.softpedia.com/get/Science-CAD/Fritzing.shtml

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


text:
Time Library Adjust Default on Windows
Looking at this Time Arduino library because I would like to send time stamps with data across my HC05-PC channel.
https://playground.arduino.cc/Code/Time
I wrote this function to get the time at any point
String getTime() {
    String timeSecond = String(second());
    String timeMinute = String(minute());
    String timeHour = String(hour());
    String timeDay = String(day());
    String timeMonth = String(month());
    String timeYear = String(year());

    String now = timeHour + ":" + timeMinute + ":" + timeSecond + " " +
        timeMonth + "/" + timeDay + "/" + timeYear;

    return now;
}

It seems in the docs he provides info on how to set the default time on a Linux/Unix system so that this library will always be grabbing the correct time by editing some bash files.
When I run the function, having been compiled on Windows, it begins running on 1/1/1970 0:0:0.
He does not provide any documentation for setting the Windows time stamp. How would I go about doing that?

You probably need to show us the code where you receive/set the time.

I don't do an original set. Do you need extra hardware and another library to do that?

AFAIK, no Arduino has an internal clock. So you need to set the library time manually. On the page you link to search for "processSyncMessage". If you want to disconnect your Arduino from the PC after setting the time, I recommend you get a Real Time Clock module.

In that case, I'd have to reset the time before every upload/run?

That's what the example shell script does - sends the PC time to the Arduino.

The Adafruit RTClib has a function to use the compiler date and time. You use the TimeLib maintained by Paul Stoffregen. That library does not have such a function, but you can write it yourself. For example with sscanf and setTime. Without external RTC that will only work if you upload a sketch and keep the Arduino always on. I have a clock like that, and since that clock is always on, I never had the need to add a RTC chip. When the Arduino resets, it returns to the date and time when it was compiled.
If you use a Arduino Due or Zero or M0 then they have their own rtc library.
If you want the computer to send the date and time, then you could make a command and send that via the serial port or via Bluetooth.
What kind of date and time do you want ? The local time, including the offset of the Daylight Saving Time ? That is possible, but not easy to make on a Arduino with RTC chip, in that case it is easier to send a command from the computer with the newest date and time.
It that function okay ? The object 'now' disappeares when the function ends, and yet you return that object.

My issue is that is have this channel between the arduino hc05 chip and my computer. It seems that because only one bit can be transmitted at a time there is a delay in the data being sent from one side to the other. I want to use exact datetime to test this theory but it seems like it is more trouble than it is worth. (I am not going to keep and arduino attached to my laptop 24/7) or buy additional hardware. Running a command line command is a fair option but even that is too extensive for the purposes of the application.


text:
Convert string into char array in Arduino?
I am not that great at Arduino and C++ yet, but I'll give this a shot:
I have a char array that looks like this:
char PROGMEM bitmap[] = {0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE};

However, I receive this char array from a string, which is basically:
String input = "0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE";

How do I turn my input variable with a comma separated char array into the actual array? I need it to be fast and not use a lot of memory. I haven't been able to find a use case like this, because it's very unique.
I feel like this should be super simple to do, but I can't wrap my head around it.
Things I've tried and didn't understand that much:
1:
char delimiter[] = ",";

char* ptr = strtok_r(text, delimiter);

while (ptr != NULL) {
  Serial.println(ptr);
  ptr = strtok_r(NULL, delimiter);
}

cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'

2:
char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
int i = 0;
char bitmap[115];
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = str;
  i++;
}
Serial.println(bitmap);

(the total length of my characters are 4799 and the total length of hexadecimals are 114, so I'm just trying something here)
Error: Apparently you can't use  =?
3:
char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  Serial.println(str);
}

This actually prints the strings to the console, but trying to add them to a char array is still a mystery I am trying to solve right as I write this.
4:
char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
char *ptr;
char bitmap[115];
int i = 0;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = strtol(str, &ptr, 16);
  i++;
}

Serial.println(bitmap);

I'm getting a lot closer now. strtol(str, &ptr, 16) actually gives me the right integers I need, but it seems like my Arduino crashes when I run this code. It simply reboots it. Error:

assertion "heap != NULL && "free() target pointer is outside heap areas"" failed: file "/Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/heap/./heap_caps.c", line 171, function: heap_caps_free
  abort() was called at PC 0x4011c173 on core 1

While it may be frustrating to not get the answers you wanted, this isn't a code-writing service. Both here and on SO, good explanations have been given about the need to parse the string by the comma character, then parse each element therein from a set of characters into the actual byte you want. It's not impossible, but it's not necessarily a one-line-of-code answer, either.

@josecanuc I completely agree that this isn't a code-writing service. However, when I've tried basically everything I've seen so far, that should be able to do it, I'm really desperate. I'm not asking for someone to give me the code. I am more than capable of looking at different functions and do my own research, but when everything I've tried has failed, what's there left to do? I come with my case and idea and hope that someone understands it and helps me solve the problem. Not give me the answer, although that would help more, but help me.

Seperate using strtok into individual strings is done and easy. Adding them to an array of chars is not that easy.

You got some useful comments on SO and an answer here, but now you deleted both questions and wasted everyone's time, who tried to help you. That isn't nice.

Also show us what you tried and explain why it isn't working. Otherwise the question is too-broad.

@gre_gor I'm not here to discuss the way I ask questions. I'll update my post with things I've tried, hold on.

@gre_gor See updated post.

@gre_gor, would you mind posting a link to the deleted questions? You can find the URLs in your browser history. That would be useful for others to determine whether they should spend any time trying to answer this question and also anyone who has a similar question.

@per1234 Unfortunately I was at work at that time and the browser history is gone. And as far as I know, you can't really see the deleted questions, event if you still have the URL.

@per1234: https://stackoverflow.com/questions/46225826/convert-string-into-char-array-in-arduino https://arduino.stackexchange.com/questions/44745/convert-string-into-char-array

So after a lot of help and some tweaking, I finally got it to work!
String text = server.arg(0);

char buf[text.length()];
text.toCharArray(buf, text.length());
char *p = buf;
char *str;
char bitmap[960]; //960 is fixed for now, need to count amount of commas + 1
int i = 0;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = strtol(str, NULL, 16);
  i++;
}

bitmap now contains all the XBM data from the GET request. I ran into some issues, causing the device to restart, because I accidentally forgot that the length of the bitmap array isn't 114 (that's the amount of horizontal pixels of the display). This caused it to overflow by a lot.
Huge thanks to jose can u c for helping me.

You note you can easily use strtok() to get individual strings of the text representation of the hex values. So now all you need is to convert the string "0xD7" or similar into the number 0xD7.
Have a look at strtol() function to perform that task.

Now that's something I like to see. Using strtok() I now have each value as a string. Using strtol() on that, I now get them all as longs. See my updated post (number 4). The Arduino crashes when I try this.

strtol(str, NULL, 16)

Same problem. Here's a small detail: If I remove the Serial.println(bitmap) it does not crash immediately. If I then add the display.drawXbm() to draw it on my OLED screen, it crashes the Arduino. Am I running out of memory perhaps?

Serial.println(bitmap) is interpreting bitmap as a C-style string, but it's not null-terminated (nor does it likely contain printable ASCII values), so it runs amok and causes a crash. Once you have your array of bytes, it's no longer a string, but an array of bytes, and you can't use it where you would use a string. What are you trying to print? What output are you expecting from Serial.println(bitmap) ?

I'm not sure. I was hoping I could see what it contained, but that's not how it works. Discard the Serial.println(bitmap).

If you want to see what it contains, print each element of the array separately (bitmap[0], then bitmap[1], ...). Handily, Serial.println(bitmap[0], HEX); will print the byte in hexadecimal representation.

Roger that. However, it does not fix the crashing. I've never seen an error like this.

Change your bitmap type as uint8_t bitmap[115];

Still crashes with the same error. Not sure if this backtrace helps: Backtrace: 0x400872b4:0x3ffd01c0 0x400873b3:0x3ffd01e0 0x4011c19b:0x3ffd0200 0x400825c3:0x3ffd0230 0x40082a35:0x3ffd0250 0x4000bec7:0x3ffd0270 0x400d4f02:0x3ffd0290 0x400d1710:0x3ffd02b0 0x400d1733:0x3ffd1620 0x400d40fb:0x3ffd1640 0x400d414b:0x3ffd1660 0x400d4182:0x3ffd1690 0x400d4295:0x3ffd16d0 0x400d185e:0x3ffd1710 0x4011b4c8:0x3ffd1730

Let us continue this discussion in chat.

When dealing with string containing values separated by comma (or any other special character), you use the function strtok to parse the string. That means, separate each value.
The mechanics is:

In the first call you indicate the string to parse and the delimiters. That calls return a pointer to the first token found.
After that, you keep calling the same way, but passing NULL as the string to parse.
When the call returns a NULL, you are done.

Here is how you do it:
void setup()

{
Serial.begin(9600);

String input = "0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE,0x0,0x1,0xFF,0x10,0x2";
char *pch;

Serial.print("Splitting string '");
Serial.print(input);
Serial.println("' into tokens:\n");
// --- Start the strtok scan
pch = strtok((char *) input.c_str(),",");

// --- Cycle thru each comma separated hex value.
while(pch != NULL) {
    //  pch poinst to a string representation of an hex value.
    Serial.print(pch);
    Serial.print(" ->");
    //  convert string to value.
    char *p = pch + 2;        // Skip "0x"
    int val = hex2dec(*p++);  // Convert first hex digit.

    if(*p) {  // Convert an optional second hex digit.
        val = val * 16 + hex2dec(*p);
    }

    Serial.println(val, HEX); // Print the value to check.
    //  Next hex value
    pch = strtok(NULL, ",");
}
}

/*
 * Convert a hex digit to decimal.
 */
int hex2dec(char d)
{
    int val = 0;

    if(isDigit(d)) {
        val = (d - '0');
    } else {
        val = 10 + (toupper(d) - 'A');
    }

    return val;
}

Interesting. The first you say is something I've learned now. Great stuff, actually. Your example is basically half done right there. It still needs to be added to a char array (I can't use each individual value for anything). Can be done farely easy, though. Thanks for a further explanation and some more code to look at!


text:
Odd Serial behavior with Uno
I'm not understanding what's going on with my Uno. I have a very simple piece of code. no peripherals are connected. Just a bare genuine uno. I program in VisualMicro for Visual Studio.
void setup()
{
    Serial.begin(115200);

    char stringy[9] = { 0x7E, 0x00, 0x05, 0x08, 0x01, 0x44, 0x33, 0x04, 0x7B };

    for (int i = 0; i < 9; i++) {

        Serial.print(stringy[i]);
        //delay(300);
    }

    Serial.println("");
    Serial.print("done");
}

void loop()
{
    while (1) {  }
}

Without a delay of around 250msec or greater in the for loop, I don't get all the characters. In fact, without the delay, the code doesn't even finish executing. I only get the first character '~'. It doesn't seem to matter what my baud rate is.
This code runs fine without a delay on my Nano. What could possibly be the issue?

Your program works as expected on my Uno.

Weird. You get the whole array of gibberish in your serial pane? I'm starting to think its just a difference in compilers.

Not the serial pane (I'm not using the IDE). I typed stty -F /dev/ttyACM0 raw 115200 && hd -n 15 /dev/ttyACM0 on the Linux console and got 00000000  7e 00 05 08 01 44 33 04  7b 0d 0a 64 6f 6e 65     |~....D3.{..done| (hd is a hexdump utility).

You are printing the unprintable.
Do you think it should print:
~0581,34{

or
0x7E 0x00 0x05 0x08 0x01 0x44 0x33 0x04 0x7B

What you will get is
tilde
null
enquiry
backspace
start of heading
comma
three
end of transmission
open brace

I think you can call
Serial.print(stringy[i], HEX);

To see the number you put in come out.

I expect it to come out gibberish, like this: ~    D3 {  (three of those white spaces actually show as strange characters that I can't paste here.) The actual content of the array is an Xbee AT command, and I designed this as an experiment to see why it's not working.
See, when I use the Xbee library with the nano and monitor the serial output without the xbee connected, ~    D3 { is what I see. But on the Uno, all I get out is ~. In this experiment I was trying to replicate the output with serial.print(), and the result is the same.


text:
Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega
I am trying to follow Need help to set PWM frequency to 25kHz and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4; I dont see any success; could someone please help?
Given below is the code I have tried based on an answer by @EdgarBonet in the linked post and  I tried on connecting fan pwm on each of the 3 pins 6, 7, 8 one by one and still cannot get the speed to change and the fan is just running at full speed;
void analogWrite25k(int value)
{
    OCR4A = value;
    OCR4B = value;
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCCR4C = 0;
    TCNT4  = 0;
    TCCR4A = _BV(COM4A1)
           | _BV(COM4B1)
           | _BV(COM4C1)
           | _BV(WGM11);
    TCCR4B = _BV(WGM13)
           | _BV(CS10);
    TCCR4C = _BV(WGM13)
           | _BV(CS10);
    ICR4   = 320;

    // Set the PWM pins as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    analogWrite25k(10);
    for (;;) ;  // infinite loop
}

edit2:
Thanks for the hints by @dannyf; I read the datasheet again and below is what I am trying now but even this is not working and I am really unable to figure out if something is not right in this; I am trying to set value of OCR4C only in analogWrite25k method since fan pwm line is connected to digital pin 8 of my Mega;
TCCR4A = 0;
TCCR4B = 0;
TCNT4  = 0;
TCCR4A = _BV(COM4C1)
      | _BV(WGM41);
TCCR4B = _BV(WGM43)
     | _BV(CS40);
ICR4   = 320;         // TOP = 320

Comments are not for extended discussion; this conversation has been moved to chat.

Found a properly working answer for the question finally; Thanks to KIV's answer on Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega to control speed of a 4-wire cpu fan  an additional usful thing he has added is to allow setting of duty cycle from serial monitor input for convenience while testing;
void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;

    // Mode 10: phase correct PWM with ICR4 as Top (= F_CPU/2/25000)
    // OC4C as Non-Inverted PWM output
    ICR4   = (F_CPU/25000)/2;
    OCR4C  = ICR4/2;                    // default: about 50:50
    TCCR4A = _BV(COM4C1) | _BV(WGM41);
    TCCR4B = _BV(WGM43) | _BV(CS40);

    Serial.begin(115200);

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    int w = Serial.parseInt();
    if (w>0) {
        analogWrite25k(w);
        Serial.println(w);
    }
}

easy.

find a copy of the datasheet for your mcu;
go to the section about your timer;
figure out a prescaler setting that yields the maximum roll-over count;
pick the timer mode that supports the roll-over count;
write your own analogWrite() function;
[optional] if you wish to reuse the stock analogWrite(), make sure that roll-over count calculated in 3) is a valid data type for the stock analogWrite(). If not, increase the prescaler in 3) until it is.
done.

edit: i decided to give it a try.
the following code:
void setup() {
  // put your setup code here, to run once:
  pwm1Set(TMR1_PS8x, F_CPU / F_PWM1 / 8);       //ps = 8x, top = F_CPU / F_PWM / 8 = 80
  analogWrite(9, 20);                           //dc = 20/80=25%
  analogWrite(10, 40);                          //dc = 40/80=50%
}

void loop() {
  // put your main code here, to run repeatedly:
}

produced the following output on an ATMega328p's TIMER1.

i'm reasonably sure that the output is indeed 25Khz.
the code itself however is capable of generating pwm at other frequencies.
edit2: the same code on mega2560 generating 25Khz pwm on pin6/7/8:

code used for that is as follows:
  //ps = 8x, top = F_CPU / F_PWM / 8 = 80
  //DC on Pin 6 = 20/80 = 25,
  //DC on Pin 7 = 40/80 = 50,
  //DC on Pin 8 = 60/80 = 75,
  pwm4Set(TMR4_PS8x, F_CPU / F_PWM4 / 8); analogWrite(6, 20);  analogWrite(7, 40);  analogWrite(8, 60);

pwm4Set() is a copy of pwm1Set(). Both are simple enough: only 5 lines of code used.

thanks for the response but the question was specific to arduino mega 2560;

@dannyf - thanks for the edit and help on mega but I am not sure where to get the pwm1Set or pwm4Set functions; are they builtin functions or part of some additional library?


text:
A beginner lost at sea, Arduino looking at the sun
I am working on trying to make a LED strip respond to natural Light levels for a sculpture. I have reached a problem in trying to get the code to work when sending PWM to the light strip. Thank you for any suggestions!
const int analogInPin = A0;
const int analogOutPin = 9;

int sensorValue = 0;
int outputValue = 0;

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

void loop() {
  sensorValue = analogRead(analogInPin);
  outputValue = map(sensorValue, 0, 1023, 0, 500);
  analogWrite(analogOutPin, outputValue);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\t output = ");
  Serial.println(outputValue);
  delay(2);
}

I am using an NTE 2908 N-channel.

You have to explain what your problem is.

The LED strip won't respond to the Photocell, I apologize for being unclear haha.

Narrow it down: Print the values read from the LDR to serial. Is that the problem?  Make the LED strip blink: is that the problem? If you can do each individually then the problem is joining it together in code. If one fails by itself then there is something wrong with that bit, obviously.  BTW, analogWrite() takes values from 0-255 not 0-500.

I guess my problem is making it blink. Thank you.

A problem in your code:
outputValue = map(sensorValue, 0, 1023, 0, 500);
analogWrite(analogOutPin, outputValue);

The range for outputValue is from 0 to 500, but analogWrite only takes from 0 to 255.

What do you mean you "guess the problem is making it blink".   Firstly, why are you guessing?  Don't you know what your problem is?  Secondly, blinking wasn't mentioned anywhere in your post and nothing in your code even attempts to do anything like blinking.  Can you please describe what you actually want this thing to do?

I'm voting to close this question as off-topic because it has been abandoned for months without ever stating a specific answerable question.

@ChrisStratton why off-topic all the time? It seems like "unclear what you're asking" would be the obvious choice here.

You'd better post also the schematic, but I'm pretty sure you just messed up the circuit.
I think you just put the ground connection for the LED strip in the wrong pin (AREF). If you look, the top-most blue wire goes to the third pin from above in the right connector (which is AREF) instead of the fourth one (which is GND). Move this and it should work
Otherwise, put the schematic on the question

How about pinMode (analogOutPin, OUTPUT); ?

It isn't needed if you're going to use analogWrite.  If you'll look at the first few lines for the source for analogWrite you'll see exactly why that is true (analogWrite sets the pinMode itself.)

@Delta_G It's safer that way. When you work in multiple platforms you can't depend on details like this. Other platforms may follow other defaults. May be it's an undefined behaviour and will change tomorrow. Omitting pinMode gain you nothing and makes your sketch less clear.

That still doesn't make it relate in any way to the OP's problem.  And I could turn that argument the other way, there's just as likely to be a hypothetical change where pinMode would break an analogWrite.  I would think that more likely even since the documentation says you don't need it they wouldn't worry about breaking code that did.  Point being, you need to know details about your platform before writing code. Don't assume this might happen or that might happen.  Don't assume anything in this game.  Assumption is the mother of all screw ups.  Always read instead of assuming.


text:
Receive an array of characters using SIM900 module
I tried to receive an array of characters using SIM900, but I couldn't. I can receive just one character like 'G', but I want to receive a string "abcd". When I used char* to save the SMS, I failed.
Does anyone know how?
My code:
#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

void setup()
{
    pinMode(3,OUTPUT);
    Serial.begin(19200); // for serial monitor
    SIM900.begin(19200); // for GSM shield
    SIM900power(); // turn on shield
    delay(20000); // give time to log on to network. `
    SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
    delay(100);
    SIM900.print("AT+CNMI=2,2,0,0,0\r");
    // blurt out contents of new SMS upon receipt to the GSM shield's serial out
    delay(100);
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button24
{
    digitalWrite(9, HIGH);
    delay(1000);
    digitalWrite(9, LOW);
    delay(7000);
}

void loop()
{
    // Now we simply display any text that the GSM shield sends out on the serial monitor
    if(SIM900.available() >0)
    {
        char *in = SIM900.read();
        if (in =="abcd") digitalWrite(3,HIGH);
        if (in == "00") digitalWrite(3,LOW);
    }
}

It solved . I used another library that manipulated . And just support sim900
U can get it in this below link and include to your arduino IDE
This library written by digispark group

How was that  solution?

Right and stable@Aiapaec

I meant, Could you post the code of the solution?

No.The solution codes are in the library in answer . You should download library and include it in your arduino ide @Aiapaec

#use this code and then inform me"
#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

void setup()
{
    pinMode(3,OUTPUT);
    Serial.begin(19200); // for serial monitor
    SIM900.begin(19200); // for GSM shield
    SIM900power(); // turn on shield
    delay(20000); // give time to log on to network. `
    SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
    SIM900.write(0x22);
    SIM900.write(0x0D);
    SIM900.write(0x0A);
    delay(100);
    SIM900.print("AT+CNMI=2,2,0,0,0\r");
    // blurt out contents of new SMS upon receipt to the GSM shield's serial out
    delay(100);
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button24
{
    digitalWrite(9, HIGH);
    delay(1000);
    digitalWrite(9, LOW);
    delay(7000);
}

void loop()
{
    // Now we simply display any text that the GSM shield sends out on the serial monitor
    if(SIM900.available() >0)
    {
        char *in = SIM900.read();
        if (in =="abcd") digitalWrite(3,HIGH);
        if (in == "00") digitalWrite(3,LOW);
    }
}

Hi.  Thank u . But these didn't work. I need to choose memory and save sms in side and open it (to this we have need to  use AT commands)

An explanation of what you changed would be useful.

It solved . I used another gsm library and worked.@gre_gor


text:
Protothread Library Stalling on One Thread
I am trying to use a protothreading library found here
http://harteware.blogspot.com/2010/11/protothread-powerfull-library.html
to perform protothreading with my Arduino so I can "simultaneously" read from the HC-05 Bluetooth chip input to receive information from the master computer which I am connected to over Bluetooth while also processing and transmitting data from the sensors over Bluetooth.
My code looks like this
/*
    This module uses the L293D chip to modulate and power
    two DC motors controlling the wheels of the FryeBot
*/

#include <Time-1.5.0\Time.h>
#include <WiShield\pt.h>

/*L293D INPUT 7*/
const int YELLOW_GEAR_MOTOR_BACK = 8;

/*L293D INPUT 2*/
const int YELLOW_GEAR_MOTOR_FORWARD = 9;

/*L293D INPUT 10*/
const int RED_GEAR_MOTOR_BACK = 10;

/*L293D INPUT 15*/
const int RED_GEAR_MOTOR_FORWARD = 11;

/*
    Establish ratio os the rate of the faster slower gear
    to the faster gear to scale the duty cycle of the
    faster gear
*/
const float RED_GEAR_SPEED_TO_YELLOW = 0.97;

/*Constant for full duty cycle for analogWrite*/
const int FULL_ANALOG_MOTOR_SPEED = 255;

/* HC05 Setup Data */
const int pingPin = 7;
const int HC05PowerPin = 2;

/* Distance data */
long duration, cm;

/* Values for Bluetooth RX/TX */
char buf[25];

char current;
String messageHolder;
String message;

/* Protothreads */
static struct pt pt1, pt2;

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

    /* add setup code here */
    pinMode(YELLOW_GEAR_MOTOR_FORWARD, OUTPUT);
    pinMode(YELLOW_GEAR_MOTOR_BACK, OUTPUT);
    pinMode(RED_GEAR_MOTOR_BACK, OUTPUT);
    pinMode(RED_GEAR_MOTOR_FORWARD, OUTPUT);
    pinMode(HC05PowerPin, OUTPUT);

    PT_INIT(&pt1);
    PT_INIT(&pt2);

}

static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;

    PT_BEGIN(pt);

    while (1) {
        collectAndTransmitData();
        PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
    }

    PT_END(pt);
}

void collectAndTransmitData() {
    digitalWrite(HC05PowerPin, HIGH);

    pinMode(pingPin, OUTPUT);
    digitalWrite(pingPin, LOW);
    delayMicroseconds(2);
    digitalWrite(pingPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(pingPin, LOW);

    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin, HIGH);

    cm = microsecondsToCentimeters(duration);

    Serial.print("TX: ");
    Serial.print(cm);
    Serial.println();

    if (message.indexOf("G") > 0) {

        analogWrite(YELLOW_GEAR_MOTOR_FORWARD, (int)(RED_GEAR_SPEED_TO_YELLOW * (float)FULL_ANALOG_MOTOR_SPEED));
        digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

        digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
        digitalWrite(RED_GEAR_MOTOR_FORWARD, HIGH);
    }
    else if (message.indexOf("S") > 0) {
        digitalWrite(YELLOW_GEAR_MOTOR_FORWARD, 0);
        digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

        digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
        digitalWrite(RED_GEAR_MOTOR_FORWARD, LOW);
    }

    /* Load the distance value into a buffer */
    String sendValue = String(cm);
    sendValue.toCharArray(buf, sizeof(buf));

    /* Write the buffer with a space after for parsing*/
    Serial1.write(buf);
    Serial1.write(' ');
}

long microsecondsToCentimeters(long microseconds) {
    // The speed of sound is 340 m/s or 29 microseconds per centimeter.
    // The ping travels out and back, so to find the distance of the
    // object we take half of the distance travelled.
    return microseconds / 29 / 2;
}

static int protothreadReadAndParseData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;

    PT_BEGIN(pt);

    while (1) {
        readAndParseData();
        PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
    }

    PT_END(pt);
}

void readAndParseData() {
    Serial.println("HERE");
    current = Serial1.read();
    Serial.print("RX: ");
    Serial.print(current);
    Serial.println();

    if (current == ' ') {
        message = messageHolder;
        messageHolder = "";
        Serial.print("message: ");
        Serial.print(message);
        Serial.println();
    }
    else {
        messageHolder += current;
    }
}

void loop() {
    Serial.println("A");
    protothreadReadAndParseData(&pt2, 20); // by calling them infinitely
    Serial.println("B");
    protothreadCollectAndTransmitData(&pt1, 20); // schedule the two protothreads
}

The code prints the following in the console when executed.
A
HERE
RX: �
B
TX: 522
TX: 524
TX: 524
TX: 524
TX: 524
TX: 524

Then continues with TX: ### forever.
I am not sure why the code is not looping back to the first function or at least running it a second time. I am not very clear on exactly how to use this library or who maintains it. The docs on their Github page for their WiShield library which this pt.h is part of are not overly helpful. If you have any experience with other Arduino protothreading libraries let me know so I might try them out. I am not sure where I went wrong with this library in my implementation.
Here is the repo containing the package I am using
https://github.com/nicolaskruchten/arduino/tree/master/libraries/WiShield

In protothreadCollectAndTransmitData you have a timestamp variable that never gets updated:
static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;   // <- This never changes
    ....

When the condition is true you will need to update timestamp = millis();.
static int protothreadCollectAndTransmitData(struct pt* pt, int interval) {
    static unsigned long timestamp = 0;

    PT_BEGIN(pt);

    while (1) {
        PT_WAIT_UNTIL(pt, millis() - timestamp > interval);
        // Updated. Move this here, else it ALWAYS gets called!
        collectAndTransmitData();
        timestamp = millis();   // <- Update timestamp for next time
    }

    PT_END(pt);
}

But to make sure that is correct, you should look at the macro:
#define PT_WAIT_UNTIL(pt, condition) \
do {                                 \
    LC_SET((pt)->lc);                \
    if(!(condition)) {               \
        return PT_WAITING;           \
    }                                \
} while(0)

(You can ignore the do/while - that's just there so you can use a semi-colon.) As you can see, when the condition is false a return is issued. So it looks like it is safe to do it this way.
Disclaimer: I've never used this threading library. I'm working off of the source code I found here: https://github.com/fernandomalmeida/protothreads-arduino/blob/master/pt.h

if you had to guess, what would you put on the millisecond argument in loop() to optimize performance for each of the threads? my baud for the serial is 9600, so i think it would make sense to try a 1 on that. Having done so, it looks like it only wants to run that thread. Barely ever touches the other one running at 20 ms

does that lib work with arduino?

Looks like I had the wrong link. Updated with what appears to be the Arduino port.

The timeout for collectAndTransmitData should be whatever your sample rate is. How often do you need to check the sensor? For readAndParseData() I would add if (!Serial.available()) return; as the first line so the function never gets entered unless a message is waiting.

it seems it will only run one thread continuously for a while then switch. I will try your library

looking at it, i think it is a different source but the same file

it is still just transmitting

Oh, I just noticed that collectAndTransmitData(); should come after PT_WAIT_UNTIL(....).

Let us continue this discussion in chat.


text:
Programming a servo on an ATtiny85
Board: "ATtiny25/45/85"
Processor: "ATtiny85"
Clock: "Internal 1 MHz"
Programmer: "Arduino as ISP"
I want to run a servo forwards and backwards on an ATtiny85. The servo library is not compatible with the ATtiny85 so I had to write code from scratch. At this point, the code that makes the servo go forwards (clockwise) is:
void setup() {
  pinMode(PB1, OUTPUT);
}

void loop() {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  // 1 millisecond determines the servo going forwards
  digitalWrite(PB1, LOW);
  delay(19);
}

And the code that makes the servo go backwards (anti-clockwise) is simply by changing the amount of microseconds to:
delayMicroseconds(2000);

I want to have the servo motor go forwards one cycle for a few seconds and then go backwards for a few. I want this to keep looping. At this point my code is:
void setup() {
  pinMode(PB1, OUTPUT);
}

void loop() {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  digitalWrite(PB1, LOW);
  delay(19);
  digitalWrite(PB1, HIGH);
  delayMicroseconds(2000);
  digitalWrite(PB1, LOW);
  delay(19);
}

This however just makes the servo go back and forward at the same spot forever. I do realise I might need a for loop for this but I am confused as how I will do this.

Did you have a try on using 8MHz.

@AllenChak yeah I did try that however, that still doesn't produce the output that i want because I want the servo to spin forwards and backwards in a row rather than separately.

Try this link: https://forum.arduino.cc/index.php?topic=62912.msg459183#msg459183

The servo can't move back and forward in 40 milliseconds. It'll be more like tremble between both.
Try something like this:
// keep sending 0 position for about 400ms
for(int i = 0; i<20; ++i) {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  digitalWrite(PB1, LOW);
  delay(19);
}

// keep sending second position for about 400ms
for(int i = 0; i<20; ++i) {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(2000);
  digitalWrite(PB1, LOW);
  delay(18);
}

Hi thanks a lot it really helped and it makes sense too. I just have one question, that delay(19) when changed to delay(20) the servo behaves differently. Why is that delay kept at 19 milliseconds and not something else? thanks again.

The servo expects pulses at 20ms rate (= 50Hz) including High side pulse width.

In trying to find basic code to work a servo, this helped a lot. Thank you!


text:
Variables displayed incorrectly
I am making a keypad and when I try to save the buttons that were pushed they reset back to zero.
int tmp = 1;
int digit = 1;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int code = 0;

void setup() {
  Serial.begin(9600);
  pinMode(7, INPUT);
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  if (digit > 4) {
    digit = 1;
  }
  for (int i = 2; i <= 7; i++) {
    int tmp = digitalRead(i);
    if (tmp == HIGH) {
      if (digit == 1) {
        int a = i - 1;
      }
      if (digit == 2) {
        int b = i - 1;
      }
      if (digit == 3) {
        int c = i - 1;
      }
      if (digit == 4) {
        int d = i - 1;
        Serial.print(a);
        Serial.print(b);
        Serial.print(c);
        Serial.print(d);
        digitalWrite(8, HIGH);
      }
      digitalWrite(9, HIGH);
      delay(100);
      digitalWrite(9, LOW);
      delay(100);
      Serial.print(i);
      digit++;
    }
  }
}

There is a library for a keypad: https://github.com/Chris--A/Keypad If you want to make your own code, you have to specify what you want: should multiple keys presses at the same time being detected ? should there be debouncing ? do you want to know how long a key is pressed ?

I already have key detection but for some reason when I have it output variables A B C and D it only stores the last digit and the rest are 0

@NathanAnderson - The compiler would be warning you about the issue, but warnings are turned off in the Arduino IDE by default.

You can make your code more flexible by keeping a running total (int total = 0;) and just add to it with each keypress: total = (total * 10) + i; - where i is the most recent digit input by the user.

Do you know what int a; does?
For example you have a global variable a and then you have local a. Local one hides global one.
In all cases you're changing local variables. Then you're printing global a,b,c and local d.


text:
WS2812 (?) RGB LED matrix turns on white
I have an RGB LED 8x8 matrix which is claimed to consist of WS2812. When turning it on, it automatically lights up all LEDs white with full brightness. The LEDs even light up without DIN being connected. I remember reading something about this behaviour and I think it was related to the LEDs being SK6812 or similar rather than WS2812, but I can't find this page anymore, nor anything else describing this behaviour.
My question is, how can I disable the LEDs lighting up when turning power on? Of course I could add some kind of relay to switch them on right before the signal is sent by the Arduino, but is there something simpler?

that's a feature of most led strips so you can test the leds without having to connect them to a control box, or be able to use them as leds until you can install the controller

I see, but is there a way to disable it?When I connect everything all 64 LEDs are lit up on full brightness white for about a second until the Arduino executes my program. Problem is I need to run on batteries and therefore lowered brightness to around 25%, so the initial flash not only looks bad, but also drains my battery.

I don't think that initial flash will drain that much Ah

If you had the Arduino "controlling" the lights and it had turned them off and then you disconnect and reconnect the power do they still flash?  (Arduino still running and DIN left connected)  The reason I am asking is because if they do still flash what different would a relay/switch on the power line make?  When you turn the power on, they will flash for a second. (I appreciate that the 'switch' is not the preferred solution, but...)

Just tried that, and unfortunately the LEDs still flash. My idea was that maybe it took the Arduino around a second to boot up and initialise everything (I'm using FastLED), and set the pin to output mode. So if I first initialised everything, then just flipped the switch to power on the LEDs and immediately set them to the correct brightness, the problem would not be notable.

Use a MOSFET to control the matrix power line and activate the MOSFET only a few milliseconds before turning off your LEDs: this way the few millis intercurring between power on and off control signal will not be noticeable and will reduce the current bootstrap consumption.

simulate this circuit – Schematic created using CircuitLab

That is the alternative approach I had in my mind. Thank you for the nice schematics :)

If that solves your problem please mark the answer as accepted, otherwise, this question will remain listed among those without an accepted answer.

@RobertoLoGiacco Why do we need R1?

The MOSFET has a capacitance you need to charge up to activate it: R1 is there to limit the current spike produced when you charge up that capacitance.


text:
ESP8266: Client Server Based Home Automation System
I am working on a home automation project in which I am trying to use Star Topology, where one esp8266 acts as a server and can be accessed from web browser to receive commands from the user, while two or more esp8266 acts as clients which are connected to relays. Upon the request of user, server esp8266 sends command to the respective client to trigger the relay and the client esp8266 replies with the current status of the relay.
Connections isn't a problem so I am keeping those things aside. So far

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

const char *ssid = "AndroidAP";
const char *password = "qvdo2440";

ESP8266WebServer server(80);
String webPage = "";

void handleRoot() {
  server.send(200, "text/html", webPage);
}

void setup() {
  webPage += "
ESP8266 Web Server
";
  webPage += "
Socket #2 <button>ON</button>
 <button>OFF</button>
";

  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println();
  while (WiFi.status() != WL_CONNECTED) {
   delay(500);
    Serial.print(".");
  }
  Serial.print("Configuring access point...");
  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.on("/", handleRoot);
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

This is the code for server side. I cannot think of how to program for client side. Any help would be appreciable.
And yes. I have been through many articles, tried out many things which i found on the internet. But nothing could help me. So i am here for few more suggestions with better elaboration.

Make each ESP8266 totally autonomous. They received commands as page requests (REST) and return results. Make a Web Server on a PC, with a page that links all the individual ESP8266 for command and results display.

I got your point. N it seems absolutely fine for my type of project. Can i do the same thing on my web host instead of making a server on my pc? And it would be very helpful if you could share some references for the same.

ESP8266 APs can only handle 4 incoming clients, so they aren't good stand-alone servers.

dandavis --> what should be my approach to achieve the completion of my project. Hope the vision of my project is clear. There are going to be n no. of nodes

I'm voting to close this question as off-topic because to OP really just wants someone to write the code for him

I agree with most of 'Look Alterno's comment.  So here it is explained in more detail.
Each ESP runs a web server.
Each ESP will handle

GET /root/status
POST /root/change?device=x,state=y

When a client requests /root/status information on each relay managed by the device will be displayed.  For satellite ESPs this will mean displaying live data and for the central on it will mean displaying the last known state (it could also request an update at this time).  If you use an array then presenting this information will be quite simple.
When a client posts a change to a device then the satellite ESPs will change the relay state and the central ESP will forward the message onto the satellite.  It should probably also request a status update to check that the change has occurred.
If you steer clear of hardcoding things and use arrays rather than variable1, variable2, variable3 you should be able to make this expandable.  The biggest problem you will have is registering the satellites with the central device, but you could get around that for now by adding a configure page which had a HTML form that allowed you to enter the IP address of the central device and enter the name of the satellite and the name of the things connected to the relay.
Personally I wouldn't use a PC web server, yes it gives you more processing power, but I don't think you really need it for this, I was surprised how good they were.  If you have issues look at using an ESP32 instead of a ESP8266 for the central node.
I hope that helps

can u please share some references so that i could learn how to achieve this? Im just 14. I am not aware of much of programming

www.w3schools.com/html would be the best place to start.  You already know how to convert a html file into string, you've done that already.  Look at forms for posting examples and GET is the default that you know how to do.

I used a NodeMCU as a WebServer, but it fails when it comes to big files (.js, images ...). Later I discovered MQTT and ditched HTTP/HTML for good/ever. No more CSS, HTML, HTTP, JavaScript. No more server configuration. Just pure, simple and plain MQTT.

Code Gorilla --> i have learned the html. I am aware of GET & POST method of html form. But i cant conclude this to implement this thing to my project.

Look Alterno --> I have been studying MQTT since the time you suggested. It seems great. Hope this takes me to the solution i am waiting for. Any relevant references or tutorials will be highly appreciated

Also i have found a great visual tool "Node-Red". I believe Node-Red, MQTT, Esp8266 will accomplish my needs. Correct me if i am wrong

Look Alterno --> MQTT is great stuff but it becomes necessary to use a third party broker. So it is definitely not my cup of tea. I want to build a system without any third party involvement

@RohitMathur - You have already implemented a handler for GET in the code you posted above.  A handler for POST is quite similar and there are lots of examples out there.  Or are you asking me to do it for you?

@CodeGorilla --> that would be a pleasure :P help me with the code please. i am heading nowhere to implement these methods.

Is this the thing you were guiding me on?
HTTPClient http;
http.begin("IP of Client ESP");
http.addHeader("Content-Type", "text/plain");
int httpCode = http.POST("Message from esp8266");
String payload = http.getString();
http.end();

#include<ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
String i;
long newvar;
String httpurl;
String TheHiddenAnswerOfClient;
HTTPClient http;
String SendWithAnswer(String IPcache, String monmessagecache)
{
  httpurl = "http://";
  httpurl += IPcache;
  httpurl += monmessagecache;
  http.begin(httpurl);
  http.GET();
  TheHiddenAnswerOfClient = (http.getString());
  http.end();
  return TheHiddenAnswerOfClient;
}

void setup() {
  // put your setup code here, to run once:
  i = "";
  newvar = 0;
  Serial.begin(9600);
  WiFi.disconnect();
  delay(3000);
  Serial.println("START");
  WiFi.begin("electromodule", "electromodule@456");
  while ((!(WiFi.status() == WL_CONNECTED)))
  {
    delay(300);
    Serial.print("..");
  }
  Serial.println("Connected");
}

void loop() {
  // put your main code here, to run repeatedly:
  i = (SendWithAnswer("192.168.0.2", "YES"));
  Serial.println("Before Clear");
  Serial.println(i);
  i.remove(0, 25);
  i.remove(i.length() - 11, 11);
  Serial.println("After clear");
  Serial.println(i);
  newvar = i.toInt();
  Serial.println((2000 + newvar));
}

This is the codefor clent side.the ip of the server will be provided in the code so that the server and clent are connected .Also include client header file in the program

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


text:
Esp32 Https Problem
I am working on a project in which i have to send GET request to my Company's  Https server. I have successfully sent the GET request using NodeMCU v 1.0 (ESP 12E). The NodeMCU 1.0 (ESP 12E) Arduino library uses SSL certificate Fingerprint ,host name and url to send the GET request. it is easy to find the fingerprint of Certificate using this website ->  https://www.grc.com/fingerprints.htm
But in ESP 32 Arduino Library i have to pass the SSL certificate . I have no idea how to find the SSL certificate of my Company's website.
The format of the SSL certificate used in ESP 32 Arduino library is given below :
/*
const char* ca = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \
"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \
"DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \
"SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \
"GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \
"AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \
"q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \
"SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \
"Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \
"a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" \
"/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" \
"AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" \
"CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" \
"bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" \
"c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" \
"VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" \
"ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" \
"MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" \
"Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" \
"AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" \
"uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" \
"wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" \
"X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" \
"PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" \
"KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" \
"-----END CERTIFICATE-----\n";
*/

Is there any easy way to find the SSL certificate of any website which uses Https instead of simple http ?
Thanks in advance

in chrome:

press [F12]
click the "Security" tab
click the "View Certificate" button under "Security overview"
click the "details" tab on the "Certificate" popup
click the "Copy to File..." button
click the "Next" button
check the "base64 encoded x509" option
click the "Next" button
click the "Browse" button and choose a folder for the export
enter a file name in the provided space
click the "Next" button
click the "Finish" button
browse to the folder and open the export using a text editor

The export file has the same format, you just need to convert to a C literal usiing end-of-line slashes and quotes, an exercise i'll let you handle. There might be some fancy tool that does all this for you, I'd love to hear about one, but I know this is a fairly universal way to get it done.

Using e.g., openssl is possible. The command could go like this from the shell:
openssl s_client -showcerts -servername www.theserver.io -connect www.theserver.io:443 -certform DER
Including >mycertif.der at the end of the command, you get the information in a file so you can cut-paste that part of the command output.
Best,

Even if it's an old question... I suggest not rely on methods describe here. Of course you can get the SSL certificate from the browser and copy-paste it into your code. But each time the server will renews the certificate, the key change!
If you have a "free" certificate, like the one from Let's Encrypt, used for example in all the shared hosting of all major web hosting companies, the key will change every... 3 months! So you'll have to update your ESP code each 3 months... For testing purpose, that's OK but for real "application" it's not a good option.
So,how can we do?

Option 1: add a module on your web server, allowing to have a pre-defined SSL key. You just set the key for a specific folder and copy it to your ESP. My server is an Apache one and it seems this modules don't exist for Apache.

Options 2: edit your Apache conf (commonly at etc/apache2/) for your serveur. In many cases, each time a customer access your server with http, Apache will change the call to https.
This is made with a rewrite rule. You can change this like that:
  RewriteCond %{HTTPS} off
  RewriteCond %{THE_REQUEST} !/XXXXXX [NC]
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  RewriteCond %{HTTPS} on
  RewriteCond %{THE_REQUEST} /XXXXXX [NC]
  RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

where XXXX is the name fo the folder in which you will put the script called by your ESP. With that all folder on your site are using https except the one you use with your ESP. Of course this mean your ESP call is done using http and not https but in many cases we have to use ESP+https not for real security reason but because the web site is in https.


text:
Where to use "static volatile bool"?
Why in the piece of code below we use "static volatile bool"?
static volatile bool wifi_connected = false;

taken from here: https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiIPv6/WiFiIPv6.ino

You could easily answer this question yourself with a little research. Maybe a good book, to start: The Definitive C Book Guide and List

The use of "static" confused me because I thought that static is a variable that remains in memory while the program is running. Thank you for the list of books!

There is a lot about C that is confusing, which is why I recommend a good book or article. A quick search found these examples: Static_(keyword) or C Static Variables and Static Functions Explained with Examples

static means that the global will only be accessible inside the current translation unit.
volatile means that while(!wifi_connected){/*...*/} cannot be optimized to if(!wifi_connected)while(true){/*...*/}
These things are orthogonal. So you would use static volatile when you need both properties.

as a C noob, i only see volatile used in interrupt routines.

@dandavis volatile is a hint to the compiler that the variable may be changed in another thread or an interrupt routine. This is to tell the optimizer not to get rid of loading the variable from memory each time we check the status.

@zeta-band: makes sense, thanks for the insight.

In your volatile case - would the compiler also include a jump out of the loop if wifi_connected were changed? If not - how would it handle exiting the loop in the (eventual) case that the variable changes?

@BrydonGibson variables are only checked when you tell them to be checked so the compiler will not introduce a break into the middle of the while body that you didn't put there. The while acts just like a normal while.

I understand. In the given example however, the while loop will run forever even if wifi_connected is changed inside. I guess the compiler wouldn't make that optimization in that scenario


text:
Xbee AT Commands failing. Something wrong with Serial? Tx commands working fine
The Xbee API library is working fine for TxRequests on my Arduino, but AT commands are failing every time. I've been at this for three days.
It seems that there is some sort of conflict happening with my hardware serial port, because if I try to repeat the command a second time (after a 3sec delay), I see that the 2nd transmission (which should trigger the "D_in" light on my Xbee shield to flash) never gets sent. Then if I try to load and execute the sketch again (this shield on the nano allows me to do so with the Xbee still plugged in), I get an avrdude error suggesting that my arduino serial is busy. My PC should be out of the picture here, since I have no Serial.print() functions and the cable is plugged into a wall adapter with power only.
Basically I get no response and the parameter I'm trying to change remains unchanged. I'm at a total loss for why this is not working. Heres my code:
#include <XBee.h>

XBee xbee = XBee();

uint8_t D3[] = { 'D', '3' };
uint8_t high[] = { 0x05 };/////for DI03 pin parameter
uint8_t low[] = { 0x04};////for DI03 pin parameter

AtCommandRequest AtRequest = AtCommandRequest();
AtCommandResponse atResponse = AtCommandResponse();

void setup()
{
    Serial.begin(9600);
    xbee.setSerial(Serial);
    delay(10000);

    AtRequest.setCommand(D3);
    AtRequest.setCommandValue(low);
    AtRequest.setCommandValueLength(sizeof(low));
    xbee.send(AtRequest);

    delay(3000);

    AtRequest.setCommand(D3);
    AtRequest.setCommandValue(low);
    AtRequest.setCommandValueLength(sizeof(low));
    xbee.send(AtRequest);

}

void loop()
{

}

And in addition, here's the code for the Tx example that works just fine:
/**
* Copyright (c) 2009 Andrew Rapp. All rights reserved.
*
* This file is part of XBee-Arduino.
*
* XBee-Arduino is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* XBee-Arduino is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBee-Arduino.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <XBee.h>

/*
This example is for Series 1 XBee
Sends a TX16 or TX64 request and checks the status response for success
Note: In my testing it took about 15 seconds for the XBee to start reporting success, so I've added a startup delay
*/

XBee xbee = XBee();

unsigned long start = millis();

// allocate two bytes for to hold a 10-bit analog reading
uint8_t payload[5] = { 0x41, 0x42, 0x43, 0x44, 0x45 };

// with Series 1 you can use either 16-bit or 64-bit addressing

// 16-bit addressing: Enter address of remote XBee, typically the coordinator
Tx16Request tx = Tx16Request(0x03, payload, sizeof(payload));

// 64-bit addressing: This is the SH + SL address of remote XBee
//XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x4105B41E);
// unless you have MY on the receiving radio set to FFFF, this will be received as a RX16 packet
//Tx64Request tx = Tx64Request(addr64, payload, sizeof(payload));

TxStatusResponse txStatus = TxStatusResponse();

int statusLed = 11;
int errorLed = 12;

void flashLed(int pin, int times, int wait) {

    for (int i = 0; i < times; i++) {
        digitalWrite(pin, HIGH);
        delay(wait);
        digitalWrite(pin, LOW);

        if (i + 1 < times) {
            delay(wait);
        }
    }
}

void setup() {
    pinMode(statusLed, OUTPUT);
    pinMode(errorLed, OUTPUT);
    Serial.begin(9600);
    xbee.setSerial(Serial);
}

void loop() {

    // start transmitting after a startup delay.  Note: this will rollover to 0 eventually so not best way to handle
    if (millis() - start > 10000) {

        xbee.send(tx);

        // flash TX indicator
        flashLed(statusLed, 1, 100);
    }

    // after sending a tx request, we expect a status response
    // wait up to 5 seconds for the status response
    if (xbee.readPacket(5000)) {
        // got a response!

        // should be a znet tx status
        if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) {
            xbee.getResponse().getTxStatusResponse(txStatus);

            // get the delivery status, the fifth byte
            if (txStatus.getStatus() == SUCCESS) {
                // success.  time to celebrate
                flashLed(statusLed, 5, 50);
            }
            else {
                // the remote XBee did not receive our packet. is it powered on?
                flashLed(errorLed, 3, 500);
            }
        }
    }
    else if (xbee.getResponse().isError()) {
        //nss.print("Error reading packet.  Error code: ");
        //nss.println(xbee.getResponse().getErrorCode());
        // or flash error led
    }
    else {
        // local XBee did not provide a timely TX Status Response.  Radio is not configured properly or connected
        flashLed(errorLed, 2, 50);
    }

    delay(1000);

}

So it turns out that it was working the whole time. The problem was that that the values were not being written to the xbee, only changed. Hence, hen I would check the radio in XCTU, the values would have reverted to previous. I had no idea I needed to be calling a "write" function to save the parameters to the radio.

Just a thought from a point of ignorance.. When I use serial comm, I always use an interrupt watching loop.  When data hits UART, a data available pin throws an interrupt that causes the loop to read the input register.

That doesn't really have anything to do with Xbee AT commands, but I do like that idea for the rest of my project.


text:
DS18B20 setting resolution without addressing
As i understand the dallas library, there are two ways of referencing the sensor, one is to refer to the address, and the other is just to grab it as it is indexed.(gettempbyindex)
I want to know how to set the resolution of the sensor when i'm using the gettempbyindex method, all the examples i can find seem to only set resolution when specifying the address explicitly..
Is it even possible?

You can use getAddress: bool DallasTemperature::getAddress(uint8_t* deviceAddress, uint8_t index)
If you want to set the resolution for all devices, you can just use void DallasTemperature::setResolution(uint8_t newResolution). (It will call getAddress for all indices.)

Thanks for the reply, i couldn't figure out how to implement what you suggested, but your suggestion led me to what seems like a good solution to my problem.
sensors.setResolution(10);  seemed to do the trick, with "sensors" being whatever was initially declared to the dallas library in setup...

Take a look at the implementation of setResolution to see how to use getAddress.


text:
How can i build mouseless technology with arduino?
I want to build mouseless technology with arduino as shown in this link
Can anyone tell me how to approach this with arduino? Or what can be the logic behind it?

Your question is far far far too broad. No one is going to come here, post all the electrical schematics you need, all the code you need, and walk you through step by step. That's not how this works. The stack exchange requires that the poster make some effort to make progress in thier project before posting specific problems they are having.
That being said I will say that what you want to achieve is not possible on only an arduino. The method you posted in the video requires a lot of image processing to track the blobs. This is not something a microcontroller such as the arduino can achieve. A more powerful Intel based device may have some potential for your project but I doubt it.
I once did image processing with the raspberry pi. The pi itself is still not powerful enough to perform real time image processing to a good level, however it's a possibility that it could work (my image processing was more complicated than processing a binary image and tracking dots).
The ideal solution for you would be to do exactly what this guy has done. Build an application on a laptop or desktop computer which has enough power for the image processing. I suggest taking this route first even if downscaling to a raspberry pi is possible in the future, it will introduce you to image processing, and at least you know that it CAN work, as there is a working example.
Look up OpenCV if you havnt already, download, build it, follow tutorials and start from there! Then I think you should aim to build an application that tracks white objects in the frame. And that would be your first step to completion.

Thanks C.W.G for explanation,
I will definitely try OpenCV as you suggested.


text:
Is it possible for Arduino firmware to recognise only one computer?
Is it possible to adjust the Arduino firmware to recognise only one PC computer? On other computers it would show driver not recognised or driver not found.
E.g.: My computer should see the Arduino normally, and it should not work if I connect the same arduino to other computers.

No.
However, it is possible to place unusual and/or secret requirements on the computer's drivers or application software - however those software components could be present on multiple computers unless you also take measures to node lock them.

You could customize the USB VID/PID and descriptors, causing the device not to be recognized by a usual driver
You could alter the behavior of the USB interface (or bootloader and sketch) to require unusual operations - either obscure, or even secret to the level of unique-per-unit cryptography
Or most simply, you could just use a board without a USB interface and bring your own.  Especially if you lock the flash, there's not a whole lot others can do except entirely erase your work and be left with an unusually expensive ATmega evaluation board.

Do note also that most operating systems make it possible to easily intercept the raw USB traffic going to/from devices, so someone who can see it in operation can learn a lot about how it is working.
If you want to play games with odd USB implementations, you'll probably do better with a direct USB board like a Leonardo - and you will certainly want to have an ISP setup to recover it, as your efforts will no doubt break it many times before you get something on there which works as intended.

Thanks for nice answer. I will try first solution, if not suceed, i will use simplest solution - third.


text:
just a silly doubt about glowing an LED
what will happen if i insert the anode of a LED to pin 12 and cathode of the LED to pin 11 and set pin 12 to high and pin 11 to low,will the led glow??

You need a resistor to limit the current.

This will answer all your questions: https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/

What will happen is you will damage your LED and/or your Arduino since you haven't mentioned a current-limiting resistor (220 ohms could well be suitable).
However the general concept is perfectly sound. You could, for example, have two LEDs, wired in opposite directions. By bringing one pin LOW and the other HIGH, one LED would light up, and by reversing the output to the pins the other LED would light up. If both pins were either HIGH or LOW then neither LED would light up, as there would be no voltage difference between the leads.
There is a calculator for LED resistors.

Yes it will, try it. This is one of the way to use a LED as a light sensor and light source by connecting it to two different Digital pins.
Ref.: https://playground.arduino.cc/Learning/LEDSensor


text:
Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega to control speed of a 4-wire cpu fan
This question is not same as the other one and this is more about employing the pwm signal to drive a CPU fan;
I am trying to follow the answer by Edgar Bonet on the question Need help to set PWM frequency to 25kHz and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4 and use this pwm signal to control the speed of a 4-wire cpu fan(with black, yellow, green and blue wires);
Following is my updated code for generating the pwm signal on timer 4
void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;
    TCCR4A = _BV(COM4C1)  // non-inverted PWM on ch. C
          | _BV(WGM41);  // mode 10: phase correct PWM, TOP = ICR4
    TCCR4B = _BV(WGM43)
         | _BV(CS40);   // prescaler = 1
    ICR4   = 320;      // TOP = 320

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    analogWrite25k(10);
    for (;;) ;  // infinite loop
}

I have connected pin 8 on the mega to the pwm input on the fan(blue wire) but I dont see any variation in fan speed and fan seems to run at full speed;
I dont really have any means or tools to verify if its really generating a 25khz pwm signal but fan speed is not changing or if its not generating a 25khz pwm signal because of which there is no change in the speed of fan;
I am stuck at this point and any help on this would he highly appreciated;

can you fan accepts such a high frequency PWM signal?

yes, its a cpu fan used for intel cpus and the fan datasheet says the signal needs to be ideally 25KHz

you should be able to measure duty cycle with a DMM or even an LED; if it's getting adjusted, it would imply operation...

i dont have a DMM, how can it be measured with an LED? and the fan speed should be noticeable ideally since I tried values as low as 5 and 10 for duty cycle and I dont see any variation in fan speed;

the LED gets dimmer at low duty-cycle values. make sure to (dramatically) limit current when testing.

okay, thats a bit difficult at the moment since I dont have an LED handy :-(

I just added some code to read the RPM of the fan using the green wire which is the sense/tach wire and the RPM does not seem to go low for lower duty cycles;

Also, I see that the PWM signal is being generated at 25KHz on pin 8; I verified it by reading the pwm output from pin 8 on pin 9 as if it were coming from the the fan and the code at http://elimelecsarduinoprojects.blogspot.in/2013/06/measure-rpms-arduino.html helps print the frequency in hertz and it looks like approximately 25KHz;

Let us continue this discussion in chat.

I've just tested your setting with older "Alpine 64 GT" CPU Fan and it works as expected. I've just added parsing integers sent from serial monitor, so I don't have to change code anymore.
void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;

    // Mode 10: phase correct PWM with ICR4 as Top (= F_CPU/2/25000)
    // OC4C as Non-Inverted PWM output
    ICR4   = (F_CPU/25000)/2;
    OCR4C  = ICR4/2;                    // default: about 50:50
    TCCR4A = _BV(COM4C1) | _BV(WGM41);
    TCCR4B = _BV(WGM43) | _BV(CS40);

    Serial.begin(115200);

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    int w = Serial.parseInt();
    if (w>0) {
      analogWrite25k(w);
      Serial.println(w);
    }
}

you have connected the pwm line of fan directly to pin 8 of mega right? or is there any additional circuitry?

https://www.amazon.in/Terabyte-CPU-Cooler-intel-LGA775/dp/B01BDOI9KE/ref=cm_cd_al_qh_dp_i thats the fan I have; could it be that the fan has 4 wires but is not a pwm fan??? these fans are used as CPU fans so I thought they must definitely respond to pwm; any thoughts?


text:
Reading FAN tachometer/RPM on 4 wire fan using arduino
I am following the wiring and code at https://playground.arduino.cc/Main/ReadingRPM but using pin 9 to read the speed instead of pin 2 and I have added a 10K pull up resistor between pin 9 and +5V as well; I dont see any interrupts firing even though the fan is running;
The fan is a standard intel cpu fan with 4 wires(black, yellow, green, blue) and the green wire is the sense/tach wire and I have connected it to pin 9 as well;
Need some help or expert advise; I am not sure if the approach works fine or not;

There are no interrupts on pin 9 (unless you are using Pin Change interrupts...?). You have to use pin 2 (interrupt 0), or pin 3 (interrupt 1) (also, on the Mega: 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2)).

I am using arduino mega and using the digitalPinToInterrupt(9) when passing the value to attach/detach interrupt calls; not sure if thats same as what you meant;

RTFM: External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2). These pins can be configured to trigger an interrupt on a low level, a rising or falling edge, or a change in level. See the attachInterrupt() function for details.

Thanks; I am using pin 19 now since other pins are occupied and the code seems to read and print RPM values;


text:
How to get elapsed seconds since Jan 1, 1970?
I am building a time-critical system using Arduino. Is there any way to get the elapsed seconds like time.h of C in Arduino? I tried time(NULL) but it returns 0. Then moved forward to use now() in Time.h. But the result persists.
How can I get the elapsed seconds since Jan 1, 1970 until now?

https://arduino.stackexchange.com/questions/38765/convert-to-and-from-unix-timestamp

The accepted answer is not the only (nor best) answer. It depends what you have in hand.
The Time library will allow your arduino to keep the current time, it just need to be set the time periodically (because of clock shifting issues)
There are several ways you can get the current time:

Use a GPS module
Get time from NTP server if you have network access to one, using an Ethernet shield or may be wifi
Use a custom Serial interface
Use a GSM service
Use a RTC module, may be the most popular and standalone, like the DS3231. However these kind of module will also require some adjustment in the long term, and they require a backup battery (often a coin like CR2032) to keep time when module is not externally powered.
Use a few push buttons and LCD to have the user manually input it.
Use a light sensor to see when it is the brightest time of the day and using azimuth calculation determine the hour of the day (ok, I might be going to far here, but consider a solar powered device in the middle of nowhere)

I sorted them in the order I would choose it if I have several options available.
Those are a few ways that come to my mind

Brilliant answer. Thanks a lot for enumerating every possible options.

@GLM - generic and broad answers do not help anyone and will only confuse other people looking at the post and answers; using an RTC module is the most standard way of doing it since RTC modules are cheaper and easier to connect and program than spending a lot of time and money on any of the other mentioned alternatives; Answer to the point is the key rather than having a broad array of options; All the best in your journeys;

An arduino does not have a real time clock (RTC) built in. Every time it restarts it will reset the millis counter.
You will need to add a RTC peripheral that you can poll to find the current date and time.

You must use an RTC module like DS3231 or DS1307 for such purposes and there are good libraries available for these modules;
Unlike the standard return value of milli seconds elapsed since Jan 1 1970 00:00 on a computer, the millis() function on arduino just returns the number of milliseconds since the board began running the current program and this number will overflow (go back to zero), after approximately 50 days as per the official documentation at https://www.arduino.cc/en/Reference/Millis
While millis() can be used for very basic time controlled operations, its not really reliable to be used for time critical operations;

“[millis()] is not really reliable to be used for time critical operations”. This sweeping statement should be better qualified. millis() can be fine for time-critical applications. It all depends on the specific timing requirements of your application (resolution, jitter, long-term/short term accuracy, ...).

The reason I said its not reliable for time critical operations is because an arduino can reset for various reasons including but not limited to inefficient SRAM usage which is a common mistake done by most newbies;

Thanks a lot for your detailed answer. It really helped.

There is an 1307 RTC module emulator for Arduino: DS1307Emulator.
You can set this emulator running and save seconds to struct tm *timeStructure and afterwards converting the structure to a time_t variable using time.h functions
DS1307Emulator.init(13);
DS1307Emulator.bufferUserData();
DS1307Emulator.writeToRTC(0x00); // set address 0
DS1307Emulator.writeToRTC(0x00); // start the RTC issuing the clock run command at address 0
DS1307Emulator.setUserData();

Adresses are as follows:

0x00 - seconds
0x01 - minutes
0x02 - hours

If you want to use weekdays, date, year etc. refer to the DS1307 datasheet or check examples on the link I provided.
For reading seconds:
DS1307Emulator.bufferUserData();
DS1307Emulator.writeToRTC(0x00);
temp = DS1307Emulator.readUserData();

temp now holds seconds in binary format, you may want to convert them to dec.
Check out examples in the link I gave for full operation.


text:
Use ESP-01 with Arduino Uno/Nano, with the ESP8266WiFi library
There is this library - https://github.com/esp8266/Arduino
That provides a more user-friendly API for WiFi capabilities with the ESP8266.
However, all tutorials that I found so far for this library show how to program the ESP8266 (usually 12) directly. That is not what I'm looking for.
My current setup is having an Arduino Uno/Nano where the ESP8266 is connected to, say, GPIO8 and GPIO9 (RX, TX) and I use SoftwareSerial to communicate with it with AT commands. So I want to keep all the logic in my Arduino, but use ESP-01 only to provide WiFi capabilities to my Arduino.
However in that library I don't see the option to set the serial port pins (RX and TX) so I'm not sure if that's even possible.
In short - I want to use this library, but not program the ESP directly. Also, I'm using an ESP-01 and not 12.
Thanks.

i strongly encourage you to investigate directly programming the ESP and forgetting the AVR;

If you use serial to talk to the ESP then you are adding a load to the Arduino and ESP you don't need to add.  You are going to constrain the data link to ~9600, because this sort of hook up doesn't seem to work above that with software serial.  Finally you a going to use a ESP, with a clock speed of at least 80MHz, as a slave to an Arduino with a max clock speed of 32MHz.  You can program the ESP with the Arduino IDE, using the same language.  Look at using the Arduino as a port expander to the ESP communication over I2C.

You cannot use that "library". Simply because that isn't a library, that is a core. It's the entirety of the Arduino API designed to run on an ESP8266.
You can use it to program the ESP8266 directly and nothing else. No part of that has anything at all to do with Arduino boards like the Uno.

+1 for the above answer as well since it clarifies the point that the stuff you have mentioned is not a library and is a core;

You can infact connect ESP as a serial device to the arduino and use AT commands supported by the ESP to interact with it and achieve what you want;
For ESP-01 read the detail on http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/
Please read the following instructable which has detailed explanation on how to connect ESP12 also if interested;
http://www.instructables.com/id/ESP-12E-ESP8266-With-Arduino-Uno-Getting-Connected/


text:
Sim800l gsm module cannot connect gprs data
I am a rookie to arduino. I am trying to access MQTT server using Sim800l coreboard GSM module with Adafruit Fona/Tinygsm library but failed.So I decided to check http GET/POST request with AT command first.In AT commands all the basic commands following www.exploreembedded.com/wiki/Setting_up_GPRS_with_SIM800L  works fine  but whenever I make a GET request by "AT+CIPSTART=" module restart itself.I also tried seeduino library GPRS_HTTP example, it gives me "error:CIPSTART" and restarts module.Though this code worked one time only,this is the code
#include <gprs.h>
#include <SoftwareSerial.h>

char http_cmd[] = "GET /media/uploads/mbed_official/hello.txt
HTTP/1.0\r\n\r\n";
char buffer[512];

GPRS gprs;

void setup() {
Serial.begin(9600);
while(!Serial);
Serial.println("GPRS - HTTP Connection Test...");
gprs.preInit();
while(0 != gprs.init()) {
 delay(1000);
 Serial.println("init error");
}
while(!gprs.join("gpinternet")) {  //change "cmnet" to your own APN
  Serial.println("gprs join network error");
  delay(2000);
}
// successful DHCP
Serial.print("IP Address is ");
Serial.println(gprs.getIPAddress());

Serial.println("Init success, start to connect mbed.org...");

if(0 == gprs.connectTCP("mbed.org", 80)) {
  Serial.println("connect mbed.org success");
}else{
  Serial.println("connect error");
  while(1);
}

Serial.println("waiting to fetch...");
if(0 == gprs.sendTCPData(http_cmd))
{
gprs.serialDebug();
}

//  gprs.closeTCP();
//  gprs.shutTCP();
//  Serial.println("close");
}

void loop() {

}

also tried this commands and module got restarted after AT+HTTPACTION=0 this last command

module power and sim configure are fine as far I know,please help me find out what am I doing wrong?Sorry for making this long.please ask me if I couldn't make the question clear.TIA

How exactly are you powering the SIM800?

I have connected a buck booster with arduino 5V pin and got 4V for SIM800l as it works between 3.6-4.2 . also while using AT+CIICR or
AT+SAPBR =1,1 command, module blinks continuously  until making a GET request I don't know if it is normal or not  and then restarts.

it can make calls ,send text ,shows network status. doesn't  restart then.

I get it now , a stable power source is the answer. arduino with usb can give right amount of Volts but it lacks stable power(amps i guess) while making a TCP connection, that's why module keep restarting.Although it works fine with call, text etc. powering arduino with an AC adapter solves my problem ,now it can connect to mqtt too.Thanks


text:
Adafruit Feather 32u4 Bluefruit LE and HC-05 Bluetooth module
Is it possible to connect an Adafruit Feather 32u4 Bluefruit LE with an HC-05 Bluetooth module?
I am making a heart rate monitor using an Adafruit Feather, but it is unable to send the data to LABView for processing as it uses BLE. I do not have the means to buy a Bluetooth dongle to work around the issue.
However, I do have an HC-05 Bluetooth module that can be read by VISA on LABView.
Therefore I would like to ask if it is possible to connect my Adafruit Feather to my HC-05 module and send the data through the HC-05 instead of the built-in BLE.
Thank you!

HC-05 does not support BLE as far as I know but you can use a HM-10 if you can get your hands on one; Its almost about the same cost as a HC-05, maybe a little more;

I understand that HC-05 does not support BLE. To clarify, is it possible for me to hook up the Adafruit to the HC-05 to connect to my laptop via classic Bluetooth? Thanks!

You should be definitely able to do that for one simple reason that hc-05 can be connected to any microcontroller board over simple serial communication; I dont have an adafruit feather handy but I have connected hc-05 to a variety of boards including but not limited to the arduinos, esps and stms;