text:
How can I run Hello World using Serial Monitor in Tinkercad Arduino simulator?
I want to achieve printing Hello World in the serial monitor using Tinkercad to simulate Arduino.
Here is a very simple example code for real Arduino.
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Hello World!");
}

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

}

However, putting an Uno board, typing this code, and clicking "Start Simulation" in Tinkercad doesn't show the Hello World message.
Is it doable? If so how?
For real Arduino, you need to select Arduino serial port and open Serial Monitor. But I can't find such an option for Tinkercad. I can't find Serial Monitor in Thinkercad.
My real purpose is to use Serial Monitor output to test code snippets. Right now I don't have real Arduino board with me, so I thought a simulator would be ideal. If I can easily check the values of variables, it doesn't have to be Serial Monitor.
Sorry if this is not a place to ask questions about simulators.

Did you open the Serial Monitor?

Can you provide a public link to your tinkercad simulation?

Does this answer your question? How to simulate Arduino?

I mean where would you expect it to print Hello World ... On the Serial Monitor, right? So first open it by clicking on the Serial Monitor button at the bottom of the code tab in Tinkercad.
I tried your code and it works perfectly fine.

Haha! Thanks a lot, this kind of things is easy if you know where to look, but hard if you don't.


text:
EEPROM.read data not comparing with DHT11 sensor value - Arduino temp controller
I'm using a DHT11 to read temperature to control a relay that will control a fan. When 'A' is pressed it allows the user to update the temp value that the relay will go HIGH at. The value is being stored and read to and from the EEPROM but they are not being compared properly in the if statement. Please help!
#include <EEPROM.h>
#include <Keypad.h>
#include <LiquidCrystal.h>
#include <dht11.h>
dht11 DHT;

char temperature[2];
char initial_temperature[2];
char new_temperature[2];
char key_pressed=0;

const int relay = 8;
const int dht11_data = 6;
int temp=0;
int relayState = LOW;
int i=0;
int j=0;
int init_pass = 0;

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the symbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {38, 40, 42, 44};
byte colPins[COLS] = {46, 48, 50, 52};

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

 //initialize an instance of class NewKeypad
 Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

 void setup() {
 Serial.begin(9600);
 pinMode(relay, OUTPUT);
 digitalWrite(relay, relayState);
 lcd.begin(16,2);
 lcd.print("  Welcome to ");
 lcd.setCursor(0,1);
 lcd.print("     Test 2");
 delay(2000);
 lcd.clear();

   }

void loop() {

DHT.read(dht11_data);
temp=DHT.temperature;

lcd.clear();
lcd.setCursor(5,0) ;
lcd.print("Temp");            //display"Temp="
lcd.setCursor(5,1);
lcd.print(temp);
lcd.write(0xDF);              //Display custom characters '°'
lcd.print("C");

delay(200);
initialtemperature();

       // here is the problem - comparing temp>=init_pass
 // 'temp' will not compare with value of 'init_pass'
 // like it does with a number value in it's place.

for(int j=0;j<2;j++){
init_pass = (initial_temperature[j] - '0');

if (temp >= (init_pass)){

 if(init_pass==2)
   relayState = HIGH;
   digitalWrite(relay,  relayState);

   Serial.print(init_pass);
  }
  }

 key_pressed = customKeypad.getKey();
 if(key_pressed=='A')
 change();
}

void change(){
  j=0;
int i=0;
Serial.begin(9600);
lcd.clear();
lcd.print("FanOn Temp=");
lcd.print(initial_temperature);
// Serial.print(initial_temperature);
lcd.write(0xDF);
lcd.write("C");
lcd.setCursor(0,1);
lcd.print("New Temp=");
delay(200);
while(i<2)

{

char pressed=customKeypad.getKey();
if(pressed){
  new_temperature[i++]=pressed;
  lcd.print(pressed);
  EEPROM.write(j,pressed);
  j++;
}

pressed=0;

}
if(i==2){
lcd.write(0xDF);
lcd.write("C");
delay(1000);
lcd.clear();
lcd.print("Saved");
delay(1000);
  }
  }

 void initialtemperature(){

for (int j = 0; j < 2; j++)
initial_temperature[j] = EEPROM.read(j);

}

temp is not comparing with init_pass ... if (temp >= (init_pass)){
if(init_pass==2)
relayState = HIGH;
digitalWrite(relay,  relayState);
Serial.print(init_pass);
}

btw it was formatted until I posted it... not sure what I did

print as in Serial.print? I was using that for testing. If you mean something else, can you provide an example?

Don't post >100 lines of code and say something vague like "... they are not being compared properly in the if statement." Delete code that isn't germane to your question, and point out the specific line that is giving you trouble (along with a description of any setup or context we need in order to understand the line in question.)

the problem starts at: if (temp >= (init_pass)){     comparing temp>=init_pass
'temp' will not compare with value of 'init_pass'  like it does with a number value in it's place.

Everything in this sketch works up to this point.

you are misunderstanding the problem ..... the if (temp >= (init_pass)){ also works correctly ..... it just does not give the results that you expect because the two values are not what you think they are     ........ as per my previous comment, what were the values of temp and init_pass and the length of temp and init_pass before the if statement?

So, to my understanding temp is a numeric or a integer value? and init_pass is converted to ASCII DEC value by using init_pass = (initial_temperature[j] - '0');? ...and the length off both is 2. it seems i either need to find a way to convert the 2 characters to one byte or write the value as one byte to begin with?

source: Stack Exchange

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

sort: votes


text:
Is there any working analogue to the pair std::function and std::bind in Arduino?
Both ArduinoSTL and StandardCplusplus don't support them. They implement the version that is compatible with c++03 (not c++11).
This functionality is handy when you design libraries that work with callbacks. And you do need them, if your Arduino does more than one thing simultaneously.
I tried also several other options, but none was enough. Most complete thing I found, Passing capturing lambda as function pointer, does not support plain function pointers and does not allow me to hold the function object as a member of the structure, because the type of the object depends on the lambda (not only its signature, like in std::function).
In particular, I need a functor that

can store both capturing lambdas and plain function wrappers
has a type that depends only on the signature of the function, so I can store it as a class member.

Well, ARM compilers with C++11 support usually have working functional library and other STL stuff. For the AVR's you can try to implement something own, or copy something like in mbed (its online compiler doesn't support c++11 so they have some not very good wrapper classes for callbacks)

@KIIV Writing a proper substitution of std::function seems very intimidating to me. Do you know something that is already written, that I can use to store both capturing lambdas and function pointers?

It can do just function pointers and as a bonus even method pointers, but it's not for the c++11 so no lambdas.

Storing capturing lambdas and function pointers will require implementing some kind of type-erasure. And that is exactly what std::function is. You will have to implement some version of std::function. You can make a simplified implementation, but there's no way around it. Although it is not clear why you claim that you need callbacks to do "more than one thing simultaneously".

I mean the event driven execution, i.e. cooperative multitasking. I suppose you are not aware if anyone wrote such library?

This is not on the whole an unreasonable thing to want to do. I've just been asked to port a framework I wrote on the ESP8266 over to vanilla Arduino and guess what - I've made extensive use of std::function for callback registration because of the elegance and modularity it enables. In a thin-and-light environment this is an extremely useful thing to be able to do.

We have written a solution, that we published as a Platformio library: https://github.com/fopeczek/function_objects.
Please note, that each functional object does one allocation, and those are not particularly friendly in an embedded environment. I am not even sure, that the Arduino C++ does heap deallocation, so you may be leaking resources if you create and destroy the functional objects in a loop.

I've changed the address of the repository - by mistake I pointed you to an old and defunct one. The proper address is https://github.com/fopeczek/function_objects

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


text:
Creating an array of structures which store bitmaps to work with u8glib
I've tried reading the documentations and I'm getting desperate because I can't find anything.
I need to create an array of structures, which contains a bitmap stored in PROGMEM space (because of issues with memory usage).
The bitmaps are created as follows:
const uint8_t pat[] PROGMEM = {
...
};

Then I need to create a structure like this:
typedef struct{
    uint8_t bitmap[8];
} chars;

chars allChars[1];

but the compiler doesn't like that for some reason and spit out a bunch on invalid conversion from const to char so it was clear I couldn't use that!
My next attempt was to create a pointer to the pattern like so:
typedef struct{
    const uint8_t *bitmap[8];
} chars;

chars allChars[1];

This time it again gave warnings about invalid conversion but at least compiled!
I then tried to write the entire code and run it:
#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

typedef struct{
    const uint8_t *bitmap[8];
} chars;

chars allChars[1];

const uint8_t pat[] PROGMEM = {
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x66
};

void draw(void) {
  u8g.drawBitmapP( 37, 28, 1, 8, pat);
  u8g.drawBitmapP( 74, 28, 1, 8, (char*) allChars[0].bitmap);
}

void setup(void) {
  allChars[0]= (chars) {*pat};
}

void loop(void) {
  draw();
  while(true);
}

the first line where I have used the pattern directly in the draw function, works perfectly fine, but the second line which retrieves the value from the pointer draws some weird noise shape (I'm guessing memory dump of an address or something)!
Is it even possible to create a struct with one of the variables being just a pointer to the constants that I have defined earlier? I'm pretty sure I'm doing something very wrong as I'm not familiar with using pointers and addresses and whatnot, so it would be great if someone could help with these issues!

Try "allChars[0].bitmap = pat;"

That still wouldn't solve the issue with struct!
I think I have found a glitch in GCC compiler where if you define your struct in dynamic memory rather than PROGMEM, even if you use a buffer and fetch the data using memcpy_P, it will return the correct value while printing, but when you copy it again to allChars[0].bitmap , the wrong value is copied! the thing that solved the issue was adding PROGMEM to the struct like below:
typedef struct {
  unsigned int ascii;
  int size[2];
  const PROGMEM unsigned char *bitmap;
} chars;

I have not yet encountered any compilers that are this specific and don't even allow transfer between memory spaces correctly. (Not to mention other issues with GCC linker that are brought up by david from eevblog like stack overflow without warning, etc). They really need to solve issues like this as this compiler is one of the most frequently used on different platforms.
anyways, here is the final code if anyone finds it useful (I will probably end up making a youtube video about it later):
#include "U8glib.h"
//U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

typedef struct {
  unsigned int ascii;
  int size[2];
  const PROGMEM unsigned char *bitmap;
} chars;

chars allChars[1];

const unsigned char pat[] PROGMEM = {
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x01, 0xfc, 0x00,  //.......%%%%%%%.......
  0x0f, 0xff, 0x00,  //....%%%%%%%%%%%%.....
  0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
  0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
  0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
  0x0f, 0xff, 0x80,  //....%%%%%%%%%%%%%....
  0x01, 0xfc, 0x00,  //.......%%%%%%%.......
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
};

void charToBitmap(int x, int y, char chr){
  for(unsigned int i=0; i<sizeof(allChars);i++){
    if (allChars[i].ascii=chr){
      u8g.drawBitmapP( x, y, allChars[i].size[0], allChars[i].size[1], allChars[i].bitmap);
      break;
    }
  }
}

void draw(void) {
  charToBitmap(0,0,'0');
}

void setup(void) {
  allChars[0] = (chars) {48,{3,54},pat};
}

void loop(void) {
    u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );
}

You're making it far too hard on yourself.
All you need is a single 2-dimensional array of data in PROGMEM:
const uint8_t bitmaps[10][8] PROGMEM = {
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
};

Each row is a bitmap, and there are 10 rows, so 10 bitmaps (I have them all the same at the moment).
Then you just reference the slice number you are interested in:
u8g.drawBitmapP( 100, 30, 1, 8, bitmaps[3]);

Note: I haven't tested this.


text:
read with Arduino SSI encoder signal
I'm stuck in my project, I try to read an absolute encoders angular position with my Arduino.
I used and cabled a differential line receiver and driver between Arduino and the encoder, like explained in the 2 following links:

Figure 2.1 here
Input circuitry of subsequent electronics

Here are the specifications of the encoder that I try to read.
Here is my Arduino code :
const int CLOCK_PIN = 5;
const int DATA_PIN = 6;
const int BIT_COUNT = 25;

void setup() {
  //setup our pins
  pinMode(DATA_PIN, INPUT);
  pinMode(CLOCK_PIN, OUTPUT);

  //give some default values
  digitalWrite(CLOCK_PIN, HIGH);

  Serial.begin(115200);
}

void loop() {
  float reading = readPosition();

  if (reading >= -0.5) {
      //Serial.print("Reading: ");
      //Serial.println(reading,2);
  }

  delay(200);
}

//read the current angular position
float readPosition() {
  unsigned long sample1 = shiftIn(DATA_PIN, CLOCK_PIN, BIT_COUNT);
  unsigned long sample2 = graytobin(sample1, BIT_COUNT);
  delayMicroseconds(25);  // Clock mus be high for 20 microseconds before a new sample can be taken

  Serial.print("grey: ");
  Serial.println(sample1, BIN);
  Serial.print("binary: ");
  Serial.println(sample2, BIN);
  Serial.print("decimal: ");
  Serial.println(sample2 & 0x0FFF);
  Serial.print("\n");

  return ((sample2 & 0x0FFF) * 360UL) / 4096.0;
}

// gray to binary
int graytobin(int grayVal, int nbits ) {
  int binVal = 0;
  bitWrite(binVal, nbits - 1, bitRead(grayVal, nbits - 1)); // MSB stays the same
  for (int b = nbits - 1; b > 0; b-- ) {
    // XOR bits
    if (bitRead(binVal, b) == bitRead(grayVal, b - 1)) { // binary bit and gray bit-1 the same
      bitWrite(binVal, b - 1, 0);
    }
    else {
      bitWrite(binVal, b - 1, 1);
    }
  }
  return binVal;
}

//read in a byte of data from the digital input of the board.
unsigned long shiftIn(const int data_pin, const int clock_pin, const int bit_count) {
  unsigned long data = 0;

  for (int i=0; i<BIT_COUNT; i++) {
    data <<= 1;
    digitalWrite(clock_pin,LOW);
    delayMicroseconds(1);
    digitalWrite(clock_pin,HIGH);
    delayMicroseconds(1);

    data |= digitalRead(data_pin);

  }

  return data;
}

I'm still able to receive information with my Arduino from the encoder but they are totally random. Here is an example of the output I get (I didn't move the encoder during this exercition):
grey: 1001111101110100011111001
binary: 11111111111111111011000010101110
decimal: 174

grey: 111110110010001111100111
binary: 11110101000101
decimal: 3397

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 1111111111111111111111111
binary: 11111111111111111010101010101010
decimal: 2730

grey: 1011001110011011100010001
binary: 10010111100001
decimal: 1505

grey: 1100111011011100100011111
binary: 11111111111111111101000111101010
decimal: 490

grey: 1101110110111001000111111
binary: 101110000101010
decimal: 3114

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 111111
binary: 101010
decimal: 42

grey: 111011011100100011100111
binary: 11111111111111111000111101000101
decimal: 3909

grey: 1100111001101110010001111
binary: 11111111111111111001011100001010
decimal: 1802

grey: 1100111011011100100011111
binary: 11111111111111111101000111101010
decimal: 490

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

grey: 0
binary: 0
decimal: 0

I don't know how to diagnose the problem, and how to find it.

Please add wiring of circuit. Double check that ground and cables. Also try a lower clock frequency, e.g. delayMicroseconds(2).


text:
How to exclude a ino/pde file from Arduino projects
I would like to be able to exclude from the auto-including process of the current project (without renaming the extension or delete it) a sketch with pde or ino extension that is used in certain circumstances only.
How can I do this?
I currently use Visual Micro to manage projects on Arduino.

One possible approach is to guard the body of that sketch with an #ifdef ... #endif pair, and use Visual Micro's  “Project Properties” to define (or not) a preprocessor symbol.  [If the .ino or .pde in question is used as a #include file, you would instead guard all the #include instances.]
Refer to the “Project Defines” page at visualmicro.com for how to define a preprocessor symbol and its value. [Via: Tools > Options > Visual Micro > Compiler > Show Build Properties]  Also see  How do I add additional compiler switches in Visual Studio.
If necessary, you can use other tests besides #ifdef to control compilation.  The first link above shows the following example.
#if USBPORT > 3
....your code here....
#endif

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


text:
ATmega328p simple shortcircuit button
I am trying to get a simple button (GPIO shortcircuit) to work. I have chosen Pin D0 as input and Pin D7 as output. It works fine in an Arduino sketch but I can't get it to run in pure C. What am I doing wrong? I bet I got the bits all wrong...
My code:
DDRD = 0b11111110; // set all port D pins to Output besides pin 0, which is set to input
PORTD = 0b11111111; // set all D pins to WRITE / PULL-UP
int a = PIND & 1; // a is 0 or 1, depending on whether pins D0 and D7 are physically connected

It doesn't work though, a is never zero, whether the pins are connected or not.
Here is my complete code sample, where the on board LED depends on my pins connection state:
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
 DDRB |= _BV(DDB5);
 DDRD = 0b11111110;
 PORTD = 0b11111111;

     while(1) {
        int a =  PIND & 1;
        if(a != 0)
             PORTB |= _BV(PORTB5); // blink on
         else
             PORTB &= ~_BV(PORTB5); // blink off
         _delay_ms(1000);
    }
}

You wired a pushbutton between digital 0 (PD0) and GND, right?

GND is not involved. I put a direct wire between PD0 and PD7. Is that wrong? It works in Sketch.

Yes, it's wrong, you will always read HIGH.

Pin D7 is HIGH, so if the pins are connected you read HIGH. If they are disconnected you will still read HIGH because you enabled the pull-up resistor. Set D7 to LOW instead. That way you can differentiate between connected and disconnected.

Setting pin D7 to 0 makes my contraption work. I don't understand it though, I thought I could imagine it like this: Setting D7 to High/1 would make it pour out power and setting D0 to read and reading it's value would tell me whether power is pouring in...

The problem here is you set pull-up on D0. So even if button is not pressed it will be at high state because of pull-up. You would need pull-down for this to work (Arduino does not have it).
The pullups are useful if you want to connect pin to GND when button is pressed. When button is not pressed it will have defined state (HIGH because of pull-up) and when pressed it will be pulled LOW by button. You can imagine pull-up as a resistor to Vcc.
So for this to work I would put the other end of button to GND and it will work (One end to D0, second on GND). Condition in code should be altered (a == 0) but otherwise all can be the same.
Other option is to connect external resistor in range 1K-100K Ohm between pin D7 and GND and turn off pull-up in code. That resistor would serve as pull down.
Just one more note. If you are not using other pins it is the best to leave them as inputs. Setting an "unused" pin as output and setting it to HIGH can damage the pin if you accidentally connected it to GND (because in previous sketch you experimented something).

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


text:
How do I (easily) power a 5 V 3-pin fan?
I have a 5 V 3-pin fan. I want to be able to:

power it from an Arduino Uno or a Seeeduino Lotus board, and, ideally;
be able to change its speed.

Most resources I can find on the web explain how to connect a standard 12 V fan and moreover complicate the thing by explaining how to get the speed of a fan or to control multiple fans. This is way too complex for me.
If my understanding is correct, I can't just connect a fan to analog output pins, because the absolute max power per pin is 40 mA (recommended: 20 mA), while the fan uses 100 mA.
Instead, I have to somehow connect two of the three pins of the fan to an external power, and use the third pin to control the speed. Am I supposed to use the ground and 5 V pins situated on the left side of the board above ANALOG IN?
If not, what are my other options? The board is powered by an USB cable, and I see no way to split the power at this level between the board and another device without running a risk of damaging the board.

You are correct in your assumption that you can not power a fan from an Arduino directly.
Use a transistor, for example 2N2222 or BC548, which is switched by the Arduino, using a single pin, in order to provide sufficient current to the fan.
Such as this simple circuit (note that the 12V supply would be 5V in your case):

Source: Driving a PC fan - transistor with or without an optocoupler?1
However, as chrisl has pointed out, you fan has three pins and not two. The above circuit will only work for a two pin fan. In your case, for the reasons stated in Chrisl's answer, one pin goes to 5 V supply, one to GND and then third goes directly to the Arduino - let's say pin 3. Then you can use the code below.
Assuming that the fan is connected to pin 3, then the code will look like this:
const int fan = 3;

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

void loop() {
  int fanSpeed = 255;
  analogWrite(fan, fanSpeed);
}

This will run the fan at full blast. However, you can thereafter modify your code to vary the value of fanSpeed.
Furthermore, by reading an analog input pin (let's assume that you have a potentiometer hanging off A0), using analogRead(), you can use the read value to modify the value of fanSpeed directly (by dividing the value returned from analogRead() by four2 and then sending to analogWrite(), like so:
  int potPin = A0;
  fanSpeed = analogRead(potPin)/4;
  analogWrite(fan, fanSpeed);

or even more succinctly, do away with fanSpeed completely and use:
  int potPin = A0;
  analogWrite(fan,analogRead(potPin)/4);

1 Note that the code in the link in incorrect as it attempts to write values greater than 255 using analogWrite(). As stated here, Arduino reference - analogWrite(), analogWrite() takes values of 0-255, whereas analogRead() returns values of 0-1023
2 See the loop() function in Arduino reference - analogWrite() for another example.

The OP has a 3 pin fan for 5V, not 12V. The third pin is already connected internally to a driver (propably a MOSFET), which can be driven with PWM. So the extra MOSFET is not needed here.

@chrisl - ah yes, you are quite right. I read the question in too much of a hurry. Your answer is more correct. I shall modify mine to make note that the voltage is 5 and not 12V. Thanks

Sorry, but command back >.< As VE7JRO pointed out these fans are different than the normal stock fans in that the third pin is actually the pin, which reports back the RPM. Didn't knew that, but we are always learning. I will delete my answer, since it is false. Yours is correct.

@chrisl - eh? Oh dear. I am a bit busy now to understand. Please undelete your answer, as it is probably useful, and I want to read it again anyway.  You can always delete it later - if need be. You were right about outputting 255 and not 1023 anyway. :-)

fyi: Fans like this are often brushless, which already have an internal "pwm" controller. You cannot control these by an external pwm signal, or at least it's speed is a bit unstable/unpredictable.

@ctrl-d - ok thanks. Does that mean that they control their own speed? That is to say that you just connect the power and ground and let it do the rest? TBH, it would appear that without a clear specification (which the product's link does not provide) it is quite difficult to tell.

Yes they control their own speed by having hall sensors to detect the position of the rotor and apply voltage to a specific coil just at the right time. If your pwm signal is low at that moment, it doesn't work. The speed can be controlled by the analogue voltage in these motors.

EDIT:
As VE7JRO pointed out the fan you are using does not have a native PWM pin. The third pin is actually reporting back the RPMs of the fan. So you need to follow Greenonline's answer by using a MOSFET. For now I will leave my answer here for reference. If wanted I will delete it later.

A 3-pin fan is controlled like a servo. The current for actually driving the motor flows through the power pins (5V and Ground). The third pin takes a PWM (pulse width modulation) signal to determine the wanted fan speed. This is just a signal line, there is only very little current flow, so that the Arduinos pin will not be damaged. So the motor driver is already included.
From the programming side you can use analogWrite(), which outputs a PWM signal at one of the PWM-capable pins. The speed of the fan is controlled via the duty cycle of the signal. 100% (value of 255 for UNO) means full speed, 0% (value of 0) stops the motor.
About the power supply: Since your fan uses 100mA at full speed (I assume), it is still possible to power it over the 5V pin of the Arduino. You can source about 500mA over it (including the current for the Arduino itself). When sourcing higher currents over the USB plug, the polyfuse will be fried. This is the value for the UNO r3. A Nano can source only 200mA, because the diode will be fried.
So be carefull how much current you draw from the 5V pin of the Arduino. Or, if you have greater current requirements you have to supply an extra voltage to drive the fan.

The 3rd pin on this particular fan may be a RPM speed signal, not a PWM input signal. See: https://noctua.at/en/support/faq/general-faqs/category/Fans and look for "What pin configuration do Noctua 5V fans use?" on the page.


text:
Regarding Arduino Mega hardware serial
I have a doubt interfacing with fingerprint module (R305) with the Arduino Mega.
I have been able to interface it to Arduino Uno before but not Arduino Mega so far.
I have used the Mega's hardware Serial1 pins 19 (Rx) and 18 (Tx) pins.
However, I am unable to get output from the module. How do I connect hardware serial and what is a sketch to do this?

Try Pin digital pins 0 (RX) and 1 (TX), as they also should be Serial0 on ArduinoMega (PWM 0 and 1)
see:
https://www.arduino.cc/en/Reference/Serial
The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX). To use these pins to communicate with your personal computer, you will need an additional USB-to-serial adaptor, as they are not connected to the Mega's USB-to-serial adaptor. To use them to communicate with an external TTL serial device, connect the TX pin to your device's RX pin, the RX to your device's TX pin, and the ground of your Mega to your device's ground.


text:
Arduino Leonardo as USB Keyboard with WiFi module
I have two PCs: the first is connected to the Arduino via WiFi, this will instruct the Arduino what keys to send, and the second PC is connected to the Arduino via USB that will act as a USB Keyboard for the PC to receive keystrokes. Is it possible to use Arduino Leonardo as a USB Keyboard connected to a PC with WiFi module connected to another PC? Do I need other components or modules for this to work?
I have searched the possibility of keystrokes and WiFi connection as separate projects but can't seem to find a project that has this scenario.
I also consider using Teensy with WiFi module if it is feasible. If this is not possible, are there any workarounds? Or other devices I can use? Thanks in advance.
EDIT: I am also checking Raspberry Pi Zero as an alternative. Is the project more probable with this or is it better to stick with Arduino?

Its always very unlikely that someone will have done exactly the same project as you, which is why you need to break it down.

You want to talk to an Arduino over Wifi.
You want he PC to send commands to the Arduino.
You want to make the Arduino act as a keyboard.

I know each of those three parts in on this site, so that should help answer a lot of questions on how to do it, but obviously some of the solutions may conflict so you'll have to discard them.

You can use an ESP8226 - the Arduino talks to it via serial (software serial).
You will need an application (c# will be easiest for Windows) that will send data to the Arduino.  You need to design and implement a protocol, using REST may be a good idea.
I've never done it and don't know how, but I think I read there is a HID Library (Human Interface Device aka Keyboard or rat) and that makes thinks easier.

As to what hardware you could use there may well be performance constraints, that affect what hardware you can use.  I suspect the lower spec Arduiano's may introduce a lag that may not be acceptable.  Since you want to do it over Wi-Fi, you might want to have a look at the ESP8226, which can be programmed like an Arduino and has native Wi-Fi.  I'm not sure if you can use it as a HID though.

Further to what @CodeGorilla says:

You don't need SoftwareSerial on the Leonardo - the UART pins 0 and 1 are independent of any other hardware and can be used directly without any interference.
The Arduino IDE has Keyboard examples for the Leonardo built in and full software support for the USB interface acting as HID is built in to the API. No need for any extra libraries on that front.
The ESP8266 has no USB interface. It may be able to bit-bang it, but I don't think anyone has written software to do that (it's a horrible thing to do anyway).

So you would use pins 0/1 to talk to an ESP8266 which would be your WiFi interface. The Leonardo can directly talk "keyboard" with the wired PC.
A better choice of host board may be the Pro Micro 3.3V since it runs at the same voltage as the ESP8266 so you don't have any issues of logic level translation. True, it runs at half the speed of the Leonardo, but you're hardly doing any intensive processing here.


text:
How to pass variables to custom callback functions
I want to use the Ticker library of the ESP8266 Arduino core to (asynchronously) delay the switch of a pin to a desired state like below. I am not sure about the "here is" function definitions and I am having a hard time to find some documentation. Please have a look at what I tried so far:
#include <Ticker.h>

Ticker change_pin;

...

    uint8_t desired_state = 1;
    ...
    change_pin.attach_ms(100, [](uint8_t state_to_change_to){
        if( digitalRead(PIN) != state_to_change_to ) {
            digitalWrite(PIN, state_to_change_to);
        }
        else {
            change_pin.detach();
        }
    }, desired_state);

But the compiler's yelling:
espIKEA:145: error: no matching function for call to 'Ticker::attach_ms(int, toogle_light(uint8_t)::__lambda0, uint8_t&)'

   }, des_state);

               ^

...

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:45:7: note:   candidate expects 2 arguments, 3 provided

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:62:7: note: template<class TArg> void Ticker::attach_ms(uint32_t, void (*)(TArg), TArg)

  void attach_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg)

       ^

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:62:7: note:   template argument deduction/substitution failed:

C:\Users\USER\Documents\Arduino\Scratch\pintest\pintest.ino:145:15: note:   mismatched types 'void (*)(TArg)' and 'toogle_light(u8)::__lambda0'

   }, des_state);

               ^

So, I am having too few knowledge to understand what to do about it. I really would like to avoid having a separate function for the callback body.
PS: Important source file can be found here: Ticker.h

The function you are trying to call is a template function:
template<typename TArg>
void attach_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg)
{
    ....
}

So, you need to tell it what type of parameter you are passing:
change_pin.attach_ms<uint8_t>(100, [](uint8_t state_to_change_to) {
//                     ^- tell the compiler about the parameter
    ....
}, desired_state);

To pass more than one parameter: Since the library only allows one parameter, I would create a struct and pass a pointer to it.
struct callback_parameter {
    int i;
    char *p;
};

Then create one of these structs and pass the address of it. You just have to make sure the struct is valid the entire time the timer is running. So either use new, static, or make it global.
callback_parameter param; // global variable

...

change_pin.attach_ms<callback_parameter *>(100, [](callback_parameter * state_to_change_to) {
    ....
}, &param);

compiles now. thank you! what about passing multiple parameters? <uint8_t, char*> ?

@milkpirate I've updated the answer.

It looks like you are trying to do a lambda function and that's a bit too modern for the Arduino compiler.
So you have:
change_pin.attach_ms(100, ????, desired_state);

Its just the ???? we need to sort, which you have:
void DoStuff (state_to_change_to)
{
    if( digitalRead(PIN) != state_to_change_to )
    {
        digitalWrite(PIN, state_to_change_to);
    }
    else
    {
        change_pin.detach();
    }
}

Now you can't just define your own function signature, it has to be either callback_t or callback_with_arg_t.  So to make your "DoSTuff" function comply with callback_with_arg_t you have to define it as:
void DoStuff (void* argument);

Which means inside you function you will have to do this:
void DoStuff (void* argument)
{
    if (argument != NULL)
    {
       const uint8_t state_to_change_to = *argument;
       if( digitalRead(PIN) != state_to_change_to )
       .... As above.

Does that make sense?
The library defines the signature of the function that acts as the call back, it has to otherwise it wouldn't be able to provide all the parameters.  void* gets around any pretence at type safe behaviour and is fine as long as you are careful to control what can get passed through those parameters.
Always remember if you are working asynchronously there is no guarantee that data will still exist when you process it, if its dynamic memory it could have been freed/deleted or variables can go out of scope.


text:
If this the way to generate a BEEP for a second
This buzzer needs to generate an audible sound for one second.  The Buzzer is inside a function that is called by a loop that continues to run. It is possible to stop the loop for this one second.  PWM to a piezo disk is what I had in mind.  The coding has been simplified to: Stating the PWM     // #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
  // set timer_0 divisor to    64 for PWM frequency of   976.56 Hz (The DEFAULT)
  // The prescaler is a 3-bit value stored in the three least significant bits of the Timer/Counter register: CS02, CS01, and CS00.
        TCCR0B = TCCR0B & B11111000 | B00000011;  // 976.56 Hz  for PIN 5
        //  TCCR0B = _BV(CS00) | _BV(CS01)
        //Register first 5 bits   B11111000  logical 'OR' Divisor  = B00000011   and stop is with: TCCR0B = 0;  Is that all that I need?      #include
      #include
      #include
      #include
      #include
      #include
      #include
    class TimingISR
    {
    public:
        TimingISR();
  char lead_char, unit_sec, tens_sec, num_min;
  int int_unit_sec, int_tens_sec, int_num_min;
  int Count_Seconds, Remainder, brightness = 4, PowerLevel;   //BRIGHT_TYPICAL = 4, BRIGHT_DARKEST = 0, BRIGHTEST = 7
  bool Colon, PointFlag;
  char data_char;
};

// these are all Clobal Variables
  int pin_Clk = 2; //  or 3 for IC2
  int pin_DIO = 3; //  or 2 for IC2
  int PIN_RELAY = 4;  // controls power on/off to 'cook'
  int PIN_Beeper = 5; // PWM beeps when finished
// Main() not included in this transmission, limit is 2 programs
// in case you recognize the above, I now have functions instead of GOTO's in the MAIN()
//*********************************************************************************
// http://www.engblaze.com/microcontroller-tutorial-avr-and-arduino-timer-interrupts/
// Arduino timer CTC interrupt example
// www.engblaze.com

// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>

//#define LEDPIN 2  will flash on & off once a second if a LED is used
Timer()
void setup()
{
    //pinMode(LEDPIN, OUTPUT);

    // initialize Timer1
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 15624;
    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);
    // Set CS10 and CS12 bits for 1024 prescaler:
    TCCR1B |= (1 << CS10);
    TCCR1B |= (1 << CS12);
    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);
    // enable global interrupts:
    sei();
}

//*********************************************************************************
ISR(TIMER1_COMPA_vect)     // once a second code    Counting down,
   void){  // can only get here if lead_ char is a 'c' or a '1' i.e. 'cook' or 'def'

       If ( Colon = On ) Colon = OFF; else Colon = ON;  //blink
       // on TM1736 4 digit 7 second LED display
    {  if  ( Count_Seconds = 0 )  // Done cooking,  Beep On for one second
// https://arduino-info.wikispaces.com/Arduino-PWM-Frequency
       // set timer 0 divisor to    64 for PWM frequency of   976.56 Hz (The DEFAULT)
        TCCR0B = TCCR0B & B11111000 | B00000011;  // 976.56 Hz  for PIN 5
// https://electronics.stackexchange.com/questions/164834/stop-timer-set-new-value-and-start-again-avr-interrupt
        TCCR0B &= ~(0 << CS00);   // set the CS02, CS01, and CS00 bits in TCCR0B
        TCCR0B &= ~(0 << CS02);
        TCCR0B &= ~(0 << CS03);
        //Write 'DonE' to the TM1736
        lead_char = 'D';  num_min = 'o'; tens_sec =  'n'; unit_sec =  'E';
        Colon = OFF; brightness = 7;//  Full Brightness // for a few seconds
DisplayAll()  // Main() has a character to number converter  // DisplayAll() has an extended Segment table
    }
     {
      if  ( Count_Seconds = -1 ) //  Beep OFF
           TCCR0B &= ~(1 << CS00);   // // clear the CS02, CS01, and CS00 bits in TCCR0B
           TCCR0B &= ~(1 << CS02);
           TCCR0B &= ~(1 << CS03);
     }
       if (  Count_Seconds < -11 )  cli();          // disable global interrupts //stop the interrupt timer
return(0);
       else
          Count_Seconds = Count_Seconds - 1  // don't restart the timer
 { ( if   Count_Seconds < -10 || Count_Seconds > 0 )
          brightness = 4; counterValue = 0; resetCounter; Count_Seconds = Count_Seconds -1
 }
 }   End of Timer
// ----------------------------------------------------

Well, does it generate one or doesn't it?   It's unlikely to be the "best" way, but why ask the question without stating if it meets you expectation or not?

Please explain, in your question, why you think that this is the way to generate a beep, and why you are asking if it is (what are your doubts)? What does it actually do, and why have you done it this way? It certainly seems a pretty low level way of achieving your goal. If you provide some explanation in your question, you will probably get some upvotes, but as it stands it is just an impressive block of code, but with no description (apart from the comments. Did you write it yourself, or did you find it on the web?

What's wrong with digitalWrite(x,HIGH); delay(1000); digitalWrite(x,LOW); ?  This seems like using a sledgehammer to swat a fly.

-1 - I see that you have attempted to edit your question, yet managed to make it even more unintelligible. Please take the time to format it correctly, so that it is readable. Sorry, I am not being mean, but please learn how to correctly present your question, using the formatting tools available in markdown, instead of hoping someone else will format it for you.

You have pasted this code together from a couple of samples, I even recognise some of it, but I think you really don't understand what its doing.
If I want to learn how to fly a plane I am not just going to jump in the pilots chair and push the throttles wide open.  Its the same with learning to code, and if you try and run this code it will do nothing.
To answer you question, no.
Try doing something really simple and annoying and wire a buzzer up to one of the pins and load this code:
static const int BuzzerPin = 5;
void setup()
{
  pinMode(BuzzerPin, OUTPUT);
}
void loop ()
{
  digitalWrite (BuzzerPin, HIGH);
  delay (500);
  digitalWrite (BuzzerPin, LOW);
  delay(500);
}

Then once you work out how that works, move on to PWM to work out how that works and then finally try interrupts (if that's what you really want).
(Oh and yes the code is virtually blink.ino which you get with the IDE.)


text:
how to send data to 15 meters with KY-005
I am using the LED KY-005 as emitter and the KY-022 as a receiver, according to their specifications they reach 18 meters.
I have performed the tests and it supports more than ten meters, however after the 6 meters the data is not received correctly. For example, I send 0xa90 but any other value except the desired one arrives at the receiver.
Here I leave the connection diagram:

This is the code that I use to send data:
#include <IRremote.h>
IRsend irsend;

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

void loop()
{
   for (int i = 0; i < 50; i++) {
     irsend.sendSony(0xa90, 12); // Sony TV power code
     delay(40);
   }
}

the link to KY-022 is invalid

you only posted 1/2 the information

The link it's ok now.

I'm sure they've tested this in special conditions to better the results, with minimal external influences. Unless you know the testing procedure, there's no way of reproducing it.

Datasheet (http://www.datasheet4u.com/datasheet/T/L/1/TL1838-OpenImpulse.pdf.html) claims minimal 10m, typical 15m receiving distance with the "L5IR = 300MA" test signal. Now if we only knew what that was..

In the emitter breakout board there is only a LED, nothing more. Comments in the linked page of the supplier states, that the 5V pin of it is not connected to anything. This means you are driving the LED directly from the Arduinos pin, which cannot provide more than 40mA. The supplier states a forward current from 30 to 60mA. You can use a small MOSFET in combination with a resistor, that limits the current to maybe 55mA, to drive the LED indirectly.
With this you won't fry the pins hardware and can provide more current, which means the LED can shine brighter. If you can find out, what LED is actually used for this board, you can refer directly to its datasheet. I couldn't find a part number at the site.


text:
How can I update global variable within a loop from outside the loop?
I have this code, but its not working. If I type "ReportFRQ 1" (or 0) it reports back that FrqON variable has changed but the behaviour of the loop doesnt. Basically I am trying to switch parts of the loop on and off using variables, which are updated by serial command.
The main body of the code was kindly provided by another answer as a way of commanding the arduino remotely with custom commands. I can get the arduino to do various things, but updating the behaviour of the loop by activating and deactivating different variables does not seem to work...
Any ideas? Thanks
#include <avr/pgmspace.h>
#include <FreqCounter.h>

#define BUF_LENGTH 128  /* Buffer for the incoming command. */

unsigned long int frq;
unsigned int frqON;

static bool do_echo = true;

/* Execute a complete command. */
static void exec(char *cmdline)
{
char *command = strsep(&cmdline, " ");

if (strcmp_P(command, PSTR("help")) == 0) {
    Serial.println(F(
        "echo <value>: set echo off (0) or on (1)\r\n"
        "freq: reports current frequency"
        ));
} else if (strcmp_P(command, PSTR("echo")) == 0) {
    do_echo = atoi(cmdline);
} else if (strcmp_P(command, PSTR("freq")) == 0) {
       FreqCounter::f_comp= 8 ;             // Set compensation to 12
       FreqCounter::start(10);            // Start counting with gatetime of 100ms
       while (FreqCounter::f_ready == 0)         // wait until counter ready
       frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
} else if (strcmp_P(command, PSTR("ReportFRQ")) == 0) {
       int frqON = atoi(strsep(&cmdline, " "));
       Serial.println(frqON);

} else {
    Serial.print(F("Error: Unknown command: "));
    Serial.println(command);
 }
 }

 void setup()
 {
Serial.begin(57600);
Serial.println("Frequency Counter");
}

void loop() {

/* Process incoming commands. */
while (Serial.available()) {
    static char buffer[BUF_LENGTH];
    static int length = 0;

    int data = Serial.read();
    if (do_echo) Serial.write(data);
    if ((data == '\b' || data == '\177') && length) {  // BS and DEL
        length--;
        if (data == '\177') Serial.write('\b');
        Serial.write(" \b");
    }
    else if (data == '\r') {
        if (do_echo) Serial.write('\n');    // output CRLF
        buffer[length] = '\0';
        if (length) exec(buffer);
        length = 0;
    }
    else if (length < BUF_LENGTH - 1)
        buffer[length++] = data;
 }

 if (frqON = 1) {
        frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
 }

    /* Whatever else needs to be done... */
 }

while (FreqCounter::f_ready == 0) If that is supposed to be a loop with no body you need while (FreqCounter::f_ready == 0); Or, to make it even more clear: while (FreqCounter::f_ready == 0) /* noop */; Either way, you need the semi-colon or empty braces: while (FreqCounter::f_ready == 0) {}

Sorry, can you please elaborate what effect that would have upon my code? If it can make it better obviously I want to but I would like to learn more - as this seems to work with the changes in the answer below... Thanks in advance

The next line frq=FreqCounter::f_freq; will get executed each iteration of the while loop - it will be the body of the while loop. In this case, there may be no side-effects, but that may not always be the case. Also, if the condition FreqCounter::f_ready returns true on the first iteration, that line will never be executed.

You have multiple problems here. First one:
You have a global variable:
unsigned int frqON;

However in your exec function you're creating a variable of the same name and writing to it. This doesn't change the global variable.
else if (strcmp_P(command, PSTR("ReportFRQ")) == 0) {
       //creates new local variable "frqOn" which overshadows global variable
       int frqON = atoi(strsep(&cmdline, " "));
       Serial.println(frqON);
}

To solve this and change the global variable, simply omit the int decleration.
Also your if check is wrong:
if (frqON = 1) {
        frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
 }

When you do if(frqOn = 1) you set the variable frqOn to 1. You however want to compare the values, i.e. use the comparison operator ==.

Many thanks for looking at my code - all fixed now thank you greatly!
I have taken onboard your tips and will apply them going forward (as I am only learning arduino, I am a hardware guy / engineer trying to branch out and digitise his projects)
Thanks again :)


text:
attiny85 reset itself instead of wakeup procedure
I have a digispark attiny85, and I am using SLEEP_MODE_PWR_DOWN to sleep, and wake-up with external interrupt on pin2. I am trying to count number of interrupts received with the code below.
Problem is on every LOW signal on pin2, attiny85 reset (restart) itself instead of processor wake-up and continue where it left. I can identify this by seeing led blink 3 times(as in setup()) on every LOW signal.
Is there a limitation on this hardware? How can I only wake-up from sleep and not reset? I appreciate if you direct me an example.
#include <avr/interrupt.h>
#include <avr/sleep.h>

//modified from http://playground.arduino.cc/Learning/arduinoSleepCode

int ledPin = 0;            // LED connected to digital pin 0
int interruptPin = 1;      // LED to show the action of a interrupt
int wakePin = 2;            // active LOW, ground this pin momentary to wake up
unsigned int counter = 0;

void setup(){
  pinMode(ledPin, OUTPUT);         // sets the digital pin as output
  pinMode(interruptPin, OUTPUT);   // sets the digital pin as output
  pinMode(wakePin, INPUT_PULLUP);        // sets the digital pin as input
  digitalWrite(wakePin, HIGH);
  counter = 0;
  //do some blinks so we can identify boot & loop
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
}

void sleepNow(){

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();                          // enables the sleep bit in the mcucr register so sleep is possible
    attachInterrupt(0, wakeUpNow, LOW);     // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
    digitalWrite(interruptPin, LOW);

    sleep_mode();                          // here the device is actually put to sleep!!

    sleep_disable();                       // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);                    // disables interrupton pin 3 so the wakeUpNow code will not be executed during normal running time.
    delay(250);                           // wait 2 sec. so humans can notice the interrupt LED to show the interrupt is handled
    digitalWrite (interruptPin, HIGH);       // turn off the interrupt LED

}

void wakeUpNow(){        // here the interrupt is handled after wakeup

  //execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
 digitalWrite(interruptPin, HIGH);
}

void loop(){
   digitalWrite(interruptPin, HIGH);
  //digitalWrite(ledPin, HIGH);            // sets the LED on
  counter++;
  delay(5000);                           // waits for a second
  sleepNow();                      // sleep function called here
}

Just a thought, shouldn't the detachInterrupt logic be in wakeUpNow method?

I don't think so Filip, in most example in internet, you can see, wakeUpNow() is optional to use. most people use it empty function.

I found this, I can confirm it is working. on digispark attiny85.
void sleepTillChg() {  // 0.02ma drain while sleeping here
    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
    PCMSK |= _BV(PCINT0);                   // Use PB0 (was PB3) as interrupt pin
    // Turn off unnecessary peripherals
    ADCSRA &= ~_BV(ADEN);                   // ADC off
    ACSR |= _BV(ACD); // Disable analog comparator

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
    sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
    sei();                                  // Enable interrupts
    sleep_cpu();                            // sleep ... Zzzz

    cli();                                  // Disable interrupts
    PCMSK &= ~_BV(PCINT0);                  // Turn off PB0 (was PB3) as interrupt pin
    sleep_disable();                        // Clear SE bit
    sei();                                  // Enable interrupts
}

ISR(PCINT0_vect) {
    // This is called when the interrupt occurs, but we don't need to do anything in it
}

credits should go
https://www.instructables.com/id/3-Minute-Game-Timer/


text:
Arduino ATmega328P works but board (Uno R3) seems broken
This is the first time I'm using my Arduino. It's an Arduino UNO R3. I have two boards. One works, but the other doesn't. I changed the ATmega328P from the broken one to the good one and it works, so I can confirm that the controller works. The issue seems to be in the board.
When I plug the board it doesn't come up either in Mac or in Windows. The LED blinks and the output pins have voltage, but it seems that it's only getting electricity from the computer, it's like the data channels don't respond. The other board works perfectly both on Windows and Mac.
I checked the logs on the Mac and nothing changes when I plug the board. It's like I'm not plugging anything.
Is there a way to reset the board only? Maybe a component was badly soldered in the factory. I can't use the warranty because I got the board last year and never used it until now.

Just to confirm - you are using the same cable with either board, right?

Try to reset the communication IC on your arduino uno. You can see the steps on this link  http://arduino.cc/en/Hacking/DFUProgramming8U2

The board doesn't even shows up in the device manager. I unplugged. @Nick I don't have the equipment to replace the chip. At least I have the ATMega chip that maybe I can use as a replacement in case the working board dies someday.

The R3 uses an ATmega16u2 in place of the FTDI. It is possible that it is not loaded, busted crystal, or it has no local power to it. It is a small SMT.
You could use your good Arduino setup as ICSP programmer to talk to the ICSP of the 16u2 to see it is alive. And if so then program it.

I can use the working board to program the chip of the broken one but I would like to know if there is a way I can test where the issue is and maybe fix the board. Without the board I can't easily use the ATMEGA for other purposes.

First setup your good working Arduino as a ISP programmer, to flash the boot loader to the suspect Arduino Board. once working, this proves your programmer. Then use avrdude to read the fuses of the suspect. If you get a response, other then 0x00 chip id. Then it likely can be programmed.

You should also check the voltages, to ensure it has proper powers. And if you got a Scope the XTAL pins to see if there is clock.

do you know where I can find instructions to do what you suggest? The board doesn't even shows up in the device manager. It only gets power, nothing else. The method you propose is an arduino to arduino or PC to arduino? because the PC to arduino is not an option.

I have a sketch, that runs on a Uno, that detects chip signatures on other boards. You can use that to verify if the other board is good.
http://www.gammon.com.au/forum/?id=11633
You just need six jumper cables, like this:

From your description it sounds more like the Atmega16U2 is not working, that is the USB interface chip, the small chip near the USB socket. You can use the same sketch and a similar interface to check that as well.

That should at least show that the chip(s) are alive and giving valid signatures.
You could use About this Mac -> System Information to see if the problem Uno is listed as some sort of USB device.


text:
error compiling for board node MCU 1.0
Arduino: 1.8.9 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Serial, 115200, 4M (3M SPIFFS)"
In file included from C:\Users\Priyaranjan Tiwari\Documents\Arduino\007mcu_php\007mcu_php.ino:3:0:

C:\Users\Priyaranjan Tiwari\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:84:9: error: 'WiFiClient' does not name a type

         WiFiClient & getStream(void)  __attribute__ ((deprecated)) ;

         ^

C:\Users\Priyaranjan Tiwari\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:85:9: error: 'WiFiClient' does not name a type

         WiFiClient * getStreamPtr(void);

         ^

C:\Users\Priyaranjan Tiwari\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:97:9: error: 'WiFiClient' does not name a type

         WiFiClient * _tcp;

         ^

C:\Users\Priyaranjan Tiwari\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.0.0\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:98:9: error: 'WiFiClientSecure' does not name a type

         WiFiClientSecure * _tcps;

         ^

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

2.0.0 is a very old version from 2015. the ESP8266HTTPClient.h then expected HTTPESP8266WiFi.h included before it in the sketch as you can see it in examples


text:
How would I give an Arduino-based product WiFi credentials?
Let's imagine I create this cool little Arduino-based (replace Arduino with any embedded system that's not a Raspberry Pi) object that does some interesting things but it needs an internet connection to retrieve some information. The object doesn't have an input interface for the user because it would be meaningless if not for the WiFi credentials insertion procedure. In my testing instance, I can just hardcode the credentials before flashing the firmware, but what if I wanted to make it a product and have every user set it up on his own network?
How was such a task handled in some commercial products with similar challenges? Or what would the best way of handling it be?


text:
exit status 1 'mySerial' does not name a type
I just can't make it work for some reason. I tried #include <SoftwareSerial.h> and I tried #include "SoftwareSerial.h". Can someone help me?
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

uint16_t buf[256];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  for(int i = 0; i < 256; i++)
    buf[i] = (uint16_t)i;
}
  mySerial.begin(4800);
  mySerial.println("Hello, world"); //printLn  L, not I

void loop() {
  Serial.write((uint8_t*)buf, 512);
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

In C and C++ we write executable code inside functions. You for some reason placed executable code outside of any functions. This is what triggered the error. What were you trying to achive by that? (In C++ some executable code can be placed outside, but this is not your case)

simple mistake mySerial.begin(4800);
  mySerial.println("Hello, world"); lines was out of void {}
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

uint16_t buf[256];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  for(int i = 0; i < 256; i++)
    buf[i] = (uint16_t)i;
   mySerial.begin(4800);
  mySerial.println("Hello, world"); //printLn  L, not I
}

void loop() {
  Serial.write((uint8_t*)buf, 512);
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}


text:
Opening and closing a hatch with different switches
I'm new to the whole Arduino thing and I'm not much of a programmer myself so I need some help...
The goal is to have 4 buttons which a person who operates it gives out different outputs from the motor connected too a hatch. The relays are connected to a hatchmotor with limit switches at both closed and fully opened positions.
My idea is like this:

button1 = activates relay 1->opens the hatch,
button2 = activates relay 2->closes the hatch,
button3 = endless loop, opens and closes the hatch,
button4 = deactivated both relay 1 and 2, and stops the loop.

My code so far:
const byte knappstangd(4); //limit switch, closed position
const byte knappoppen(5); //limit switch, open position
const byte brytareoppnalucka(6); //momentary switch for opening hatch
const byte brytarestangalucka(7); //momentary switch for closing hatch
const byte startaloop(8); //momentary switch for starting the "loop"
const byte stoppaloop(9); //momentary switch for stopping the loop.

const byte relastanga = 2; //activates relay 1 which closes the hatch
const byte relaoppna = 12; //activates relay 2 which opens the hatch

void setup()
{
    pinMode (knappstangd,INPUT);
    pinMode (knappoppen,INPUT);
    pinMode (brytareoppnalucka,INPUT);
    pinMode (brytarestangalucka,INPUT);
    pinMode (startaloop,INPUT);
    pinMode (stoppaloop,INPUT);

    pinMode (relastanga, OUTPUT);
    pinMode (relaoppna, OUTPUT);
}

void loop()
{
    if(digitalRead(brytareoppnalucka)==HIGH){       //if momentary switch brytareoppnalucka = 1 do this:
        digitalWrite (relaoppna, HIGH);             //open hatch
    }

    if(digitalRead(brytarestangalucka)==HIGH) {     //if momentary switchå brytarestangaluckan = 1 do this:
        digitalWrite (relastanga, HIGH);            //close hatch
    }

    if(digitalRead(stoppaloop)==HIGH) {             //if momentary switch stoppaloop=1 do this:
        digitalWrite (relaoppna, LOW);              //turn off relay for opening
        digitalWrite (relastanga, LOW);             //turn off relay for closing

        if(digitalRead(startaloop)==HIGH) {         //if momentary switch startaloop=1 do this:
            digitalWrite(relastanga, HIGH);         //start with closing the hatch to set a zero point

            if(digitalRead(knappstangd)==HIGH) {    //if limit switch knappstangd=1 do this:
                digitalWrite (relastanga, LOW);     //turn off Relay for closing
                delay (200);                        //wait 0,2 seconds
                digitalWrite (relaoppna, HIGH);     //turn on relay for opening
            }
            if(digitalRead(knappoppen)==HIGH) {     //if limit switch knappoppen=1 do this:
                digitalWrite (relaoppna, LOW);      //turn off relay for opening
                delay (200);                        //wait 0,2 seconds
                digitalWrite (relastanga, HIGH);    //turn on relay for closing
            }
        }
    }
}

Just to be aligned between the description and the source code, could you add what is the label of button1, button2, button3 and button4 ? Is button1 equal knappoppen(5); or knappstangd(4); ?

Yeah the buttons equals the momentary switches.
Button 1 = brytareoppnalucka
button 2= brytarestangalucka
button 3= startaloop
button 4= stoppaloop
Sry for swedish involved in programming lol, makes sense in swedish

What is the problem? 2. The switch is active high? How about your pull-down circuit?

What i'm experiencing right now is that if i push button1, the relay1 for opening turns ON as intended but keeps being turned ON for some reason... All the other switches does not work at all... not even Button 3 which simply says turn both relay1 and relay 2 OFF.

If a switch is active it gives out HIGH input to the board. (Normally open).

I'm not sure, but I think, what you need is a 4th if statement that check if none of the buttons are pressed, and turns of all the relays. Or on turning on the "open-hatch" relay, you should add a while so it waits till the end-switch is triggered, so it can turn off the relay.

For the activity of "relay1" (relaoppna), you have defined a state to be HIGH when "button1" (brytareoppnalucka) goes to HIGH, but no condition to go back to LOW. Are you expected that the "button2" (brytarestangalucka) should do that simultaneously as rising "relay2" (relastanga) to 'HIGH` ?


text:
HTTPS POST method fails in esp32
I was trying to connect with server but, I was unable to post the data. I have added the SSL key to connect with server that is happening but HTTPS POST is not. I tried the same method with http, I am able to connect with server in that case.
/* set SSL/TLS certificate */
    client.setCACert(ca_cert);
//////////////////////////////// try to connect to server again and POST the data on the cloud //////////////////////////
  if (!client.connect(host, httpsPort)) {
     Serial.println("Connection failed!");
  } else {
     Serial.println("Connected to server!");
     client.println("POST /devices/deviceData HTTP/1.1");
     client.println("Host: api.thi***i.io");
     client.println("cache-control: no-cache");
     client.println("Content-Type: application/json");
     client.println("Authorization: Bearer eyJ0e***");
     client.println("Postman-Token: b1f4e147-8d13-4a27-a1a9-b****");
     client.print("Content-Length: ");
     client.println(PostValue.length());
     client.println();
     client.println(PostValue);
  }
  Serial.print("Waiting for response ");
  while (client.available() == 0) {
     if (millis() - timeout > 50000) {
        Serial.println(">>> Client Timeout !");
        client.stop();
        return;
     }
  }

  Serial.println("Response From Server");
  while(client.available()) {
     char c = client.read();
     Serial.write(c);
  }

It should connect from my logic but I am getting server error 400.
Can I know, what can be issue here?

Still, I am getting the same issue. Bad Response  400

Is there any other method to resolve this issue?

I have fixed in my code. But, still I am getting the same issue.

I have edited into the question. I have removed client.println() and in my code also. But, still I am getting BAD response from the servre. Is there any space or next line I am missing into the code?

this does not say if you were able to connect to the server .... I was trying to connect with server. But, I was unable to post the data. ....  please clarify you post

try adding another client.println(); after client.println(PostValue);

what is the actual host name? api.thi***i.io


text:
How to send data to multiple slave at a time
I have one master and three slave devices and i need to send data to all the slaves at a time.is that possible if so how to check which slave has recieved the data first

The I2C protocol implements the general call/broadcast address for this purpose. If you send data to the address 0 (zero), this is interpreted as general call by all slaves. All slaves, that can receive data, will respond by pulling the SDA line to low in the acknowledgement cycle (the timing is set up by the masters clock so all slaves will do it at the same time, thus no problem with garbled data). Note, that you cannot read from the general call address, since then all slaves might transmit at the same time. As the Atmega328Ps (the microcontroller on the Arduino Uno) datasheet states:

Note that transmitting the general call address followed by a Read bit
  is meaningless, as this would cause contention if several slaves started transmitting different data.

I think the Wire library does not do any read operations on the general call address to prevent this, so this would not block up the I2C bus.

how to check which slave has recieved the first

Not, because all slaves receive the data at the same time. The I2C bus is much like the IP protocol in this topic. A master/sender is sending out packages of data with the address of the intended target. But it is up to the slaves/receivers to decide, on which address they want to listen. So on every I2C transmission you are sending data over the bus, that could be read by all slaves. Only that in normal operation a slave will decide to only listen to the bus, when it sees it's own address (or the general call address).

In the IP protocol there is something called "broadcast address" when a packet contains this address all devices read it. You can do the same with i2c. Each slave has it's own address, but you can program them to also look for a "broadcast address" of your choosing. A single master can then send a single i2c message that will be read by all slaves at the same time.


text:
pin numbering for non-standard chips
so i replaced the mainboard in (what was) an anet a8 3d printer with a proper RAMPS setup. there was nothing wrong with it, (or at least it wasnt damaged, there are a number of severe design flaws) so i thought it might be a good start point for a remote controlled crawler/bot thing. it already has four a4988 drivers on board, plus a few mosfets and other bits which will be great for accessories (planning headlights, horn, maybe light sensor). its built around the atmega1284p, which is something of an oddball inbetween the 328 on the uno and the 2560 on the mega, but is the same product line. ive already worked out the libraries/drivers for the ch340 or whatever it is that is needed to flash code to the board,it already has already been added to the arduino ide, i have successfully flashed sketches to it before, but not my own. what im wondering is how to declare pins when im writing my own code. the bottom right of this schematic lists connections to the main chip, is it reasonably safe to assume that the digital pin numbers listed there can be used like the normally labeled headers on a standard board? how exactly are those numbers determined?

Does this answer your question? Adding a custom board to the Arduino IDE

example https://github.com/jandrassy/my_boards

Each chip uses the normal register names (like PORTB or DDRA) with the bits representing a pin. The pin numbers, that you know from other Arduinos are just referencing to them. The numbers are defined in the core for the used chip. So when you are installing the core for the used chip inside the Arduino IDE, that core also defines the pin numbers.

@Juraj a custom board file has already been made by someone, it sounds like i need to dig through those core files to find where things get enumerated or whatever the word is

not much digging. it is the variants folder. in my_boards I have a custom 1284p too

Look for a file named pins_arduino.h.

ok so what ive found is that pins are declared in a file, pins_arduino.h. for each board/chip/variant another file is added(or created, if writing your own) to the arduino hardware files. in my specific case the numbers in the graphic are consistent with those listed in the hardware file, so im good


text:
Can't push data to ThingSpeak - Status 400 Bad Request
I'm trying to push some data to ThingSpeak using the EtherCard library with the ENC28J60 ethernet module.
At the moment I'm using the exemple code that comes with the library just for tests. But no matter what I do, always receive the same reply:
REPLY recieved....
HTTP/1.1 400 Bad Request
Date: Sat, 09 Mar 2019 17:26:52 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Status: 400 Bad Request
X-Frame-Options: SAMEORIGIN
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, DELETE, PATCH
Access-Control-Allow-Headers: origin, content-type, X-Requested-With
Access-Control-Max-Age: 1800
Cache-Control: no-cache
Set-Cookie: request_method=POST; path=/
X-Request-Id: 9184d325-402d-4512-a942-e7

Code:
#include <EtherCard.h>

// Simple demo for feeding some random data to Pachube.
// 2011-07-08 <jc@wippler.nl>
//
// License: GPLv2

// Handle returning code and reset ethernet module if needed
// 2013-10-22 hneiraf@gmail.com

// Modifing so that it works on my setup for www.thingspeak.com.
// Arduino pro-mini 5V/16MHz, ETH modul on SPI with CS on pin 10.
// Also added a few changes found on various forums. Do not know what the
// res variable is for, tweaked it so it works faster for my application
// 2015-11-09 dani.lomajhenic@gmail.com

// change these settings to match your own setup
//#define FEED "000"
#define APIKEY "XXXXXXXXXXXX" // put your key here

// ethernet interface mac address, must be unique on the LAN
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x32 };
const char website[] PROGMEM = "api.thingspeak.com";
byte Ethernet::buffer[700];
uint32_t timer;
Stash stash;
byte session;

//timing variable
int res = 100; // was 0

void setup () {
  Serial.begin(9600);
  Serial.println("\n[ThingSpeak example]");

  //Initialize Ethernet
  initialize_ethernet();
}

void loop () {
  //if correct answer is not received then re-initialize ethernet module
  if (res > 220){
    initialize_ethernet();
  }

  res = res + 1;

  ether.packetLoop(ether.packetReceive());

  //200 res = 10 seconds (50ms each res)
  if (res == 200) {

    //Generate random info
    float demo = random(0,500);
    //word one = random(0,500);
    //String msje;

//    if (demo < 250){
//      msje = "low";
//    }
//    else{
//      msje = "high";
//    }

    // generate two fake values as payload - by using a separate stash,
    // we can determine the size of the generated message ahead of time
    // field1=(Field 1 Data)&field2=(Field 2 Data)&field3=(Field 3 Data)&field4=(Field 4 Data)&field5=(Field 5 Data)&field6=(Field 6 Data)&field7=(Field 7 Data)&field8=(Field 8 Data)&lat=(Latitude in Decimal Degrees)&long=(Longitude in Decimal Degrees)&elevation=(Elevation in meters)&status=(140 Character Message)
    byte sd = stash.create();
    stash.print("&field1=");
    stash.println(demo);
    //stash.print("&field2=");
    //stash.print(one);
    //stash.print("&field3=");
    //stash.print(msje);
    stash.save();

    //Display data to be sent
    Serial.println(demo);

    // generate the header with payload - note that the stash size is used,
    // and that a "stash descriptor" is passed in as argument using "$H"
    Stash::prepare(PSTR("POST /update HTTP/1.1" "\r\n"
      "Host: $F" "\r\n"
      "Connection: close" "\r\n"
      "X-THINGSPEAKAPIKEY: $F" "\r\n"
      "Content-Type: application/x-www-form-urlencoded" "\r\n"
      "Content-Length: $D" "\r\n"
      "\r\n"
      "$H"),
    website, PSTR(APIKEY), stash.size(), sd);

    // send the packet - this also releases all stash buffers once done
    session = ether.tcpSend();

 // added from: http://jeelabs.net/boards/7/topics/2241
 int freeCount = stash.freeCount();
    if (freeCount <= 3) {   Stash::initMap(56); }
  }

   const char* reply = ether.tcpReply(session);

   if (reply != 0) {
     res = 0;
     Serial.println(F(" >>>REPLY recieved...."));
     Serial.println(reply);
   }
   delay(300);
}

void initialize_ethernet(void){
  for(;;){ // keep trying until you succeed
    //Reinitialize ethernet module
    //pinMode(5, OUTPUT);  // do notknow what this is for, i ve got something elso on pin5
    //Serial.println("Reseting Ethernet...");
    //digitalWrite(5, LOW);
    //delay(1000);
    //digitalWrite(5, HIGH);
    //delay(500);

    // Change 'SS' to your Slave Select pin, if you arn't using the default pin
    if (ether.begin(sizeof Ethernet::buffer, mymac, SS) == 0){
      Serial.println( "Failed to access Ethernet controller");
      continue;
    }

    if (!ether.dhcpSetup()){
      Serial.println("DHCP failed");
      continue;
    }

    ether.printIp("IP:  ", ether.myip);
    ether.printIp("GW:  ", ether.gwip);
    ether.printIp("DNS: ", ether.dnsip);

    if (!ether.dnsLookup(website))
      Serial.println("DNS failed");

    ether.printIp("SRV: ", ether.hisip);

    //reset init value
    res = 180;
    break;
  }
}

I searched the site and saw that the Bad Request is related to syntax error.
Any attempt I made was in this part of the code, almost every change I tried was on the first line:
Stash::prepare(PSTR("POST /update HTTP/1.1" "\r\n"
      "Host: $F" "\r\n"
      "Connection: close" "\r\n"
      "X-THINGSPEAKAPIKEY: $F" "\r\n"
      "Content-Type: application/x-www-form-urlencoded" "\r\n"
      "Content-Length: $D" "\r\n"
      "\r\n"
      "$H"),
    website, PSTR(APIKEY), stash.size(), sd);

I think that is the part responsible for the URL syntax.
I tried to change the POST for GET, to put all the URL on the first line, something like: "POST https://$F/update?api_key=$F HTTP/1.1"(that one I saw on StackOverflow).
But I don't have any more idea where is the problem.
To confirm that the channel is OK I tried to send data directly via URL, and everything is OK.
URL Exemple:
https://api.thingspeak.com/update?api_key=XXXXXXXXXXXXX&field1=0

I don't know what to do to get it work. Thanks for your help!

Please add info/link to the library and the example. Also high-light any changes you might have done.

If your GET request https://api.thingspeak.com/update?api_key=XXXXXXXXXXXXX&field1=0 works, but the POST request is not, the only thing that could be incorrect is your payload sent by POST request. that is, the value of sd. If you print it out, what do you see?

Generates a float like 307.0. I tested the URL with this value and worked. I tested the URL manually, just put the URL on the browser. When i changed on the code to GET doesn't worked too


text:
Servo doesn't move with fingerprint
I've a project which i need to make a door open and close using the fingerprint.
I've successfully made fingerprint works just fine it reads and confirm the fingerprints stored in it but the servo doesn't act at all to my confirmed finger print.
    #include <Servo.h>
    #include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
Servo myservo;

int getFingerprintIDez();
int pos = 0;
int id ();
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino (WHITE wire)
SoftwareSerial mySerial(A12, A13);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

// On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
//Adafruit_Fingerprint finger = Adafruit_Fingerprint(&Serial1);

void setup()
{
myservo.attach(10);
while (!Serial); // For Yun/Leo/Micro/Zero/...

Serial.begin(9600);
Serial.println("Adafruit finger detect test");

// set the data rate for the sensor serial port
finger.begin(57600);

if (finger.verifyPassword()) {
Serial.println("Found fingerprint sensor!");
} else {
Serial.println("Did not find fingerprint sensor :(");
while (1);
}
Serial.println("Waiting for valid finger...");
}

void loop() // run over and over again
{
getFingerprintIDez();
delay(50); //don't ned to run this at full speed.

}

uint8_t getFingerprintID() {
uint8_t p = finger.getImage();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image taken");
break;
case FINGERPRINT_NOFINGER:
Serial.println("No finger detected");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_IMAGEFAIL:
Serial.println("Imaging error");
return p;
default:
Serial.println("Unknown error");
return p;
}

// OK success!

p = finger.image2Tz();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image converted");
break;
case FINGERPRINT_IMAGEMESS:
Serial.println("Image too messy");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_FEATUREFAIL:
Serial.println("Could not find fingerprint features");
return p;
case FINGERPRINT_INVALIDIMAGE:
Serial.println("Could not find fingerprint features");
return p;
default:
Serial.println("Unknown error");
return p;
}

// OK converted!
p = finger.fingerFastSearch();
if (p == FINGERPRINT_OK) {
sweep();
Serial.println("Found a print match!");
} else if (p == FINGERPRINT_PACKETRECIEVEERR) {
Serial.println("Communication error");
return p;
} else if (p == FINGERPRINT_NOTFOUND) {
Serial.println("Did not find a match");
return p;
} else {
Serial.println("Unknown error");
return p;
}

// found a match!
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
}

// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
uint8_t p = finger.getImage();
if (p != FINGERPRINT_OK) return -1;

p = finger.image2Tz();
if (p != FINGERPRINT_OK) return -1;

p = finger.fingerFastSearch();
if (p != FINGERPRINT_OK) return -1;

// found a match!
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
return finger.fingerID;

}

void sweep()
{
 for(int pos = 0; pos < 180; pos += 25)  // goes from 0 degrees to 180 degrees
 {                                  // in steps of 1 degree
   myservo.write(pos);              // tell servo to go to position in variable 'pos'
   delay(122);                       // waits 122ms for the servo to reach the position
 }

 for(int pos = 180; pos>=1; pos-=25)     // goes from 180 degrees to 0 degrees
 {
   myservo.write(pos);              // tell servo to go to position in variable 'pos'
   delay(122);                       // waits 122ms for the servo to reach the position
 }
}

please use the {} button to format your code

you said that you verified the operation of the fingerprint reader .....  did you also verify the operation of the servo? ..... what kind of a servo are you using?


text:
Digispark ATtiny 85 - not recognised as HID device
I am trying to create auto-username-writer with Digispark ATtiny 85. I have a pretty simple sketch:
#include <DigiKeyboard.h>
void setup() {
}
void loop() {
    DigiKeyboard.sendKeyStroke(0);
    DigiKeyboard.delay(100);
    DigiKeyboard.sendKeyStroke(76, MOD_ALT_RIGHT | MOD_CONTROL_LEFT); //ctrl+alt+del
    DigiKeyboard.delay(2000);
    DigiKeyboard.print("username");
    DigiKeyboard.sendKeyStroke(0x2B); //tab

    for (;;) {}
}

When I upload the code via Arduino IDE into the device (Board: Digispark (Default - 16.5MHz), it finishes successfully, it is recognised as a HID device and immediately performs all the tasks. But when I disconnect it and connect it again (to my PC or any other PC) it is recognised as Digispark Bootloader and does not do anything.
I have tried it in Arduino IDE 1.8.8 and in Arduino IDE 1.6.5 and I have no idea why it is only recognised right after upload. I have two ATtinys and both do the same behaviour.
Can someone help me, please?
EDIT:
I tried adding digitalWrite(1, HIGH); to detect, whether the sketch even runs and it turned out it does not even run (except after the upload)...

are you waiting 5 seconds for the sketch to start executing?

Well, I have tried adding something like a 4-second delay at the start and I even let the ATTiny be in USB for some time. Neither helped...

the title of your post indicates that you have not identified the problem correctly, so it is difficult to find a solution on the internet  ..... not recognised as HID device is not the problem ....... the problem is that the loaded program does not start after the digispark is reset  .... the digispark enters program loader mode and does not continue to the loaded program after a timeout

You are probably right. At time of writing I did not know the sketch is not executing. I tried googling the problem in regard what you have written, but was also unsuccessful - did not find anything I can use.

After five seconds, which is when the bootloader should switch to running your code, how does it show up in the list of usb devices (lsusb in Linux, Device Manager in Windows, etc.)
The original Digispark was a bit temperamental when plugged into USB 3 ports. If you are plugging it into one, try using a usb2 hub and plugging it into the hub instead.
Also, did you get this from Digistump, or is it a knock-off?

I have tried several USB ports (2 and 3) and neither worked even after extended period of time.  Whole time it is shown in device manager as Digispark bootloader. Unfortunately I bought it in a local Czech e-shop, so I have no idea whether they are selling clone or original. Is there a way to detect whether it is original or clone?

I just run your sketch on a digispark, and it behaved as expected; at this point the easiest thing to do is to just get another little digispark and see if that one works. It's open-source hardware, so chances are that unless you ordered it from digistump directly, it's a knockoff.

I hope I'm not too late here, but I believe you may need to update the bootloader.  Could you try the instructions here? https://www.iot-experiments.com/micronucleus-bootloader-upgrade/  I happened to be reading through this guide: https://hackernoon.com/low-cost-usb-rubber-ducky-pen-test-tool-for-3-using-digispark-and-duck2spark-5d59afc1910 and the troubleshooting section there sounds like the issue you're having.

Hi, thank you for your answer. I tried upgrading the firmware, but unfortunately without any success, here is micronucleus.exe output: https://pastebin.com/2SsexNQ4 .

Same here,
I am new user so not saying this is the correct way.
I now includes "digiKeyboard.update();" and "digiKeyboard.delay(1000);". both at top ,both to trigger usb signal many many times to the host.
the "digiKeyboard.sendKeyStroke(0);" does not work every time.


text:
How to create an inverted PWM on the Due via software
Hello I am i need of a piece of code that lets me invert a PWM signal of two PWM pins on the due. Example D1 will be 101010 and D2 will be 010101. Is it possible?
Im pretty limited in my options because, doing it externally is not an option because there will be a time where a change in mode is needed and both pins will be sending signal independently. Manually pulling the pins High and Low is also not an option for me because this will make the code blocking other codes.

inverted 75% is same as noninverted 25%

@jsotola i am having trouble visualizing that, although they would be opposing but the frequency would not match, the 25% would miss one cycle of the 75% . Am i missing something?

take a piece of paper and a pencil ... dreaw 10 cycles of 25% PWM waveform ... rotate the paper upside down ... maybe I'm missing something

Image. The above signal in the image is 75% and the one at the bottom is 25%. the 25% is missing one cycle of the 75%

this is PWM ... https://www.nightsea.com/wp-content/uploads/2017/12/PWM-diagram.jpg

Yeah i got a wrong understanding of pwm, im sorry. New Image although inverted but i have to phase out by a little bit. Now that would be a different approach, i guess which ever is easier to do, both i think would involve direct register manipulations

Let us continue this discussion in chat.

you could use an xor gate to invert the PWM signal. this allows you to   easily un-invert the signal with another GPIO pin feeding the gate's other input.

@dandavis well that is an approach i can go if i cant find a way to do in via software.  with everything i have read so far, I believe that it can be done via software, getting there is ust a little bit difficult

Not using the Arduino API, no. But you can by direct manipulation of the SAM3X8E registers.
You should study section 38 of the datasheet, where it mentions in the list of facilities:

Independent Complementary Outputs with 12-bit Dead-Time Generator (Also Called Dead-Band or Non-Overlapping Time) for Each Channel

Register manipulation is way over me, hopefully there is some examples.

@Jack There probably are, but probably not around here. The Atmel forums might be good though.


text:
RP2040 RTC alarm or similar function
I have a rp2040 board using Earl E. Philhower core. I would like to use the rtc functions just like the one mentioned in the sdk. Especially the alarm function which is critical in my project.
Supposedly from what i know you have access to all the functions in the sdk on the arduino IDE but when i tried out the example in the sdk it would not compile saying that rtc functions are not declared
char datetime_buf[256];
char *datetime_str = &datetime_buf[0];

    datetime_t t = {
            .year  = 2020,
            .month = 06,
            .day   = 05,
            .dotw  = 5, // 0 is Sunday, so 5 is Friday
            .hour  = 15,
            .min   = 45,
            .sec   = 00
    };

void setup() {
    Serial.begin(9600);
    Serial.println("Hello RTC!");

    rtc_init();
    rtc_set_datetime(&t);
}

// the loop function runs over and over again forever
void loop() {
        rtc_get_datetime(&t);

        Serial.println(datetime_str);
        sleep_ms(100);             // wait for a second
}

Earl E. Philhower comes with a Time sketch example but problem is i could not find a documentation if a alarm like function exist
/* Simple demonstration of setting and printing the current time */
/* The initial time will need to come from an RTC, NTP, or user */

/* Released to the public domain by Earle F. Philhower, III <earlephilhower@yahoo.com> */

#include <time.h>
#include <sys/time.h>

void setup() {
  Serial.begin(115200);
  delay(5000);
  struct timeval tv;

  tv.tv_sec = 1611198855; // Jan 21, 2021  3:14:15AM ...RPi Pico Release;
  tv.tv_usec = 0;
  settimeofday(&tv, nullptr);
}

void loop() {
  time_t now;
  char buff[80];

  time(&now);
  strftime(buff, sizeof(buff), "%c", localtime(&now));
  Serial.println(buff);
  delay(1000);
}

Did you #include "hardware/rtc.h" when trying to use the RTC from the SDK?

@Majenko Yes, it could not find the library. fatal error: hardware/rtc.h: No such file or directoryResolveLibrary(hardware/rtc.h)

You can try to use my RP2040_RTC Library, especially this RP2040_RTC_Alarm example.
Both ArduinoCore-mbed and Earle Philhower arduino-pico cores are supported.

This looks nice, it even has example on how to get time via, ethernet which is one of the reason for the alarm, i need to update the time every 6 hours.

by the way , is this a hardware implementation of RTC?

Yes. It's the RP2040 hardware RTC, as mentioned in section 4.1.21. hardware_rtc of Raspberry Pi Pico-C/C++ SDK

Cool, thank you for making the library :)

I have a question about alarms, if the alarm goes off it triggers an interrupt right? and just like how standard interrupts work, it will stop whatever its doing and process that interrupt right?

Yes. Check the ISR code here  RP2040_RTC_Alarm.ino#L54-L58. The ISR just sets a flag and flag is read and processed in loop() at RP2040_RTC_Alarm.ino#L179-L186

Another question, how many alarms can be set at a given time?