text:
Need lot GPIO pins on arduino mega - what are restrictions?
I would like to use as much as possible GPIO pins on Arduino Mega especially with (mis)using pinMode(x,INPUT); and pinMode(x,INPUT_PULLUP); to achieve two things at the same time - drive something else by the pin weakly down or up and measure the logical level there with digitalRead(x) to detemine, if that "something else" is input, or outputting some logical level.
Also I need I2C, Serial over USB and nothing else.
On Arduino UNO/nano/micro/pro it works just fine for Digital pins (except D0/D1 (RX/TX), D13 (LED as strong pull-down), A4/A5 (I2C) and A6/A7 which are not digital IO). The problem is limited number of pins, so I bought ArduinoMega.
The question is - which pins can be used that way there?
So far I am aware of D0/D1 (RX/TX), D20/D21 (I2C) and D13 (LED).
The rest (D2-D12, D14-D19, D22-D52 and A0-A15) seem aviable and usable.
Or I am missing something else?
Are there some libraries/objects I should disable to not interfere with my script?
Thank you.

"D13 (LED as strong pull-down)," You are misinformed there. D13 is also connected to the input of a comparator (LM358) which then drives the LED. The LED does not present a strong pulldown.  If you are not using I2C or SPI, those pins are also available.

I looked at it, but it depends on version, https://store.arduino.cc/arduino-uno-smd-rev3 shows still connection of direct led+resistor on D13, https://store.arduino.cc/arduino-uno-rev3 have comparator, my old UNO (with DIP) also have resistor+LED, Nano also have LED+resistor and no comparator. So only some revisions of some types have the comparator at all.

My last project had problems just for this reason and I was forced to rearrange the pin usage to avoid D13 for this very reason (unconnected D13 with INPUT_PULLUP had show  like 1.3V on voltmeter, while all others show over 4.5V ), so it is not just matter of some PDF, but real physical units proves that too.

All those pins should be available. But if you want to use Pin change interrupts, you have to check which pins are usable.

No more than 2 pin interrupts and it is not so much needed anyway (just reading buttons, digitalRead can work just as well, as there is a lot of points, where I can check regulary)


text:
Arduino Uno with data logging shield has a problem switching power sources
I have the basic Adafruit "Light & Temperature data logger Tutorial kit" made, and it works well when connected to a PC, but when I unplug the PC USB connection and hook it up to another power source, it will not launch and run by itself. I have reset both the logger and Arduino board reset buttons, but it does not seem to start recording data to a new file. One of my power sources was a Solar panel / Solar Lithium Battery charger  (with the "Power Boost 500 basic 5V boost board, and an another alternate power source was a 6 x AA battery holder with a barrel jack connector. What am I missing here? I'm a newbie! Thanks.

what have you done to troubleshoot the problem?

Can you measure the right voltage at your power inputs? (9V at the barrel Jack vor 5V directly tied to the 5V-pin of the arduino)

I checked and changed to new AA batteries, and obtained 9V on the battery pack jack, and checked and obtained the 5V pin on the arduino also. The serial monitor will start showing data for a while on its own. When I come back and refresh the PC, it starts up again. I noticed that it had 6 readings initially, and then continued with reading number 20, 21, etc. The SD disk file however, did not show any additional of the missing readings!  I may have a program code issue (maybe?). (To "chrism" , and "jstotola").

My troubleshooting so far leads me to the likely issue of enough alternative power, and possibly the sketch feature that has to do with the "sync_interval" time before a number of readings is written to the disk. I had not appreciated this feature, and may have pulled out the SD to see what was recorded and lost a good number of readings.....AFAIK.

source: Stack Exchange

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

sort: votes


text:
Looking for a sensor that measures heart/pulse rate
I am looking for a sensor which is able to measure heart/pulse rate. Apart from the common pulse sensor from here, are there any others?
I have seen people recommending this as well, and it seems more accurate. Should I get the piezo vibration sensor or are there better sensors? Hoping for something that is easy to use (Like the pulse sensor where you can just place your finger onto the sensor)
Cross-post from: https://www.reddit.com/r/arduino/comments/8f051k/looking_for_a_sensor_which_measures_heartpulse/ and https://forum.arduino.cc/index.php?topic=543857.0

sensor which is able to measure heart/pulse rate means that the sensor calculates the pulse rate and outputs the final value to the microcontroller ............. are you sure that is what you actually want?  .... or do you want a sensor that detects a heartbeat?

@jsotola yeah detects heartbeat. Sorry about that.

The commonly used approach is to use an infrared source and sensor pressed against the skin.  Usually the finger tip is all that is needed. In addition to pulse, many have also incorporated an Oxygen measurement feature.
The 1st sensor you linked to appears to use this approach.  But instead of buying a ready made sensor, many have made a project of building their own...
This project has been done and published many times on the Internet.  There are well documented projects such as this one from Rutgeurs.  As well as this complex one from a journal called EDN.  And this one and this one from various independent hackers.

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


text:
How do I merge two programs in Arduino?
So I have an esp8266 nodemcu which I flashed a program called Deauther 2.0. I spent the past two hours trying to merge another Sketch. Which I failed miserably.
What I am trying to achieve:
When I first power up my nodemcu it should load the Deauther program. But when I press the built in flash button it should load the second sketch.
What I have tried to fix the problem:

Add my own clock.cpp to the Deauther sketch and edited the top part of the sketch:
const int button = 0;

int temp = 0;

 void setup() {

 pinMode(button, INPUT)

 }

 void loop() {

 temp = digitalRead(button)

 if (temp == HIGH ) {

 // run the code below

}

Some other stuff which I don't want to mention.

Any ideas on how to fix this?
Thanks!

There's no magic way to merge two sketches. In the general case, it may be impossible. You need to understand what one sketch does and how it does it, understand what the other does and how, and write a third sketch which combines both things. Debug any problems which arise in the usual ways.

the OP is not talking about merging the two sketches. .... the OP is talking about using one sketch to load another sketch

Anyone asking a basic question like this has no legitimate use for a WiFi deauther. There are so many amazing things you can do with an ESP8266. Why do you have to chose the malicious usage?

@per1234 I am not using the deauther for malicious purposes I only test it on my own network.

To be able to merge the sketches you must ensure that both will not try to access the same pins/resource in ways that are incompatible. For example if both need to input from serial you will need to adjust things so the input you send it will reach the correct code.
Once you have made sure of that it is often simplest to first refactor both sketches to avoid any type of delay-like code or anything that halts execution while waiting for something to happen and instead go with state-machine based that just loops constantly and uses timestamps to manage when to actually do stuff.
For example the second sketch has the format:
void loop(){
    //do stuff

    delay(1000);
}

You should refactor that to
unsigned long last_run = 0;

void loop(){
    unsigned long current_millis = millis();
    if(current_millis - last_run > 1000){
        last_run = current_millis;
        //do stuff that never blocks

    }
}

Once that is complete and you made sure there is no name conflict between the sketches for the functions/globals you can simply append the loop() and setup() functions into a new loop() and setup()


text:
Sending data to Arduino Via Nodejs: Arduino does not echo back the data
I have the following sketch that runs in a arduino UNO:
/*
 * Copyright 2018 Dimitrios Desyllas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

String inputString = "";         // a String to hold incoming data
bool seralReadEnded=false;

void setup() {
  Serial.begin(19200);
  while (!Serial);
}

void loop() {
  if(seralReadEnded){
    sendDataOverSerial((byte [])inputString.c_str(),inputString.length());
    inputString="";
    seralReadEnded=false;
    delay(5000);
  }
}

String concatHex(byte value,String string){
  string+="\\x";
  if(value<16){
   string+="0";
  }
  string+=String(value,HEX);
  return string;
}

void sendDataOverSerial(byte byteArray[],size_t arrayLength){
  String returnVal="BEGIN:";
  for(int i=0;i<arrayLength;i++){
    returnVal=concatHex(byteArray[i],returnVal);
  }
  returnVal+="\n";
  Serial.println(returnVal);
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    if(inChar == 0x11){
       char inChar = (char)Serial.read();
    } else if (inChar == 0x03) {
      seralReadEnded = true;
    } else {
     inputString+=inChar;
    }
  }
 }

And I made the following Node.js software in order to read and send data over the USB to arduino:
const SerialPort = require('serialport');
const Readline = require('parser-readline');
const Ready = require('parser-ready');
const Regex = require('parser-regex');
const crypto = require('crypto')

const valueIntoHex=function(value){
  switch(value){
    case 0x11:
      return "0x11";
    case 0x03:
      return "0x03";
    case 0x02:
      return "0x02";
    default:
      return value;
  }
}

/**
* Escaping NonPrintable Ascii Characters (bytes) of a buffer data
* @param <Buffer> data The data to read
*/
const formatDataForSerialSend=function(data){
  //I allocate double the length because I assume worst case scenario that all bytes to be the ones I need to escape
  const returnBuffer =  Buffer.alloc(2*data.length);
  indexToWrite=0;
  //I use indexToWrite index because during escapes the posision that I write the byte is different from the ne I read.
  for(let i=0;i<data.length;i++){
    const byte=data.readUInt8(i);

    if(byte == 0x11 || byte == 0x03 || byte == 0x02){
      console.log("Escaped Ascii: "+valueIntoHex(byte));
      indexToWrite=returnBuffer.writeUInt8(0x11,indexToWrite);
    }
    indexToWrite=returnBuffer.writeUInt8(byte,indexToWrite);
  }
  returnBuffer.writeUInt8(0x03,indexToWrite);
  //Because I do not want uneeded size of data in my buffer
  const lastIndex=returnBuffer.lastIndexOf(0x03);
  return returnBuffer.slice(0,lastIndex+1);//I want size and not the last index. (Size=lastIndex+1)
}

/**
* Application Specific send logic
* @param <Buffer> data Data te send
*/
const sendData=function(data){
  console.log("Escaping dirty Ascii");
  data=formatDataForSerialSend(data);
  console.log("SEND DATA: "+data.toString('hex'));
  port.write(data,'binary',(err)=>{
    if(err){
      console.err("Could not send data",err);
    }
  });
}

const portName = '/dev/ttyACM0';

const port = new SerialPort(portName, {baudRate: 19200});

//Look over: https://regex101.com/r/QcBTTj/1
const hexRegex=/((\\|0)(x|X)[0-9A-Fa-f]{2})+/g;
const parser = port.pipe(new Ready({ delimiter: 'BEGIN:' })).pipe(new Readline({ delimiter: '\r\n' }));

console.log("################# SEND ####################");
sendData(Buffer.from('hello','ascii'));
console.log("############# END OF SEND #################");

parser.on('data', function(input) {
    console.log("################# RECIEVE ##################");
    console.log("Message: "+input);

    const input2=input.replace(/^BEGIN:|(\r|\n|(\\|0)(x|X))/g,"");
    console.log("Sanitized Input: ",input2);

    try{
        const data=Buffer.from(input2,'hex')
        console.log("REPRINT HEX FOR VERIFICATION: "+data.toString('hex'));
        console.log("############ END RECIEVE ##############");
    } catch(e) {
        console.error(e);
    }
});

But for some reason I managed to make it send data but the arduino does not send them back. So I want to debug it, but I do not know how I can do that I mean over arduino code how I will launch a debugger in order to do that?
How I can at the same time look and analyze the USB traffic between an application and Arduino in order to determine the logic bug?
Also I could not distinguish why arduino does not echo back some data, if I use this code for this sketch, the node.js application reads the data fine:
/*
 * Copyright 2018 Dimitrios Desyllas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

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

void loop() {
  byte byteArray[]={1,10,255,3,4,2,1,55};
  for(int i=0;i<sizeof(byteArray);i++){
    Serial.print("\\x");
    if(byteArray[i]<16){Serial.print(0);}
    Serial.print(byteArray[i],HEX);
  }
  Serial.println("\n");
  delay(3000);
}

Edit1
So far I modified the sketch into this:
String inputString = "";         // a String to hold incoming data
bool seralReadEnded=false;

void setup() {
  Serial.begin(19200);
  while (!Serial);
}

void loop() {
  if(seralReadEnded){
    sendDataOverSerial((byte [])inputString.c_str(),inputString.length());
    inputString="";
    seralReadEnded=false;
  }
}

String concatHex(byte value,String string){
  string+="\\x";
  if(value<16){
   string+="0";
  }
  string+=String(value,HEX);
  return string;
}

void sendDataOverSerial(byte byteArray[],size_t arrayLength){
  String returnVal="BEGIN:";
  for(int i=0;i<arrayLength;i++){
    returnVal=concatHex(byteArray[i],returnVal);
  }
  returnVal+="\n";
  Serial.println(returnVal);
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    if(inChar == 0x11){
       char inChar = (char)Serial.read();
    } else if (inChar == 0x03) {
      seralReadEnded = true;
    } else {
     inputString+=inChar;
    }
  }
 }

And I tested it by running over my GNU/Linux terminal like that:
screen /dev/ttyACM0 19200

I typed some stuff and by pressing CTRL+C keyboard combination I managed to get them back (Somehow gives a character 0x03 that is the ETX ascii character that in my case indicated the data stream).
But How I get some random binary escape them with 0x11 charactes and send into arduino via bash, as fas ad I know is that on GNU/Linux systems I can use the /dev/random for generating data?

Do not use delay(). 2. Do not use String objects, as they are not memory friendly. Use plain byte arrays instead. 3. Do not use Node.js for testing your sketch. Use the serial console or a serial terminal emulator (e.g., putty), then add the Node part once you know your sketch runs fine.

Don't use 0x11 (DC1) as an escape, as the Linux terminal driver interprets it as a “start” (Xon). You may use 0x10 (DLE), which you can type at the keyboard as Control-P. Also, your handling of the escape is flawed: you do a Serial.read() which will most often return -1 (meaning: no character available), and you don't use the result.

There are too many String copies in your code. This is asking for
trouble, as it can lead to memory fragmentation and, ultimately, to
memory exhaustion. That's why I recommended in a comment to buffer the
data in plain byte arrays.
However, it appears your Node.js script is going to do the buffering
anyway (that's what the Readline parser does). Thus there is no point
in buffering also on the Arduino, which has one million (or more) times
less memory than the computer running the Node.js code. If the Arduino
just outputs the bytes as it gets them, the program becomes very simple:
void setup()
{
    Serial.begin(19200);
    Serial.print("BEGIN:");
}

// Send a byte over the serial port, formatted in hex.
static void send_hex(uint8_t value)
{
    Serial.print("\\x");
    if (value < 16)
        Serial.print('0');
    Serial.print(value, HEX);
}

void loop()
{
    static bool escaped;  // is the next character escaped?
    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\x10' && !escaped) {  // DLE (data link escape)
            escaped = true;
        } else if (c == '\x03' && !escaped) {  // ETX (end of text)
            Serial.print("\r\nBEGIN:");
        } else {
            send_hex(c);
            escaped = false;
        }
    }
}

Note that, upon receiving an “end of text”, the program terminates the
current line (by sending "\r\n") and immediately sends the preamble for
the next one ("BEGIN:"). On the receiving side, the readline parser will
take care of delivering only complete lines.
If, for whatever reason, you do need to buffer inside the Arduino, then
remove the Serial.print("BEGIN:"); line from setup() and change the
loop as follows:
void loop()
{
    static char buffer[1024];
    static size_t pos;    // current position in buffer
    static bool escaped;  // is the next character escaped?
    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\x10' && !escaped) {  // DLE (data link escape)
            escaped = true;
        } else if (c == '\x03' && !escaped) {  // ETX (end of text)
            Serial.print("BEGIN:");
            for (size_t i = 0; i < pos; i++)
                send_hex(buffer[i]);
            Serial.println();
            pos = 0;
        } else {
            if (pos < sizeof buffer)
                buffer[pos++] = c;
            escaped = false;
        }
    }
}

Note that the buffer is sized at half the RAM of your Uno. This is safe,
as it is a very simple program that uses very little dynamic memory
(stack only, no heap) and has no risk of fragmentation. Note also that
your original program stores both the raw data and the formatted hex
(which is 4 times larger) in memory at the same time, which means your
buffering would be limited to 1/5 of the available RAM.

I splited them because I want to look on how serial I/O will be done in https://arduino.stackexchange.com/questions/52151/how-to-indicate-an-end-of-a-stream-on-usb so I wanted  them as separate functions the send and the receive

Also the problem in on Node.js Application and not over arduino,


text:
"function" was not declared in this scope (called in setup)
I have this bit of code I'm trying to execute only once. but I seem to get this error every time I try to compile: "calcOppervlakte' was not declared in this scope" when it's being called in the setup.
I've looked at code examples where calling functions like this works, and I cannot wrap my head around this problem.
google isn't really helpful either since the search for something-something not declared in this scope gets me thousands of results.
double pi = 3.14159265359;

void setup() {
  Serial.begin(9600);
  for(int r = 1; r <11; r++){
    Serial.print(calcOppervlakte(r)); <----
  }
}

void loop() {

}

double calcOpppervlakte(float radius){
  double result = pi * pow(radius, 2);
  return result;
}

The function name you're calling is calcOppervlakte but the function name in the definition is calcOpppervlakte. If you look closely you'll see there is an extra p in the function definition. If you change the names to match the error will be resolved.


text:
How to connect/call to the PSTN network using Arduino?
For a few months I made an alarm for my house, it is very simple: it is based on magnetic sensors DC-1561 (for windows and exterior doors), a few PIR sensors for rooms, buttons, LEDs and (of course) an ArduinoNano v3. Something simple!
The question is that lately I do not spend much time in my house and I would like it when I'm away from home the alarm calls me (when is activated) to my cell phone using the public switched telephone network (PSTN) because I live in Cuba and it's the easiest way and cheaper (the GSM modems/modules are very expensive for me). I do not want to leave any message or sound record, just call me and receive the call on my cell phone, using the RJ-11 connector (in my country only 2 pins are used) to connect it with the Arduino/some_IC.
I have been investigating since yesterday and have found quite a bit of information. The most recommended/successful that I found (remember that I want to continue using the system that I already have, I just want to add to the Arduino the ability to use the mark through the PSTN) is to use an IC (HT9200B) that is a generator of DTMF codes (as see in the figure) with serial AND parallel connection, aparently, compatible with the electronic logic of the Arduino (5V).

But of all the information that I found is to connect to this IC (HT9200B) a speaker and reproduce the DTMF codes. This is not what I want, what I want is to connect directly to the phone line and be able to "call" from it.
Anyone have any ideas, links, projects in progress, or anything that can help me?

You need an FXO device. The simplest of these is a MODEM.

@Majenko Anyone in particular? Have you work with one that you can recommend to me?

They are hard to find new now. You want an external MODEM (RS232 one - find one on eBay) and a UART to RS232 (e.g., MAX232 based) adaptor.

https://www.ebay.com/sch/i.html?_nkw=external+modem+rs232

Mmm... Ok, let's assume that I already buy the modem and the UART to RS232 adaptor, now: how can I use it with Arduino?

You connect the TX of the Arduino through the adaptor to the RX of the modem, and the other way around as well. Then send something like "ATDT18005553827\n" at the right baud rate. Wait 10 seconds or so, then send "\n" to cancel the call.

It's something like the SIM900, a GSM modem that work with 2g and GPRS (work flawlessly in my country), with the AT commands? Let me do some research, when I found one that I think I could use, can I consultate with you?

It's the predecessor. It uses the "Hayes" AT command set that GSM modems later on inherited.

Somethink like this one would work for me: modem ?

Sure. Looks good to me. Any one will do. They all work the same.

As already written in the comments, you may use any RS232 modem you can find. They use the so-called AT commands, which is a very common way to exchange commands with this kind of peripheral. You can check on wikipedia or on google to get more information on it.
The main problem is that this kind of modems are a bit hard to find (or at least, they are a bit harder to find and a bit too expensive for my liking). That's why, for a project of mine, I wanted to switch to a cheaper alternative. Looking on the internet, a lot of people stated that it was much better to have an already approved instrument rather than designing your own. For this reason, I bought a mini-phone like this one:

You just have to open it, wire the keys (or rather, the rows and columns of the keypad) to the arduino and let it do the magic.
This solution is cheaper (I spent 4€ for this, but if you have an old phone it becomes free) than getting a RS232 modem, but needs more work on your side.

I like your solution more. Could you give me the link where you bought the phone that you show me in the image? When I search (Amazon, eBay and Aliexpress) I get many cell phones and landlines, and I would like to buy yours, because I know it works. Thanks for the advice!

Is this one?

I bought it from ebay, but it is the same as yours. Just note that I did not complete the project, and with respect to the modem this requires you to tinker with it a bit more. On the other side you will technically be able to send also audio and receive DTMF codes


text:
Unicast image transmission using Xbee
I've been working on image transmission using XBee S2B Pro modules and Arduino Mega. Main task is to transmit a jpg image taken by a jpeg serial camera at the transmitter and send it to a microSD memory at the receiver, but I've been dealing with one unique trouble: I need a delay of 2 seconds to send and receive 1 byte successfully. If I set fewer seconds I lose information and the received image gets corrupted. Here you will see my codes:
Transmitter code:

byte ZERO = 0x00;
byte incomingbyte;
long int a=0x0000,j=0,k=0,count=0,i=0;
uint8_t MH,ML;
boolean EndFlag=0;

void SendResetCmd();
void SetBaudRateCmd();
void SetImageSizeCmd();
void SendTakePhotoCmd();
void SendReadDataCmd();
void StopTakePhotoCmd();

void setup()
{
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial1.begin(38400);
}

void loop()
{
  byte a[32];
  int ii;
  SendResetCmd();
  delay(4000);
  SendTakePhotoCmd();
  delay(1000);
  while(Serial1.available()>0)
  {
    incomingbyte=Serial1.read();
  }
  while(!EndFlag)
  {
    j=0;
    k=0;
    count=0;
    SendReadDataCmd();
    delay(20);
    while(Serial1.available()>0)
    {
      incomingbyte=Serial1.read();
      k++;
      if((k>5)&&(j<32)&&(!EndFlag))
      {
        a[j]=incomingbyte;
        if((a[j-1]==0xFF)&&(a[j]==0xD9))     //tell if the picture is finished
          EndFlag=1;
        j++;
        count++;
      }
    }
    for(j=0;j<count;j++)
    {
      Serial.write(a[j]);
      delay(2000);// observe the image through serial port
    }
    i++;
  }
  while(1);
}

void SendResetCmd()
{
  Serial1.write(0x56);
  Serial1.write(ZERO);
  Serial1.write(0x26);
  Serial1.write(ZERO);
}

void SetImageSizeCmd()
{
  Serial1.write(0x56);
  Serial1.write(ZERO);
  Serial1.write(0x31);
  Serial1.write(0x05);
  Serial1.write(0x04);
  Serial1.write(0x01);
  Serial1.write(ZERO);
  Serial1.write(0x19);
  Serial1.write(0x11);
}

void SetBaudRateCmd()
{
  Serial1.write(0x56);
  Serial1.write(ZERO);
  Serial1.write(0x24);
  Serial1.write(0x03);
  Serial1.write(0x01);
  Serial1.write(0x2A);
  Serial1.write(0xC8);
}

void SendTakePhotoCmd()
{
  Serial1.write(0x56);
  Serial1.write(ZERO);
  Serial1.write(0x36);
  Serial1.write(0x01);
  Serial1.write(ZERO);
}

void SendReadDataCmd()
{
  MH=a/0x100;
  ML=a%0x100;
  Serial1.write(0x56);
  Serial1.write(ZERO);
  Serial1.write(0x32);
  Serial1.write(0x0c);
  Serial1.write(ZERO);
  Serial1.write(0x0a);
  Serial1.write(ZERO);
  Serial1.write(ZERO);
  Serial1.write(MH);
  Serial1.write(ML);
  Serial1.write(ZERO);
  Serial1.write(ZERO);
  Serial1.write(ZERO);
  Serial1.write(0x20);
  Serial1.write(ZERO);
  Serial1.write(0x0a);
  a+=0x20;
}

void StopTakePhotoCmd()
{
  Serial1.write(0x56);
  Serial1.write(ZERO);
  Serial1.write(0x36);
  Serial1.write(0x01);
  Serial1.write(0x03);
}

Receiver code:
#include <SD.h>
#include <SPI.h>

File myFile;
int pinCS = 53; // Pin 10 on Arduino Uno

void setup()
{
  Serial.begin(9600);
  pinMode(pinCS, OUTPUT);
  if (!SD.begin()) {
    return;
  }
}

void loop() {
  byte buf[5000];
  if (Serial.available()>0)
  {
    myFile = SD.open("imgrx.jpg", FILE_WRITE);
    Serial.readBytes(buf,sizeof(buf));
    Serial.println((byte)*buf);
    myFile.write((byte)*buf);
    while(Serial.available()>0) Serial.read();
  }
  else{
    myFile.close();
  }
}

I've tried a MicroSD -> XBEE -> MicroSD also and that trouble continued there, maybe I've passed through something and I'd like to tell me where. Let me add these methods give me images identical to the ones I send, so even slowly, it's very effective. I changed baudrates without any success. Xbee adresses are connected as unicast. I also tried using only Serial.readBytes and I got Bytes faster but as decimal values and is unreadable.
I would really appreciate any information or experience approach to solve this problem. Ask me anything you don't understand about my question.

Learn how to read serial. There is never any cause to use delay().

Problem is I need to use that delay, is practically sending 1 byte and waiting 2 secs until receiver read it and it's ready to receive a new one so I send a next byte, without it I receive anything. Could you please give me a more specific reference? Thanks

Your biggest failing is assuming that when the first byte arrives the whole thing is available. That is never true - you need to have some concept of how much data is being sent, and where the end of it is. Not just make incorrect assumptions.

Ok, got it. I'll improve transmission and searching for more information. Thanks

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


text:
Arduino AES128 - CMAC
I'm looking for AES128 library with CMAC for Arduino. Help me to find one

Did you ask Professor Google?

Yes, i search in google but i don't find any library aes128 cmac with example to use it, thank you

I happen to know some libraries which use this. AES128-CMAC is for example used in the LoRaWAN MAC / driver implementation (LoRa is a low-power-wide-range radio technology). For example, the library Arduino-LMIC (LoRa MAC in C) uses this AES-CMAC implementation (has actually 2 built-in, Ideetron is the other one):

https://github.com/matthijskooijman/arduino-lmic/tree/master/src/aes

Other stacks use the mbedtls library with only the AES and CMAC layer activated. The library, written by ARM, is entirely in C and thus easily configrable (config.h) and compilable for the Arduino platform:

https://github.com/ARMmbed/mbedtls
https://github.com/ARMmbed/mbedtls/blob/development/library/cmac.c

Semetech's LoRa stack even has AES and CMAC abstracted in 4 four files:

https://github.com/arduino-org/arduino-library-lora-node-shield/tree/master/src/system/crypto

Another good point would be to search PlatformIO's library index for "AES CMAC". Then this library comes up:

https://platformio.org/lib/search?query=AES%20CMAC
https://github.com/DavyLandman/AESLib

This also offers a CMAC implementation specifically designed for the Atmel AVR MCUs (Arduino Uno and likes) and partially written in Assembler. This should be best suited for you.

https://github.com/DavyLandman/AESLib/blob/master/bcal-cmac.c

Thanks for your answer, I am already working on LoraWan device and a network server .


text:
Arduino MKR Zero problem with new UART comunication
I'm currently using an Arduino MKR Zero board and I need to add a new communication because the Serial1 on pins 13 and 14 is already used by another device.
I've followed this tutorial from Arduino official website to create a new serial communication, but using the given code I have no communication on pins 0 and 1.
The code compiles, but it doesn't work when uploaded to the MKR Zero board.
I've noted that IrqHandler() is not highlighted in my Arduino IDE (it remains black).
So, should I install some library?
Thank you.

Did you manage to resolve the issue? I also struggle to get an additional serial interface to work.

When a library does not highlight, it might be that the library is not coded to be highlighted (see here).
If you installed the library yourself, you may have put it in the wrong path.


text:
Can I use an IR distance sensor in rain?
I am planning on using 'SHARP IR Distance Sensor - GP2Y0A710K0F' in an outdoor environment. Assuming the casing I design for the sensor is waterproof, can I use this IR sensor without any trouble? If the water is interfering, what can I do to reduce that noise?
The sensor is fixed above the ground and aimed towards the ground like this.

If this is off topic, where can I ask a technical question like this, and not get rejected by people who did not even bother to answer?

According to the data sheet for this device, located at Adafruit's web site, the frequency used is 870nm. If you required specific attenuation figures, that might be useful information.
Another web site suggests that thermal IR camera imaging systems (which use a different frequency IR) are attenuated by rain. Some of the IR energy is lost by absorption and some by reflection. I was hesitant to suggest that as the answer due to the different frequencies involved.
Digikey has a document covering wide use of IR sensing. Listed in the document:
The disadvantages of IR technology are:

Line of sight: transmitters and receivers must be almost directly
aligned
Blocked by common materials: people, walls, plants, and other objects can block transmission
Short range: performance drops off with longer distances
Light and weather sensitive: direct sunlight, rain, fog, dust, and pollution can affect transmission
Speed: data rate transmission is lower than typical wired and RF transmission

Even though data transmission is not your objective, the considerations apply. A wet surface over which your sensor passes will have the signal attenuated and may also be slightly diffracted.
I found no direct reference to the magnitude of the attenuation. If your sensor is protected from water intrusion and the surface is only slightly wet, you may have minimal problems reading the distance. If the rainfall is at the level of a frog-strangler, there could be sufficient water to eliminate useful readings.
Another search resulted in a similar question on the physics stack exhange, which led to a more comprehensive answer:

There is another image on the same page, but both show that at the 870nm frequency, there is lower attenuation than much of the IR spectrum, particularly above 3000nm. The above linked document suggests that the affect of rain (water) is low at near-infrared (970-1940nm) but that's still higher than the device's 870nm figure.
For your objective, shielding the surface from rain (umbrella) or clearing the surface of standing water seems to be the best options. If those are impractical, one would have to experiment to determine how much water flow can be tolerated before the signal is lost or attenuated beyond reception limits.

Thank you very much for this comprehensive answer @fred. I will follow the guide you gave and do some experiments with rain. Never thought that the frequency had a connection with my problem. Thank you very much.

the ir-sensor senses a difference in infrared. the rain will only interfere if its way warmer then the base outside temperature. this is how humans and other mammals trigger infrared sensors on outdoor garden lamps. we emit infrared because our body temp being higher than the temperature of our surroundings.
just a nice quote from this site: https://www.techwalla.com/articles/how-do-ir-sensors-work

All objects emit light according to their temperature--this is called "black body radiation." The hotter the object, the shorter wavelength of light it emits. The Earth emits infrared light at a peak of about nine to 10 micrometers--and so do warm-blooded animals like humans. This light can be used to detect motion or warmth.

Thank you for the response @Jelle. I think you misunderstood how the SHARP IR distance sensor works. It uses it's own IR light source and captures the reflection on a surface. Black body radiation has nothing to do with it.

i see. i was expecting a standard pir sensor


text:
Controlling voltage and current from chip?
I'm well aware that this question perfectly showcases my spectacular ignorance, but oh well. It's a simple enough question, so here we go.
I have a 595 chip (SN74HC595) wired up to an Arduino, fed by the 5V output. After switching all the outputs on, I measured an output pin at 5.04V and 74mA.
I want to use the chip's outputs to switch transistors (P2N2222A) which will have 60 mA through them (switching common cathode RGB LEDs), so I believe I need to drop it down to around .6 to 1.2V at .6mA, right (I'm not at all sure I'm reading the datasheet right)?
So how exactly do I do that? It seems like I need to put a resistor in between the pin and the base, but don't I need to know the TOTAL resistance of the circuit? Or can I just calculate from the pin itself (I believe that would need 7K)?
Thanks in advance for your help, and please feel free to OVER-explain if you're so inclined.
EDIT:
EDIT 2: Resistor values are listed wrong. R1=200, R2 & R3 = 100.

74mA was your total draw (including arduino?)    I am very confused what your trying to do here.  Please provide a schematic showing what you have/ what you intend on doing.  I am fairly certain your assumptions about the 1.2V/.6mA thing is wrong, but not sure exactly what your talking about yet

Added hurriedly thrown together schematic.

You dont need the transistors or the IC to turn on those two LED's. Right now, both LED's will be the same(is that what you want) but you can just connect them to ground(remove transistors and IC) and then control their colors via the pins(6,5,4).   Also no sure why you have different value resistors for each color, the 100, and 200 ohm ones are too low. I would suggest at least 680ohm, but the 1k should be fine too

Connecting an ammeter between a pin and ground is silly. That's just like shorting the pin to ground, and will show the maximum the chip is capable of, which is usually far more than it's rated for.

@ChadG, the transistors are there so that I can expand the circuit beyond two LEDs. I realize I could simply drive two LEDs directly from the board's PWM pins, but there are only 6 of those, limiting me to two LEDs. This way I can switch them on one at a time fast enough that they appear to remain lit.
I did mess up the resistor values, but they should be 200, 100, and 100. The red part of the LED drops 2V and needs 20mA, so (5-2)/.02=150, rounding up to the nearest resistor value I have. The blue and green drop 3.2V, so (5-3.2)/.02=90, rounding up to the nearest resistor I have.

@Majenko, thanks for the information. Like I said in the question, I am spectacularly ignorant about electronics.

There should not be that much of a voltage drop on an led

why do you think that shorting an output to ground is equivalent to no load?  .... try shorting a battery, and then tell me if you still think the same thing

@jsotola because I've only been learning this stuff for about a month now. I take it from your answer it's not. So is the load then the meter? The wire? Please explain more.

You're misunderstanding what you need to drive a transistor.
A transistor will allow up to a specific amount of current through the collector depending on the current that flows through the base. If less is needed by the load then less will flow.
Think of it like a tap. If there's not much water pressure it doesn't matter how far you turn on the tap, after a certain point the flow of water won't increase any more.
To allow 60mA through the collector you need to provide at least 0.6mA (assuming a hFE of 100) through the base. That 0.6mA will set the upper limit of the current to 60mA. If you provide more than 0.6mA then you will allow a higher upper limit.
The 0.6V on the base is the voltage (difference between base and emitter when wired as "common emitter") at which current will start flowing through the base. It's the same concept as the forward voltage of an LED. For switching the voltage you put on the base must be more than 0.6V to allow current to start flowing. Since 5V is more than 0.6V you don't need to worry about it.  If you want precision in your calculations you will want to take that 0.6V into account, though.
So if you want at least 0.6mA from 5V with a 0.6V drop on the BE junction, you need:
R=V/I = (5 - 0.6) / 0.0006 = 7.3kΩ.

That's the maximum resistance you want. Anything more than that and the current through the base will limit the current through the collector to below the 60mA you want.  So you must select some resistance that is lower than that.
What value? Well, it really doesn't matter that much. The lower the value the higher the current, but at these levels the current levels you're dealing with will be minuscule anyway.
It's common to use a 1kΩ resistor in the base for a transistor when using it as a simple switch like you are.  That would give you, for each transistor:
I=V/R = (5 - 0.6) / 1000 = 4.4mA

For all 8 outputs that's a paltry 35.2mA. Far below the total the chip can provide of 70mA.
If you care about current consumption (you're running from batteries, for instance) you may want to increase to 4.7kΩ resistors to reduce the total drive current down to 7.5mA.

Thank you for such an in-depth explanation. I'm trying to make sure I've wrapped my head around this. I'll try out some of your examples tomorrow. Will putting the ammeter across the resistor give me the correct current?

Ammeters go in series with the connection, not parallel.

So in terms of calculating the voltage and current, I treat the pin as a 5V DC source?

Well, that's what it it...

Thanks again for the great explanation. Tried it out with some 2K and 5K resistors (making sure to put the meter in SERIES for current measurements this time), checking against the math, and I see what you're saying. :D

You are making the design more complicated than it needs to be.
Use a WS2803 chip, it has 18 outputs, 0-255 PWM level programmable for each output.  Got more LEDs? Use more chips.
http://da-share.com/files/datasheets/WS2803.pdf
Or use WS2812B RGB LEDs, easy to wire up in a daisychain. SMD typically, and Sparkfun carries 2 thru hole variants also.

Thanks for the tip, but I'm aware that this isn't the optimal or easy way to do this. I've actually already ordered some PWM expansion chips (TLC5940), but they haven't arrived yet, and won't for about a month.
So I'm trying to figure out how to do it with what I have on hand, and what I have on hand is a dozen or so 595s. Besides, I'm learning more this way. :D

Where did you order from? Digikey.com or Mouser.com would have had them to you in under a week in the US.

Chinese crap off ebay. I know, "boo, hiss". And I know there's a good chance of them not being authentic or good quality, but I'm just tinkering around on my kitchen table here, so...
Also, I am not in the U.S.


text:
Pro Micro recognised as Micro (win10, IDE 1.8.1)
I just got this pro-micro clone 5V and it's my first pro micro ever. After reading lots of discussions about how easy it is to brick and how it's just a smaller Leonardo, I've also found tutorials where they guide you to install custom things (sprkfun) to recognise the board, and others where it shows up as a Leonardo board.
However in my case I just plugged it in my Win10 laptop, the drivers got installed and it is automatically recognised as an Arduino Micro.
Since I haven't found people having this, and since I'd like not to brick it immediately I was wondering what's the procedure between:

follow sparkfun's guide for pro micro and install their custom
drivers
treat it as a Leonardo (in the IDE)
treat it as a standard Micro (in the IDE) since it's recognised as such

Thanks!
edit: solution: it's a Leonardo.

Treat it as what it is.
What windows sees it as is just what USB reports it as. It's just a name. It has no bearing on what it is or how you program it. Select the actual board that you have in the IDE, not what Windows says it thinks it is.
As a general rule: Ignore everything Windows ever says, it's full of sh!t.

yeah, but it is sh!t in carefully crafted layers of never ending annoyance ... lol


text:
How reliable is Arduino Uno Serial, via USB (ATmega16U2), CRC needed?
I have a question about the reliability of Serial communication, i.e. in particular if I need to implement CRC/checksum/ECC because of bit transmission errors?
I
I however think there is no general answer as there are different ways in which serial communication with the Arduino Uno's Atmega328P chip might work.

(a) The serial communication is between two Atmega328P Chips, and using rather long wires
(b) The serial communication is between two Atmega328P Chips, and using rather short wires
(c) The serial communication is between one Atmega328P and the ATmega16U2, who picks up and forwards the signals via USB protocol (e.g. to a PC)

My question is with regard to the ATmega16U2. The distance (wire/line length) on the Arduino R3 board is about 2cm/1" tops, which I expect to reduce the likeliness that a signal will become corrupted.
Assuming that the USB protocol which is further employed to transport the signal by itself provides by itself an ECC/CRC/checksums, I wonder if it is not rather superflous to implement a CRC when receving and sending messages via the serial communication in the case (c), while I however expect it to be more necessary for (b) and almost certainly necessary for (c).
Also, if this matters to respond to the question, I was wondering if the power supply (i.e. if Arduino Uno is powered by the USB provided voltage of ~4.5V or rather via an external 12V power adapter) would have an impact on the "corruptability" of the signals on the TX/RX serial lines?

UART already has parity bit in the protocol, though the Arduino doesn't use it. It might be more useful to do some kind of checksum on a higher level protocol, on top of UART.

for a crypto box project, i used thumbtacks as uart contacts. I transferred 2kb keys with CRCs at 115200.  In testing ~1200 keys, I only once had to resend once because of a CRC mismatch, and i think that was because the thumbtacks stopped touching as i plopped down into my desk setup...

If you use the appropriate buffering of the 0/5V signal over the long wires, case A, no error detection and correction is needed. RS232, RS485, your data will be just fine (can be up to thousands of feet).
Shorter wires, from Atmega device to Atmega device, I've neved had to use anything, even at 115200 speeds, case B, case C.
16U2 to PC, that will depend on the quality of the USB cable. The +/-3V differential signal (similar to RS485 levels) is quite high speed, like 4 Mbits/second, so you want a good cable with good shielding.


text:
if two arduinos are connected by I2C and one of them is using an ethernet shield, does that grant both of them access to the internet?
i have two arduino mega and they send data to each other by an I2C connection. But one of those arduinos is connected to an ethernet shield which allows it to send data to a web server. Being both connected does that mean that they both can send or access the web server. Sorry if any ambiguity was found but I didnt find a better way to ask this question.

I2C does not automatically share resources between two connected devices. You would not be able to share an Internet connection from a Mega connected via I2C to another Mega which has an Ethernet shield.
However, you could write code for both Megas that implements a two-way communication in which the non-shield Mega sends requests or commands to the one with the Shield, and then passes that data back to the non-shield Mega.
However, you, as the coder, would be responsible for designing such a protocol and implementing it. It would be quite a task probably.

Thank you my friend, this couldn't be answered better.

It can but only if the one with the shield allows it (it acts like a router).
The only way for the arduino without the shield can communicate with the internet if it can send a message to the one with the shield and it will forward that message and return the replies back.


text:
how to establish a connection between an arduino and a web server?
I want to establish a connection between my arduino mega ( which is connected to an ethernet shield so internet access is available) to a web server. Any idea how the code should be?
I searched for it but all I found was a local host connection establishment.
Thanks in advance.

None of the examples in the IDE help you?

That's the one thing i forgot to check. I'll get to it right now.

The answer of this was already existing in the arduino examples which I forgot to check at first. Thanks Majenko for making me notice.

@jsotola - actually this is an answer, as it resolves the question.  When a solution is posted as a comment, summarizing it in an answer is permitted; short of closing the question (as subsequently happened here) it's typically the only way the system can be convinced to consider the issue resolved and avoid having it bubble back up every few months to annoy everyone.


text:
Should I use a loop instead of an If statement?
I have a simple sketch that tests input from 2 touch sensors and outputs to 2 relays (if a sensor is touched, trigger the respective momentary relay).  It has been a bit quirky to say the least.  perhaps I need to adjust delays or adjust sensitivity of the touch sensors, but I feel that maybe the coding could be more efficient.  Would using a WHILE or DOWHILE loop work better than an IF statement for this?  It seems like there is a timing issue between the relay and the sensor.  When I hit the sensor, the relay triggers immediately, but then it doesn't shut off right away.  Also if both sensors are made at the same time, I am seeing only 1 relay trigger or neither.  I am trying to eliminate the code as my failure point. I have the code printing to the serial monitor to show "Sensor 1 touched" or "Sensor 2 touched", and sometimes that triggers once and sometimes it will print multiple times.
int touchPin1 = 2; //Touch sensor 1
int touchPin2 = 4; //Touch sensor 2
int val_1 = 0;
int val_2 = 0;
int relayPin1 = 8; //Relay 1
int relayPin2 = 9; //Relay 2

void setup()
{
  Serial.begin(9600);
  pinMode(touchPin1, INPUT);
  pinMode(touchPin2, INPUT);
  pinMode(relayPin1, OUTPUT);
  pinMode(relayPin2, OUTPUT);

}

void loop() {
  digitalWrite(relayPin1, LOW);
  digitalWrite(relayPin2, LOW);
  val_1 = digitalRead(touchPin1);
  val_2 = digitalRead(touchPin2);
  if(val_1 ==1)
  {
  Serial.println("Pad 1 Touched");
  digitalWrite(relayPin1, HIGH);
  }
  if(val_2 ==1)
  {
  Serial.println("Pad 2 Touched");
  digitalWrite(relayPin2, HIGH);
  }
  delay(100);
  //Serial.println();
}

Basically I am asking if there is a more efficient way to code this.
Touch Sensors: Adafruit Standalone Momentary Capacitive Touch Sensor Breakout Adafruit Part Number: 1374
Relays: SunFounder Relay Module for Arduino and Raspberry Pi 5V DC Trigger by HIGHLO (HIGH Trigger)

As we do not have a crystal ball, we cannot help you debug code we do not see.

For us to be able to help us you will have to share your code. We can't recommend one strategy over another when we don't know what it is your code is doing, or even what sensors you are using and how the code for them works.  You will have to add your code, along with a drawing of your setup (known as a schematic) or at the very least a photograph of your breadboard or whatever you're using, to your question (use the edit button under your question).

What do you want the beahviour to be? As long as the touch pad is pressed, the relay is activated, and as soon as you don't touch it anymore the relay closes? Because I don't understand why you always digitalWrite(relayPin1, LOW); in every loop iteration, and then (depending on val_1) immediately set it HIGH again.

As you stated, I would like the touch pad to activate the relay as long as the pad is touched and then off when no longer touched.  Ideally, I would like any of the relays to only be able to activate for a max of 1 second and not be able to be activated again for 1 second.

that is not what your code does ..... the loop() repeats 10 times a second because of the delay at the end .... look at your code carefully and determine what each line of your code does .... you will see that it does not do what you think it does

the delay is necessary to account for the time it takes for the relay to switch.  If there is no delay then the entire process breaks down.  If I place the delay inside the conditionals, then the relays cannot engage at the same time.  the digital write LOW command is necessary in order to make the relays momentary like the touch sensors.  Otherwise they will permanently latch to the normally open leg.  I have some electronics and programming experience, but brand new to Arduino.  Not used to having to code within the constraints of a forced active loop.

You aren't "forced" to use loop, you know. Just leave it empty if you want, and put all your code into setup. This is effectively what any other programming environment does, you have main which does what you want (possibly looping inside it, and possibly calling other functions).

What you are lacking is the else concept:

If a touch pad is pressed, then

Turn the relay on

else

Turn the relay off

Rather than turn the relay off every iteration, you only turn it off if the touch pad is not pressed.
That can be written as:
val_1 = digitalRead(touchPin1);

if(val_1 ==1)
{
  Serial.println("Pad 1 Touched");
  digitalWrite(relayPin1, HIGH);
} else {
  digitalWrite(relayPin1, LOW);
}

If you want your messages to be more meaningful and not spam, then you can remember the previous state and only do things if the state changes:
static uint8_t oldVal1 = LOW;

uint8_t val1 = digitaRead(touchPin1);

if (val1 != oldVal1) {
    oldVal1 = val1;
    if (val1 == HIGH) {
        Serial.println("Pad 1 Touched");
        digitalWrite(relayPin1, HIGH);
    } else {
        Serial.println("Pad 1 Released");
        digitalWrite(relayPin1, LOW);
    }
}


text:
3 digit 7 segment display
I have 3 digit 7 segment display with 10 pins
I found this image pinout but it not working for me I need to know the pin out of this display

How do you think you have wired it? Also, do you have the datasheet for your actual device?

What is not working? How is it connected to the arduino?

make a test tool consisting of a 1.2V battery and a 2.2k ohm resistor in series with the battery .... apply one side to pin 10 and the other side to pin 7 .... if nothing lights, reverse the wires .... if nothing lights still, try other pins ..... if no lights, lower the resistor value to 1k ohm and try again

I am also get a weired 3 digit display MK5631G3 .. find its pinout and I get this ...... check this link for circuit of the display : http://ibb.co/mvvmE8
for model of the display : http://ibb.co/hdvsnT
for pinout of the Display : http://ibb.co/b5NcMo Thank you

you are supposed to multiplex this display. Put a current limiting resistor between pins 10, 8 and 6 and the arduino and all the rest can be connected directly.
First pull pin 10 low and use pins 7,9,2,3,4,1 and 5 to set the segments of the first digit.
Then put 10 high and 8 low and again use pins 7,9,2,3,4,1 and 5 to set the segments of the second digit.
repeat with pin 6 pulled low.
You can test the display with a battery and resistor. Connect them in series and put positive on the lower left pin and negative on the upper left pin. That should light up the top left vertical segment on the left most digit. You may need to turn the display around.

I believe that the problem is that the asker has found some random datasheet on the Internet that doesn't match their device, not that they don't know how to drive it (although they may also not know how to drive it).


text:
Right PIN to activate a wireless relay with ESP8266 ESP-01
I'm trying to program an ESP8266 ESP-01 module to let it connect to my personal wifi network and activate a wireless relay that I've bought.
No problems with Wifi connection so I've omitted the code about it, my problem is to find what is the right PIN to set to LOW/HIGH to control my relay.
Setting relayPin to 1 as shown in this code works and with it I can see the embedded LED turning on and off.
const int relayPin = 1;

void setup() {
    pinMode(relayPin, OUTPUT);
}

void loop() {
    Serial.println("Close Relay for 100 ms and then Open");
    digitalWrite(relayPin, LOW);
    delay(100);
    digitalWrite(relayPin, HIGH);
    delay(200);
}

Surfing the web I've found the following diagram about the ESP8266 ESP-01 module:

I've tried to set relayPin to 0 or to 2 but the relay doesn't activate/deactivate.
So, what is the right PIN number to set in my relayPin constant to control the GPIO0 port?
The relay works succesfully if I give him +3.3V on GPIO0 with an external power.
Thanks in advance

why don't you just write test code that tries all the pins in sequence?

@jsotola tried with https://pastebin.com/pNsZY1ZX but nothing happens :(

check the traces on the relay PCB

@Juraj how can I do that?

I'm in the same boat as Roberto and wondering if this issue was resolved and what was the solution. Also interested in the firmware that was used in the ESP.

most GPIO pins on the ESP8266 "boot" up in INPUT mode
You'll need to
const int relayPin = 0; // or 2

void setup()
{
    pinMode(relayPin, OUTPUT);
}

The reason GPIO1 works is because GPIO1 is serial TxD - so, it's set to output

Thanks for your comment! It was already written in my code but I've forgotten to write it, now I've edited the 1st post ;) Thanks

Looking at better pictures of the PCB on ALIExpress it looks like GPIO0 is used to switch the relay.
What that pin maps to, though, depends on what board you have selected in the IDE.

Thanks for your answer Majenko! In Arduino IDE I've set "Generic ESP8266 Module", but where can I find the PIN mapping? :)

"PIN mapping"? GPIO0 is pin 0 ... GPIO1 is pin 1 ... up to GPIO16 is pin 16 ... it's not hard :p

@JaromandaX In this case it looks like yes, it's a 1:1 mapping between the GPIO number and the Arduino pin number (which is default). However, since digitalWrite() is a weak alias to __digitalWrite() it's perfectly possible that a board definition overrides that function with its own to implement a different numbering scheme.

Pin 1 is gpio 1 always on every 8266. Some boards may have d0 d1 etc.  But that is completely irrelevant to an esp01

Ok thanks, I've tried to set relayPin to 0 but nothing happens on the relay :( I've also tried with this sketch but nothing happens: https://pastebin.com/pNsZY1ZX What is missing?

1 solution I did is to use rx [GPIO 3] to drive relay. For this,

Need to short the GPIO 0 and GPIO 3(Rx) pin on the relay board.
While inserting the ESP-01, either bend the GPIO 0 or completely remove it from ESP-01 board. Be careful, on removing you wil find difficult to program the ESP-01 module again because GPIO 0 should go low at boot time to enable program mode. And this is the reason why GPIO 0 is HIGH on boot.

If you want, you can try this product
Smart Switch. Android Based ESP01 Relay Module

I had this exact same problem. Solution was to put 5 volts on the relay.
There is a regulator on the wireless relay that gives 3v to the ESP-01 and not 5v. But 5v is required for the relay to work.

You can use any pin of the esp-01
You may want to tell the TX and Rx pins though to behave like regular I/O with the pinMode/Function_3 command as described here:
https://arduinodiy.wordpress.com/2018/06/14/simple-wifi-relay-board-or-diy-sonoff-sv-sonoff-4-channel-2/

the question is about a pcb with relay already wired to a pin

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


text:
Arduino Uno R3 (with Atmega 16U2) and macOS 10.11 not working
So,
I have the newest Arduino IDE (1.8.5) installed and the newest release of Arduino AVR Boards 1.6.21.
My OS: macOS 10.11.6.
Usually I only use Nano's china clones with an CH340 USB-Serial chip, I have installed the wch driver and it worked fine !
My Nano's have the newest bootloader (Arduino AVR Boards 1.6.21).
And now the really annoying problem:
I recently ordered Elegoo Uno R3 boards, they have the original 16U2 chip for USB-Serial, no FTDI and no CH340 it's a Atmega 16U2.
And of course nothing works..
When I connect the Elegoo Uno to the mac (over the USB cable), it will show up in the system report - > USB as Arduino, but the IDE won't found it.
Sometimes it will be found by the IDE, but when I click upload (the Blink sketch) it print following:
    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/Users/USERNAME/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf"
         User configuration file is "/Users/USERNAME/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

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

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

         Programmer Type : Arduino
         Description     : Arduino
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
         Hardware Version: 3
         Firmware Version: 4.444305
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
         Vtarget         : 322122183.2 V
         Varef           : 49804.8 V
         Oscillator      : 548.816 Hz
         SCK period      : 3495249366.4 us

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: stk500_recv(): programmer is not responding

avrdude done.  Thank you.

So it receives the board information, but then the programmer does not respond, then he responds again and then not, a back and forth.
I have already made it by repeatedly clicking that the program has been uploaded.
Now the possible sources of error:

USB cable
Atmega328
Atmega16U2
My thought: something with the auto reset

Sidenote: I also update the 328 and 16U2(over DFU and USBasp) bootloader with an USBasp, no success (the bootloaders have been uploaded successfully, but I still can't upload a sketch)
Now the things I tried:

Other USB cable -> no success
Upload bootloader to the 328 -> success, program it via an TTL adapter over RX TX -> success, the led start blinking.
Upload bootloader to the 16U2 -> success, but simultaneously not an success, because the bootloader was uploaded successfully, but I still can't upload a sketch.
I read read read over 5 hours now, and the only helpful articles were:

Same problem as me, he has/had an mac with 10.11.06
He did it with an update of the USB drivers via MultiBeast (hackintosh driver installer) I also try it with no success (I also know that their is now driver for the 16U2, because normally there are built in CDC/ACM drivers, exception windows.)
..................
Arduino IDE serial ports not working on EL Capitan OSX
A big Github thread, with no real solution.
..................
The 80% solution
That gave me the idea to test it in a virtual windows machine and surprise surprise it worked, it uploaded without any errors (that I did not figure it out sooner, my fault).
So now I know that the usb cable, the 328, the 16U2 are fully working and nothing is damaged, the only thing that is not working is my mac.
Sometimes the UNO's are not recognized.
Sometimes the sketch is only uploaded to 90 percent, then the board doesn't respond.
The Nano's are fully woking, I thought maybe the CH340 driver for the NANO's make problems ?
So because of that my mac have problems with the UNO boards.
Honestly after that, I have no idea, I just want it to work.

A hackintosh is not a supported platform. Either Linux or Windows on a PC or OS X on a Mac. A frankensteinian combination of the two, well, it's anyone's guess what may work and what won't.

@Majenko Sorry this is absolute nonsense.

Using an operating system designed for Mac hardware on a pc (yes, the CPU is the same, but so what?) is asking for trouble. There are no guarantees that hardware drivers will function right. That includes things like the USB subsystem.

Do you come here to discuss or help?

If you had an Arduino problem then sure, we'd help. You have already proved that your Arduino is fine and that the problem is with running osx on a pc. We don't support that configuration. We know nothing about that kind of thing. Osx on a Mac, sure, you have a chance of support, since many here use a Mac. A real Mac. (Poor fools). I know of no one else that uses osx on a pc.

Ok i updated my question with "macintosh", because i think you don't understand that also the ones who have a "real mac" could help me very well, because many have the same issue and maybe someone fixed it.

From what I can see it's either problems with el crapitan (it's known as that for a reason) or hackintosh USB drivers. The Arduino is just a class-compliant CDC/ACM device. No drivers needed, no magic to get it working. Unless the OS is buggy as hell or you're running it on unsupported hardware.

No magic, hmm.. why so many people have the problem ?
Github Blog
With a OS that is stable as hell.
I will wait on answers, that give me more information, so that I can explore new solutions paths.

"Stable as hell..."...  (howls of derisive laughter...)

It sounds to me like the whole USB subsystem in El Crapitan is completely borked. For example, it's not just CDC/ACM that suffers: "Some users report that audio output devices attached via USB will spontaneously disconnect, with audio output reverting to internal speakers. "

Here's one nice review quote: "While the Apple faithful want users to focus on the benefits of upgrading to El Capitan, what I'm seeing is the rockiest, most buggy OS X release I can ever remember, and the first time since OS X has been available for download that I've not upgraded all my systems on day one."

My suggestion: Either upgrade or downgrade. Like I said: it's called "El Crapitan" for a reason.

No, I don't have such problems, my machine is rather stable.
It is only the port problem.
Oh, and to the "It's the Hackintosh's fault", whenI run the virtual machine, it is working just fine ,the mac even redirects the port to the vm.
It's also listed in the system report, it's not a real hackintosh problem.
It's a problem in macOS 10.11,
that's what i know.
And I think that a few people fixes this problem very well !

No, people with a real mac fix a problem that sounds similar to yours. You have an OS with known USB faults running on foreign hardware using third party USB drivers. Your problem is reasonably unique to you, because very few other people use the same combination as you. Which is why the fixes that work for other people don't work for you.


text:
Press button and Send Message Error
The problem is that sometime I don't even need to press the button and it sent message and keep on sending continuously.
What I want to do is that once the button is pressed, sent 1 message.
I cannot figure out why it is happening. Please help me to figure out.
 #define CUSTOM_SETTINGS
    #define INCLUDE_GPS_SHIELD
    #define INCLUDE_SMS_SHIELD
    #define INCLUDE_VIBRATION_SHIELD

/* Include 1Sheeld library.*/
#include <OneSheeld.h>
#include <string.h>
#define SW 8

/* Define a boolean flag. */

float lat;
float lon;
String Message;
String Message1;
String Message2;
char latitude[10];
char longitude[10];

void setup()
{
  pinMode(SW, INPUT);
  /* Start communication.*/
  Serial.begin(9600);
  OneSheeld.begin();

}

void Emergency() {

      /* Send SMS. */
      if(digitalRead(SW) == 1)
      {
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        Message1 = String(lat,8);
        Message2 = String(lon,8);

        Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
        Serial.println(Message);

        SMS.send("0637200721",Message);
        //Vibration.start(1000,2000);

        delay(3000);
      }
}

void loop()
{
  Emergency();

  delay(1000);
}

This is how I connect the button. The Grey cable is for Ground, The red is for 5V and the orange is to pin8. Between Red and Grey there is resistor.

I don't have a coding answer for you, but your problem is almost certainly contact bounce. There are de-bounce settings, but these tend to be one-way. A better approach is to detect a press, delay for a short time then confirm the button is still pressed.

@Milliways I am quite new to this field. So can you advice me more how to figure it out. Thanks

There are plenty of references e.g. https://playground.arduino.cc/Learning/SoftwareDebounce

I am trying to puzzle out the wiring of your button. It looks like you have +5V -> Resistor -> GND and then also GPIO  -> GND, and alongside that Nothing -> Button -> GND. Learn how to wire a button!

The problem is because I didn't put the following lines and I changed to use physical push button to 1Sheeld provided button from mobile. The follwing is the working code.
#define CUSTOM_SETTINGS
#define INCLUDE_GPS_SHIELD
#define INCLUDE_SMS_SHIELD
#define INCLUDE_VIBRATION_SHIELD
#define INCLUDE_PUSH_BUTTON_SHIELD

/* Include 1Sheeld library.*/
#include <OneSheeld.h>
#include <string.h>

/* Define a boolean flag. */
boolean isMessageSent = false;
float lat;
float lon;
String Message;
String Message1;
String Message2;
char latitude[10];
char longitude[10];

void setup()
{
  /* Start communication.*/
  Serial.begin(9600);
  OneSheeld.begin();
  PushButton.setOnButtonStatusChange(&Emergency);
}

void loop()
{

}

void Emergency(byte isButtonPressed) {
 if(isButtonPressed)
      {
        if(!isMessageSent)
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        Message1 = String(lat,8);
        Message2 = String(lon,8);

        Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
        Serial.println(Message);

        SMS.send("0637200721",Message);
        isMessageSent = true; // This line
      }
      else{
        isMessageSent = false; // This line
      }


text:
Compiling with -flto and -nostartfiles results in no program at all
Towards developing my own bootloader I've stumbled over an issue with avr-gcc. I am trying to compile my code with the compiler flags
-flto          #to enable link time optimization
-nostartfiles  #to omit the interrupt vector table

My bootloader consists of multiple files which are used depending of compile flags. All the sources are being compiled and linked while the code path only leads to some portions of them. So I wanted to get rid of the dead code and -flto (being a newer development) creates a much smaller machine code size than -ffunction-sections -fdata-sections with -Wl,--gc-sections -Wl,--print-gc-sections.
But when it comes to further reducing the machine code size by removing the interrupt vector table using -nostartfiles, the complete code gets optimized away leaving me with a zero byte output.
Has anyone experienced the same issue with that compiler flag combination?

I have experienced that I couldn't compile an Arduino sketch anymore with LTO because the optmization was so aggressive that it optimized out certain ISRs of hardware peripherals. Maybe GCC thinks that the initial bootup function (at 0x0000 or wherever) is never called and kills everything? Maybe try sprinkling __attribute__ ((used)) over some functions and see what happens? (https://gcc.gnu.org/wiki/LinkTimeOptimizationFAQ)

This is it! It now produces output. But it is not smaller than the --gc-sections version any more. I suppose it was removing some parts already that were supposed to stay. Thank you!

Great to hear! I think I'd be great if you'd answer the question yourself and include your specific critical piece of code that made it work.

As @MaximilanGerhardt wrote in his comment. LTO was optimizing away too much of the code. Usual programs start with the interrupt vector table that in case of a regular reset or startup point to the main function. That is why the compiler knows that main has an entry point and is used. The actual program starts at the table.
Removing  the interrupt vector table with -nostartfiles causes the compiler not to know that main is used at all and optimizes it away.
To give the compiler a hint __attribute__((used)) has to be placed at all methods that have to stay and there is no code path leading to them otherwise.

You've sort of stumbled into something that works, but it's not really the right answer.  What you should be doing is using a linker script (traditionally .ld file) which puts your startup code (preferably a wrapper not main() itself) at the correct address, with a "keep" attribute.   In the case of the AVR the "vectors" are really jump instructions, so if you only want to support the reset one you can probably just start your code there; in other architectures the vectors are pointers, so you'd need the address of your startup code followed by code.

Also note that without startup code, initialized RAM variables won't work, as copying that initialization from flash to RAM is done by startup code; however PROGMEM type values will.


text:
comparison in a time sequence
in an Arduino sketch a user is invited to input a number representing a time in the format HH:MM,  this number is to be added at the end of an ordered and limited sequence of times
--the first input (lower limit) can be any time within the 24 hours,
--the upper limit is calculated as lower_limit+period; with period being 1,2,3,4,6,8,12 or 24 hours,
--and to be accepted, the input must verify that it is chronologically after the previous element, and that it's within the given period;
for example if first element is 20:00 and the period is 8, the upper limit will be 20+8=28 wich is 04:00; both 21:00 and 03:00 are accepted, where'is 19:00, 05:00, 09:00, 17:00, ... are rejected.
without any information on the 'day', i did not find any suitable algorithm, and none of the available Arduino libraries is useful in this case.
any link, or tip,...

Are the numbers inputted via Serial? On the first example, is it correct that any time from inclusive 20:01 to 04:00 will be accepted?

This smacks of homework to me....

Tip: work in minutes. The modulus (%) operator is your friend.

@maximilian-gerhardt: numbers are inputted via buttons... any number from 20:01 to 04:00 are accepted if it's chronologically after the last element before the upper limit...

You have numerous problems here - how to enter the times, how to convert that entered time into minutes, how to compare those times properly. Tackle it one thing at a time.

So you said you already solved the problem?

@majenko: sorry  i didn't give anough information... the only problem is how to compare those times properly...

@maximilian-gerhardt: working in minutes give a simple representation of the times but did not solve the problem... applied to the example the upper limit is still inferior to the lower limit: [20:00 to 04:00] becomes [1200 to 240]...

if (start < end) { // check if it's greater than start *and* less than end } else { // check if it's greater than start *or* less than end }

Here is the basic idea and a sample implementation for solving the problem:
The problem is: Given a start time time1 and a period period, each described by a pair of (hour,minute), how can we check whether another time time2 is within time1 to time1 + period?
First we can see that we given a (hour, minute) pair we can compute the total number of minutes as totalMinutes = 60*hour + minute.
Then we can observe that there two distinct cases that we must check:

the entire "time check period", that is, time1 to time1 + period is within 00:00 to 24:00 without overflowing past 24:00 when we simply add the times. then, we can use a simple bounds check worded as "time2 must be greater than time1 and less or equal to time1 + period when comparing total minnutes.
time1 + period overflows past 24:00. We consider an example of  time1= 20:00 and period = 8:00. Thus all valid times are from 20:00 to 04:00 with an implicit "wrap around" at 24:00 to 00:00. We can see that there are now two time-intervals we must check: Everything from 20:01 to 24:00 and from 00:00 to 04:00 is valid. Thus we can derive the the bounds in minutes again. We can obtain the 04:00 by computing 20:00 + 08:00 modulo 24:00. The C operator % is used to compute the residue of the division by a certain number. I.e. 28 % 24 = 4 because 28 / 24 = 1 residue 4. This is  called modulo-arithmetic.

The following C++ program demonstrates the solution:
#include <cstdio>

/* returns whether time2 defined by hour2:minute2 is within the period time1 = hour1:minute1 to time1 + period. */
bool is_time_within_period(
    int hour1, int minute1,
    int hour2, int minute2,
    int periodHour, int periodMinute) {

        //Reject garbage input
        if(hour1 > 24 || hour2 > 24
            || minute1 > 60 || minute2 > 60
            || periodHour > 24 || periodMinute > 60) {
                //TODO throw error message
                return false;
        }

        //Convert hours and minutes into absolute minutes. One hour is 60 minutes.
        int time1Minutes = 60 * hour1  + minute1;
        int periodMinutes = 60 * periodHour + periodMinute;
        int time2Minutes  = 60 * hour2 + minute2;

        int periodEnd = time1Minutes + periodMinutes;

        //If the start time plus the period time is over 24:00 there is a wrap-around the we need to consider.
        bool wrapAround = false;
        if( periodEnd > (24 * 60)) {
            wrapAround = true;
        }

        bool result = false;

        //printf("Wrap: %d Period end %d\n", wrapAround, periodEnd);

        if(!wrapAround) {
            //if there is no wrap-around we can just compare the total minutes against each other
            //time1 must be after time2 but before (time1 + period).
            result = time2Minutes <= (time1Minutes + periodMinutes) && time2Minutes > time1Minutes;
        } else {
            //There was a wrap around, i.e. start time + period was beyond 24:00.
            //We need to make two comparisons: is it in the time period from time1Minutes to 24:00?
            result = time1Minutes < time2Minutes && time2Minutes <= (24 * 60);

            //the result can also be okay if it from the time from 00:00 to the remaining period
            //use the module operator here. This transforms e.g. 28:00 would be reduced to 04:00. (modulo 24 hours calculated in minutes)
            int upper = (periodEnd % (24 * 60));
            //printf("Upper: %d (%02d:%02d)\n", upper, (upper / 60), upper % 60);
            result |= time2Minutes >= 0 && time2Minutes <= upper;
        }

        return result;
}

int main() {

    const int hourStart = 20;
    const int minuteStart = 0;

    const int periodHours = 8;
    const int periodMinutes = 0;

    //play around with these values
    const int compareTimeHour  = 4;
    const int compareTimeMinute = 0;

    printf("Start: %02d:%02d\n", hourStart, minuteStart);
    printf("Period: %02d:%02d\n", periodHours, periodMinutes);
    printf("Check time: %02d:%02d\n", compareTimeHour, compareTimeMinute);

    bool res = is_time_within_period(hourStart, minuteStart, compareTimeHour, compareTimeMinute, periodHours, periodMinutes);

    if(res) {
        printf("Time is within bounds\n");
    } else {
        printf("Time is not within bounds\n");
    }

    printf("Hello\n");

    return 0;
}

The function is_time_within_period has no dependencies and can thus be copy-pasted into any Arduino sketch.
Let the start time be 20:00 and the period 04:00. Then feeding the program different times to compare against lets us see that it indeed works.
Start: 20:00
Period: 08:00
Check time: 20:00
Time is not within bounds

Start: 20:00
Period: 08:00
Check time: 20:01
Time is within bounds

Start: 20:00
Period: 08:00
Check time: 04:00
Time is within bounds

Start: 20:00
Period: 08:00
Check time: 04:01
Time is not within bounds

it was very simple: if there is a wrap-around in the comparison interval; then we divide this interval in two at the point of this wrap-around... thanks and +5...

The function is_time_within_period has no dependencies and can thus be copy-pasted into any Arduino sketch.


text:
Arduino weather station BMP280 and BM1750
im experiencing troubles with combining a arduino sketch with BMP280 and BM1750. At this moment i have 2 sketches which need to be combined.

#include Wire.h>
#include BH1750.h>

// ADDR line LOW/open:  I2C address 0x23 (0x46 including R/W bit) [default]
// ADDR line HIGH:      I2C address 0x5C (0xB8 including R/W bit)
BH1750 sensor(LOW);

void setup()
{
  Serial.begin(115200);
  Serial.println(F("BH1750 continues measurement basic example"));

  // Initialize I2C bus
  Wire.begin();

  // Initialize sensor in continues mode, medium 1 lx resolution
  sensor.begin(ModeContinuous, ResolutionMid);

  // Start conversion
  sensor.startConversion();
}

void loop()
{
  uint16_t lux;

  // Wait for completion (blocking busy-wait delay)
  if (sensor.isConversionCompleted()) {
    // Read light
    lux = sensor.read();

    // Print light
    Serial.print(F("Light: "));
    Serial.print(lux);
    Serial.println(F(" LUX"));
  }
}

and the BMP280

#include  Wire.h>
#include SPI.h>
#include Adafruit_Sensor.h>
#include Adafruit_BMP280.h>
#include ESP8266WiFi.h>
#include BH1750.h>

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10

Adafruit_BMP280 bme; // I2C
BH1750 lightMeter;

/**************************
 *   S E T U P
 **************************/
void setup() {
  Serial.begin(9600);
  // Initialize the I2C bus (BH1750 library doesn't do this automatically)
  Wire.begin(D2,D1);
  // On esp8266 you can select SCL and SDA pins using Wire.begin(D4, D3);

  lightMeter.begin();
  Serial.println(F("BMP280 test"));
  if (!bme.begin()) {
    Serial.println("Could not find a valid BMP280 sensor, check wiring!");
  }

}

  /**************************
 *  L O O P
 **************************/
void loop() {

  uint16_t lux;

  // Wait for completion (blocking busy-wait delay)
  if (sensor.isConversionCompleted()) {
    // Read light
    lux = sensor.read();

    // Print light
    Serial.print(F("Light: "));
    Serial.print(lux);
    Serial.println(F(" LUX"));
  }
    Serial.print("T=");
    Serial.print(bme.readTemperature());
    Serial.print(" *C");

    Serial.print(" P=");
    Serial.print(bme.readPressure()/100);
    Serial.print(" hPa");

    Serial.print(" A= ");
    Serial.print(bme.readAltitude(1013.25)); // this should be adjusted to your local forcase
    Serial.println(" m");
    //every 20 sec
    delay(2000);
}

The BMP part is working fine.

i do have a combined script now, but it seems only the lux part is giving results. the BMP values are 0

Then you'd need to edit the question to show us your current program.


text:
Android phone can't get ESP8266WebServer page if Content-Length > 1460
I uploaded the following sketch to my ESP8266:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);
String toServe;

void serveShortString() {
    server.send(200, "text/plain", "short string!");
}

void serveLongString() {
    server.send(200, "text/plain", toServe);
}

void setup() {
    WiFi.softAP("test");

    // fill string to serve:
    toServe.reserve(3000);
    for(int i=0; i<150; i++) toServe += "1234567890123456789\n";

    server.on("/long", serveLongString);
    server.on("/short", serveShortString);
    server.begin();
}

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

It serves a short message on /short and a long message (3000 chars) on /long.
The /short page works everywhere: Windows, Desktop Linux (Fedora) and Android.
The /long page, on the other hand, only works on Windows and most of the time on desktop Linux. It never works on Android. I tried two phones.
I captured the network traffic on my Android phone using tPacketCapture. This is the result:

When trying to get /short, everything works fine. When trying to get /long, only the header comes through but the content never arrives. As I said, everything works fine on Windows and (most of the time) on Desktop Linux. Any idea what's going wrong?

Sounds like you're hitting some MTU limit or fragmentation issue.

@Majenko yeah, when the response takes up more than one TCP packet, Android only receives the first one (as seen in the capture). It works on other operating systems though.

This seems to be a problem with the core libraries, probably best to open an issue on GitHub.

The solution is to add the following line to platformio.ini:
build_flags = -D PIO_FRAMEWORK_ARDUINO_LWIP2_LOW_MEMORY

I noticed that the same sketch works without a problem when building with the Arduino IDE, so I checked the differences in building with platformio and the Arduino IDE.
Turns out the relevant difference is that the Arduino IDE uses lwIP 2 by default, while platformio uses 1.4, which seems to have this bug (the same bug appears when using the Arduino IDE with lwIP 1.4).
The build flag above tells platformio to use lwIP v2.


text:
Power on, power off voice using fx board
I played with one of those Adafruit FX sound boards in a project a while ago, and see a lot of potential uses for it.
I would like to create “something” for my daughter, when she turns the lights on, (110v bedroom lights) a voice may say “good evening Kyndra” and when she turns the lights off the voice may say “have a good day...”.
The power “on” is not a big problem, the power off is my issue.... I could run a separate circuit and use a solid state off delay that when it sees first circuit go down it triggers a line of code.
With all the new stuff coming out all the time, just wondering if anyone else has a better idea to build a poor mans version “Jarvis 1.0”.  Perhaps using an Arduino may not even be the route I want.
This is just a thought... I’ve been tossing over for a while now.  It’s not imperative it ever gets built. Just thought it would be cool for her.

A sufficiently large capacitor may give you enough time to play the sound after loss of power if you do a good job of detecting the event.  Best to do this downstream of an off-the-shelf mains supply rather than trying to make your own.

Just have it run on independent power, and detect if the lights go on/off by measuring the light level.


text:
ESP.deepSleep() - over and over?
Important note: the esp.deepsleep function uses microseconds, not milliseconds.
I posted another question here asking for clarification on how an RTC can be used to put a NodeMCU 12 to sleep for a long time (~24hrs or more).
This question concerns the use of ESP.deepSleep([microseconds]) with the NodeMCU 12 board.  There is a discussion here and I have followed the advice but have been unable to successfully implement the ESP.deepSleep() function using the Arduino IDE and a NodeMCU 12 board.
Initial findings:
-Connecting gpio16 (D0) to the RST pin causes a reset immediately upon entering sleep.  The entire boot process and loop are repeated over and over again.
-Simply using the ESP.deepSleep() function without gpio16-to-RST generates gibberish on the serial monitor and illuminates the red led on the board.
My code is here (I just drop "deepsleep();" where I want the sleep process to begin):
void deepsleep() {
  Serial.println("sleeping hr 1");
  ESP.deepSleep(3600000); //1hr
  delay(100);
  Serial.println("sleeping hr 2");
  ESP.deepSleep(3600000); //2hr
  delay(100);
  Serial.println("sleeping hr 3");
  ESP.deepSleep(3600000); //3hr
  delay(100);
  Serial.println("sleeping hr 4");
  ESP.deepSleep(3600000); //4hr
  delay(100);
  Serial.println("sleeping hr 5");
  ESP.deepSleep(3600000); //5hr
  delay(100);
  Serial.println("sleeping hr 6");
  ESP.deepSleep(3600000); //6hr
  delay(100);
  Serial.println("sleeping hr 7");
  ESP.deepSleep(3600000); //7hr
  delay(100);
  Serial.println("sleeping hr 8");
  ESP.deepSleep(3600000, WAKE_RF_DEFAULT);  //8hr
}

What is wrong with this approach and why am I (apparently) causing an error?

just one point you may not be aware of ... the code you show suggests you think the ESP will continue on from after the deepsleep once it wakes up - that's not the case. after it wakes from deepsleep, it goes through the boot process (with a boot reason that indicates it has woken from sleep) - when you say "the entire boot process are repeated", do you mean immediately? or after 1 hour?

Immediate.  Sorry for the confusion.

well, that's not good - if it were after 1 hour, then the solution is easy, but immediate is problematic

What's the solution for the 1hr error?

Not sure what you mean by that. Seeing as you say that the ESP isn't deep sleeping at all, then the question makes no sense

It's something that people may run into at some point and, if it's a simple answer, we are all better off knowing how to resolve it.  Even a simple explanation may get someone pointed in the right direction.

but that's not your problem - Anyway, the solution I'm speaking of regarding the code you posted is simply knowing that when a ESP awakes from deepsleep, it goes through full boot process, does not continue from where it left off. You can use system_rtc_mem to save some simple "state" so that when you boot, you know if this is an initial boot, or wake from deep sleep (and which deep sleep you've woken from) - the guy with a swiss accent has some nice code examples

Use a resistor between GPIO16 and RST. I usually use a 470 Ohm resistor. Shorting the pins with a wire does not work.
https://www.esp8266.com/viewtopic.php?t=14350#p64510
Maximum deep sleep is about 71 minutes. 3600000 microseconds = 3.6 seconds, not 1 hour. 1 hour in microseconds is 3600000000UL.
As mentioned in the comments, waking from deep sleep on the ESP8266 is a hardware reset so execution begins at the start of the setup function.

Every circuit for deep sleep I've ever seen has no resistor. I think the only issue was the sleep interval

inputs are high-impedance, so adding 470 ohms makes no practical diff

Yes, the linked-to topic is talking about also using an external method for resetting the board. In that case, you'll need a resistor, not when just connecting the GPIO to RST.


text:
Arduino Due & Spec gas sensor - how to choose specific information from a stream of incoming bytes to store
I'm trying to build an air pollution sensor for a college project, with an Arduino Due and a series of Spec Sensors digital gas detectors. However, I'm having a little trouble getting the first one of them (Carbon Monoxide, https://www.spec-sensors.com/product/digital-co-sensor/) to behave, before I can run multiple. As they're all the same sensor setup but for different gasses, once I get the first one working, the rest should follow easily.
The code's very simple, as it uses Spec's own command system - sending the letter "c" to the sensor forces it to take one reading per second for as long as the sensor is powered, and then the serial monitor displays whatever comes back:
    void setup() {
      // sensor running via Serial1
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial1.print("c");
    }

    void loop() {
      if(Serial1.available()!=0)
      {
        Serial.write(Serial1.read());
      }
    }

My problem comes with the data that's being returned. The gas reading is present, but so is a lot of superfluous information that I don't need. According to the sensor's tech document, the information returned is: serial number, reading (ppb), temperature, humidity, raw voltages, and amount of time the sensor has been running for. In the serial monitor, it looks like this:

Right now, all I want is the reading in ppb (the second value), either as the only data coming through or being stored, so that it can then be used in calculations like averages per hour. The trouble I have is that this information appears to be coming through as a stream of individual bytes, and in this format I'm having difficulty working out an effective way to specify which information I want to store, and which I want to ignore.  I've been trying, for example, to come up with a way to specify that the first 14 bytes (serial number, comma, space - as this will always be the same length) should be ignored, and then the next series (up until the next comma - as this reading could be 4-6 digits) be stored as an int, or something, but I just can't seem to get anywhere no matter what I try. Does anyone have any suggestions?

note: the 1 second continuous read seems to be undocumented

Since the length of each data varies, you should extract data using spererator like comma in the stream.
First, get one data line from sensor. Read the string until the "Line feed(LF)" character or "Carriage Return(CR)" character appears. located at the end of line(EOL), these two characters seperates each string by changing line. Without these two characters, the monitor shows the stream like this(no line change).

102617010933, 8486, 22, 35, 13464, 25716, 21962, 00, 00, 20, 06102617010933, 87216, 22, 35, 13576, 25223, 21442, 00, 00, 20, 07

So you can see there are CR, LF characters at the EOL. Utilize CR or LF as a terminator of ReadStringUntil() function.
https://www.arduino.cc/en/Serial/ReadStringUntil
Second, parsing process. This process is extracting data you want from strtok() function. strtok() is from C language. It divides string by seperator characters.
https://stackoverflow.com/questions/3889992/how-does-strtok-split-the-string-into-tokens-in-c?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
Lastly, utilize the data and repeat whenever sensor sends the data.
I'm not expert at coding. I haven't tested the code below. But this code would be helpful.
int data[12];
int isDataReceived = false;

void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.write('c');
}

void loop(){
  while(Serial1.available()>0) {
    String inString = Serial1.readStringUntil('\n');
    char * pch = strtok(inString, ","); //Serial number would be ignored
    for(int i=0; pch != NULL; i++) {    //following data are stored in data[12] string
      pch = strtok(NULL, ",");
      data[i] = atoi(pch);
    }
    isDataReceived=true;
  }
  if(isDataReceived) {
    Serial.print("Data:");
    Serial.println(data[0]); //just example code. You may see ppb on the serial monitor.
    isDataReceived=false;
  }

}