text:
Arduino-compatible micro-controller with both I2C and CAN
I am looking for a controller that works with Arduino (i.e. there is official or third-party support for the controller in the Arduino IDE and core libs) and has both built-in CAN and I2C buses. I was looking at the ATMega automotive series (16M1, 32M1, 64M1, 32C1, 64C1) but it does not mention I2C/TWI in the datasheet at all.
(I know I can bitbang I2C, I know there is MCP2515 for CAN over SPI.)
Thanks!
EDIT: The application in mind is a bridge between a few I2C sensors and CAN, no complex logic. High performance is not necessary, plus it will drive costs upwards.

the ESP32 comes to mind. you can disable wifi/bt to save power and make it more like a mega

Thanks, @dandavis, ESP32 is too much :) I added a note on looking for rather low-performance chips.

Is i2c to CAN conversion possible on microcontroller which has both CAN and I2C.(TM4C123GXL)...

Many options come to mind:

Bluepill board
Literally any board with I2C and CAN buses from the STM32 series, as searchable on their website (https://my.st.com/content/my_st_com/en/products/microcontrollers.html)
ESP32

A Bluebill board is programmable with mbed, STM32HAL (CubeMX) and Arduino, all of which have either CAN libraries for the CAN peripheral or have it even built-in in the OS (mbedos).
The Bluepill board is extremely low cost ($1.81 with free shipping from aliexpress) and features an STM32F103C8 microcontroller with 128kB Flash and 20kB RAM. Its peripherals include two I2C and one CAN bus.

Infos & Datasheet: http://www.st.com/en/microcontrollers/stm32f103c8.html, http://wiki.stm32duino.com/index.php?title=Blue_Pill
For flashing and debugging the chip you should have one cheap ST-Linkv2 clone (~3$ from china).
For programming environments you can use:

Arduino IDE (STM32Duino Arduino Core for STM32F1/F3/F4 chips: http://wiki.stm32duino.com/index.php?title=Boards_Manager_package)
PlatformIO, more general purpose and more powerful (https://platformio.org:443/boards?count=15&filter%5Bmcu%5D=STM32F103C&page=1&sorting%5Bname%5D=asc)

As frameworks you can use:

Arduino (see above)
ARM mbedos (builds upon STM32HAL, natively supported by PlatformIO)
STM32HAL (e.g. with project files for an IDE generated by STM32CubeMX)

Documentation references:

https://os.mbed.com/docs/v5.8/reference/can.html
https://www.st.com/resource/en/user_manual/dm00154093.pdf (Chapter 8)
https://github.com/Locoduino/Commanders

8 Bit microcontrollers from STM8AF series have a few micros with 1 I2C and 1 CAN bus: See http://www.st.com/en/microcontrollers/stm8af-series.html?querycriteria=productId=SS1583

Ready buyable evaluation board: http://www.st.com/en/evaluation-tools/stm8a-discovery.html (you want the STM8AF5288 one)
The toolchain changes then, of course. See https://my.st.com/content/my_st_com/en/extended-query.html?querycriteria=productId=LN1759$$associatedTo=SS1584

Good answer. Anything 8bit, though?

@eudoxos sure, updated.


text:
Can I use my PC or Android mobile as WiFi Shield/Module for Arduino UNO?
I'm using an Arduino Uno. Currently I am using an ESP8266 WIFI module to connect to the Wifi. But is it possible to use my laptop or Android mobile as a WiFi Shield/Module? I want to connect with cloud server using the connection.
Thanks in advance.

Why would you do that? ESP8266 is generally powerful enough to deal with connection to cloud server. Also I suppose you are using ESP8266 as shield on top of Uno, which is not a efficient way of using it. The Arduino core itself can be running on ESP8266, so you may drop your Uno and run your full code on ESP8266.

you may want to take a look here on how to use esp8266 as an Arduino board: https://github.com/esp8266/Arduino

This problem can be broken into several components:
Communications channel between the Arduino Uno and the laptop or Android mobile
There are several options. The most common and probably easiest is to do serial communication over USB. The Uno has a USB-serial chip that creates a virtual COM port (VCP) on a computer when you connect the Uno to it via the USB receptacle on the board. This VCP is commonly used to upload sketches to the Uno and also to communicate with the Arduino IDE's Serial Monitor.
Another option for communications between your Uno and the laptop or Android mobile is Bluetooth. You can buy a Bluetooth module for your Uno that will allow this. This may be preferable if you need wireless communication.
Application on the Laptop or Android mobile that interprets communication with the Uno
Now you can communicate between the two devices but you need a program running on the Laptop or Android mobile to actually do something with the communication. This application will receive commands from the Uno, and make the desired interactions with the "cloud server", and perhaps respond to the Uno. You will need to have some sort of a command protocol. The details of this will be dependent on which type of communications channel you chose. There are many ways you can accomplish this and the best option will also depend on whether you will be writing this application yourself or trying to find an existing application that suits your needs.
Arduino Uno firmware
This is a sketch you will write and upload to your Uno that sends commands to the laptop or Android mobile via your chosen communications channel and handles any responses.

source: Stack Exchange

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

sort: votes


text:
Ultrasonic HC-SR04 echo and trig pins
I am doing a watch with GPS tracker project. I am using an Ultrasonic HC-SR04 sensor. I don't know where to connect the Echo and trig pins with my Arduino. Please let me know how to connect it.

To any 2 free IO pins.
To quote sparkfuns datasheet:

(1) Using IO trigger for at least 10us high level s ignal,
  (2) The Module automatically sends eight 40 kHz and  detect whether there is a pulse signal back.
  (3) IF the signal back, through high level , time of high output IO duration is  the time from sending ultrasonic to returning.
  Test distance = (high level time×velocity of sound (340M/S) / 2,

In other words you send a short pulse to trigger pin and then wait for the echo pulse and measure how long it was high. Divide the number of microseconds it was high by 58 and you have the distance in centimetres ( use 148 for inches)

You can connect them to two GPIO pins. It does not matter much which ones (probably between 2 and 12 since these are not used by other functions like the builtin led or RX/TX).
In the following example pins 9 and 10 are used:
Example
Fragment related to the pins:

The HC-SR04 Ultrasonic Module has 4 pins, Ground, VCC, Trig and Echo. The Ground and the VCC pins of the module needs to be connected to the Ground and the 5 volts pins on the Arduino Board respectively and the trig and echo pins to any Digital I/O pin on the Arduino Board.

Okay I will try sir . Another question that i want to ask is ,what is the red light indication in an arduino nano? and how to connect rx/dx from gps tracker with arduino nano ? please help me

I don't have a Nano. It's best to post it as a new question with a picture and a mark to the indicator you mean. Also the other question is best to ask as a separate question. I never worked with a GPS tracker.

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


text:
What sensor is used to judge transparency?
I want to create a system to separate between an aluminum can and a plastic bottle.
Both are lightweight, so I'm thinking of using the transparency property, meaning that the can is not transparent, but the plastic bottle is.
Will the light sensor work out?
Or would you suggest me another type of sensor I should use?

A light sensor should work. Another option would be an inductive Sensor to detect the Aluminium Can. And if you need to know if there is a Can in your sensor area you can combine it with an IR (or capacitive) Sensor, which should detect both Can types.
So it would be something like this:
if(IRdetect == true){
  if(inductive == true){
    type = alu;
  }else{
    type = plastic;
  }
}else{
  // no Can
}

Some cheap sensors as Example:

Inductive: Banggood
Infrared: Banggood

It's better never to use == true or == false, omit the true or use !.
This code can be replaced by     type = IRdetect && inductive;

A light sensor should work. If the aluminium can reflect much light, you can consider putting the light and light sensor on the same side, close together.
If not, put the light and light sensor of opposite sides so the light beam goes through the bottle.


text:
If-statement matches but doesn't give a result
I just started two weeks ago with Arduino and I'm hooked!
I got off to a good start and went through some online tutorials quite easily. Then came the RGB LED, which I couldn't get to work all of a sudden (it required putting in a color through the serial monitor, which would then be given by the RGB).
And the strange thing is, I can't get anything to work anymore that requires input through the serial monitor, where I used to get it working immediately...
I presume it's something with the if-statement, because if I remove it and just say digitalwrite HIGH to a certain pin, it works fine....
Checks I did:

Full re-install of Arduino (didn't solve it).
Check the LEDs by hooking them up to 5V directly (they all work).
Reconnecting the Arduino (didn't solve it).
Use a multimeter to measure current (there isn't, although the if-statement matches...

Here's my code. Does anybody see it? Because I don't...
Regards,
nannev (using Mac and Arduino Uno)
int yellowPin=8;
int redPin=9;
int greenPin=10;
String myLED;

void setup() {
  Serial.begin(9600);
  pinMode(yellowPin,OUTPUT);
  pinMode(redPin,OUTPUT);
  pinMode(greenPin,OUTPUT);
}

void loop() {
  Serial.println("Your color?");
  while (Serial.available()==0) {
  }

  myLED=Serial.readString();
  Serial.print(myLED); //check if the input came through correctly, which it did
  delay(1000);
  if(myLED == "yellow"){ .    //nothing happens at yellow....
    digitalWrite(yellowPin, HIGH);
    digitalWrite(redPin, LOW);
    digitalWrite(greenPin, LOW);
  }

  if(myLED == "red"){             //nothing happens at red....
    digitalWrite(yellowPin, LOW);
    digitalWrite(redPin, HIGH);
    digitalWrite(greenPin, LOW);
  }

  if(myLED == "green"){       //nothing happens at green....
    digitalWrite(yellowPin, LOW);
    digitalWrite(redPin, LOW);
    digitalWrite(greenPin, HIGH);
  }
}

check the line ending setting in Serial Monitor. 'yellow\r\n" is not equal to "yellow". you can trim the line ends with myLED.trim();

you can add Serial.print(myLED.length()); so that you can see how many characters there are in the string

"  if(myLED == "yellow"){ .    //nothing happens at yellow...." Look at the period after {. That's a Mac quirk: sometimes when you press space twice it converts it to ". " – there's no way your code is compiling as is.

@Juraj Wow, this solved it! It appeared that the length of the String was 1 character greater than the actual word. Strange though, that I had it working several times before without the Trim function. Thanks, wouldn't have come up with this myself.

@jsotola Thanks too!

the line ending in Serial Monitor is configurable. it worked without the Serial Monitor sending line end characters

The Arduino IDE uses the C and C++ programming languages.
Some string comparison basics using C:
In the C programming language, a string can be thought of as an array of 8 bit values.  One way to compare two strings is to compare each 8 bit value and consider the strings different (not equal) upon finding the first not-matching 8 bit value.  Here is an example from programmingsimplified.com:
int compare_strings(char a[], char b[])
{
   int c = 0;

   while (a[c] == b[c]) {
      if (a[c] == '\0' || b[c] == '\0')
         break;
      c++;
   }

   if (a[c] == '\0' && b[c] == '\0')
      return 0;
   else
      return -1;
}

There is a common function called strcmp() which can be used instead.  Here is another example from the same web page which uses strcmp():
#include <stdio.h>
#include <string.h>

int main()
{
   char a[100], b[100];

   printf("Enter a string\n");
   gets(a);

   printf("Enter a string\n");
   gets(b);

   if (strcmp(a,b) == 0)
      printf("The strings are equal.\n");
   else
      printf("The strings are not equal.\n");

   return 0;
}

Note that in both cases the array of strings is assumed to end with a NULL or zero value byte.  If you do not wish to follow this format you can use an alternate version of the function called strncmp() where the number of characters to be compared is passed along with pointers to the 2 strings.
Some string comparison options using C++:
There are C++ ways to compare 2 strings which make coding Arduino Sketches easier.  But C++ string manipulation usually requires more RAM.  And RAM is usually in short supply on inexpensive embedded processors.
As the code in the question is written using type String we can explore that approach. And, as there is some concern the strings may have unexpected trailing characters, we will continue to check only the necessary number of characters. In this slightly modified code example from geeksforgeeks.org string s1 is compared with string s2.  But only the first 6 characters are compared:
void compareOperation(string s1, string s2)
{
    // Compares 5 characters from index number 3 of s2 with s1
    if((s2.compare(0, 6, s1)) == 0)
        cout << "Here, "<< s1 << " are " << s2;

    else
        cout << "Strings didn't match ";
}

The number 6 was chosen because "yellow" contains 6 printable characters.  In this way, we can avoid the uncertainty of what character(s) follow the characters that make up "yellow" as received from the serial port.

the Arduino String class has == operator overloaded to compare with char*. why this complicated off-topic answer?

The "compare()" was the 1st example found. So it was used. Also, there was talk in the comments about string length and problems with different unprintable characters after the desired printable word. So I offered a solution which mitigated problems associated with unprintable characters by counting the number of characters to compare. Lastly, this is an Arduino forum. Most Arduino platforms contain a very-low-cost embedded processor with very-limited resources. So it is almost always better to control string manipulation explicitly with clearly defined string lengths using C programming.

I've changed the answer making it clear that the 1st part is C and the 2nd part is C++.  I also added text explaining that character counting in both examples was used to mitigate any differences between the 2 strings which might occur after the desired word.

all true but not an answer. the compare failed only because the Serial Monitor input did contain line ends. this as a common mistake by beginners

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


text:
Can't store time over 9 hours and 10 minutes
I am making a clock on my Arduino Uno using the time library http://playground.arduino.cc/Code/Time
I let the user set a time. Which is then converted to seconds and used in the
setTime(s);

function.
When the value is over 9:10h, the seconds evaluate to 4 294 941 360 seconds (=
1 193 039.27 hours)
A code snippet:
void timeChange() {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Change time");
  lcd.setCursor(0, 1);
  lcd.print("00:00");
  int hoursSet    = 0; //Stores the hours added.
  int minutesSet  = 0; //Stores the minutes added.
  String printTime;
  bool timeComplete = false;
  while (!timeComplete) {
    int buttonVal = analogRead(A0);
    if (buttonVal >= 490 && buttonVal <= 520) { //Indicates button 3 is pressed. It's function is to add one hour to the time.
      hoursSet = (hoursSet + 1) % 24; //Adds one hour to the hours.
      delay(100);
    } else if (buttonVal >= 5 && buttonVal <= 10) { //Indicates button 4 is pressed. It's function si to add 5 minutes to the time.
      minutesSet = (minutesSet + 5) % 60; //Adds minutes to the minutes.
      delay(100);
    }

    lcd.setCursor(0,1);
    String strHr = String(hoursSet);
    String strMn = String(minutesSet);
    if(strHr.length() == 2){
      lcd.print(hoursSet);
    } else if(strHr.length() == 1) {
      lcd.print("0");
      lcd.setCursor(1, 1);
      lcd.print(hoursSet);
    }

    lcd.setCursor(2,1);
    lcd.print(":");
    lcd.setCursor(3,1);
    if(strMn.length() == 2){
      lcd.print(minutesSet);
    } else if(strMn.length() == 1) {
      lcd.print("0");
      lcd.setCursor(4, 1);
      lcd.print(minutesSet);
    }
    delay(100);

    if (buttonVal >= 990 && buttonVal <= 1010) { //if button 2 is pressed again, the timecomeplete is set to true, and the script continues.
      timeIsSet = true;
      timeComplete = true;
    }
  }
  lcd.clear(); //Clear the screen
  lcd.setCursor(0, 0);
  lcd.print("The time"); //Print text, move cursor and print the time
  lcd.setCursor(0, 1);
  String strHr = String(hoursSet);
  String strMn = String(minutesSet);
  if(strHr.length() == 2){
    lcd.print(hoursSet);
  } else if(strHr.length() == 1) {
    lcd.print("0");
    lcd.setCursor(1, 1);
    lcd.print(hoursSet);
  }
  lcd.setCursor(2,1);
  lcd.print(":");
  lcd.setCursor(3,1);
  if(strMn.length() == 2){
    lcd.print(minutesSet);
  } else if(strMn.length() == 1) {
    lcd.print("0");
    lcd.setCursor(4, 1);
    lcd.print(minutesSet);
  }
  lcd.print(" is saved!");
  setTime((hoursSet * 3600) + (minutesSet * 60));
  timeIsSet = true;
  delay(5000); //Wait five, seconds then proceed

}
Added this to the code:
      Serial.print("hours ");
  Serial.println(hoursSet);
  Serial.print("hours in s ");
  Serial.println(hoursSet * 3600);
  Serial.print("minutes ");
  Serial.println(minutesSet);
  Serial.print("minutes in s ");
  Serial.println(minutesSet * 60);
  Serial.print("Combined:  ");
  Serial.println( (hoursSet * 3600) + (minutesSet * 60) );

When I input 5:15 it results in:

hours 5
  hours in s 18000
  minutes 15
  minutes in s 900
  Combined:  18900

When I input 9:15 it results in:

hours 9
  hours in s 32400
  minutes 15
  minutes in s 900
  Combined:  -32236

So, it looks like the library only holds an Int. But that seems odd, as the function expects seconds.

And now you know why no one does that.

Well, this is a school project due tomorrow. So I can't do much with this...

What IDE version are you using, that page you've referenced specifically states it doesn't work with 1.61

Here's a hint: 32767 seconds is 9 hours, 6 minutes and 7 seconds.
What is the largest value that an int can hold?

EDIT: I can't add comments on this computer (old browser), so I have to respond to your question here.
time_t is an unsigned 32-bit value, but all of your input values are signed 16-bit values. When you take a product like 3600*10, you get a bit pattern of 1000110010100000, which is 36000 when interpreted as an unsigned value, but is -29536 when interpreted as a signed value.
When assigned to a time_t, the value is sign-extended to 32 bits, which makes it 11111111111111111000110010100000, which is 4294937760 when interpreted as an unsigned value.
If you want to write a statement like
time_t x = (hoursSet * 3600) + (minutesSet * 60);

you need to type-cast your input arguments to the correct type first:
time_t x = ((time_t)hoursSet * 3600) + ((time_t)minutesSet * 60);

Well, I know that is. But as it is a function "setTime" Which expects a second input for the time. And also would take a date like that.

Can I edit the function so that it takes unsigned long?

time_t x = (hoursSet * 3600) + (minutesSet * 60);
Serial.println(x);
  setTime(x);

When I try it like that, it returns Combined:  4294937760 (For 10:00)

Changing this:
  time_t x = (hoursSet * 3600) + (minutesSet * 60);

To this:
  time_t x = ((unsigned long)hoursSet * 3600) + (minutesSet * 60);

Has solved the problem


text:
My Arduino Code isn't workig... and i just couldn't see any problems... thoughts?

There's Latest Update!

So i'm working on a counter just for fun. How it works is when you press BUTTON1 the LED Lights up red, the buzzer beeps and the variable "counter" adds one to itself; After counting, you can press BUTTON2 then it will first show a transition animation then blink&beep while taking away the value of "counter". After the value of "counter" is less than 1, everything will start from the beginning.
But what actually happens is after the transition animation played, the LED and the buzzer just won't do any thing. I'm sure my physical connection is all correct, and the buttons are also pulled to ground with a resistor& a 100nf cap to prevent accidental pressing and vibration.

Note that I'm using a common anode RGB LED, so the anode pin is always HIGH but to light up individual colors i'll have to pull the cathode pins LOW (remember how electrons flow?)

Update
@Tom Carpenter's latest answer still didn't solve the problem. I found the "else" function inside the "if" didn't work at all. So if i put the counter code inside the "else" function, the result would be none. But if i put the counter code in the "if" inside the primary "if", it would, again, count at clock speed, which results blinking forever!
So is there anyway for the code to only count once per press&release cycle without losing?

The latest code:

#define RLED 10
#define GLED 11
#define BLED 12

#define B1 4
#define B2 5

#define BZZ 3

boolean OB1V;

int counter;

void setup() {

  pinMode(RLED, OUTPUT);
  pinMode(GLED, OUTPUT);
  pinMode(BLED, OUTPUT);

  pinMode(B1, INPUT);
  pinMode(B2, INPUT);

  pinMode(BZZ, OUTPUT);

  OB1V = digitalRead(B1);

}

void loop() {

  digitalWrite(RLED, HIGH);
  digitalWrite(GLED, HIGH);
  digitalWrite(BLED, HIGH);

  boolean NB1V = digitalRead(B1);

  if (NB1V != OB1V)
    {
      digitalWrite(RLED, LOW);
      digitalWrite(BZZ, HIGH);
      counter = 0;
    }
  else
    {
      digitalWrite(RLED, HIGH);
      digitalWrite(BZZ, LOW);
      counter = counter +1;
    }

  if ( digitalRead(B2) == HIGH )
    {
      digitalWrite(GLED, LOW);
      delay(300);
      digitalWrite(GLED, HIGH);
      digitalWrite(RLED, LOW);
      delay(300);
      digitalWrite(RLED, HIGH);
      digitalWrite(GLED, LOW);
      delay(300);
      digitalWrite(GLED, HIGH);
      digitalWrite(BLED, LOW);
      delay(100);
      digitalWrite(BLED, HIGH);
      delay(300);

      for ( counter; counter >= 1; counter -- )
        {
          digitalWrite(GLED, LOW);
          digitalWrite(BZZ, HIGH);
          delay(200);
          digitalWrite(GLED, HIGH);
          digitalWrite(BZZ, LOW);
          delay(200);
        }
    }
}

How are your buttons wired?   Typically you would use a pullup resistor and a button switching to ground, so pushed is "low".  Also your non-delay counter case would probably be subject to contact bounce, except for the fact that "counter +1" doesn't actually count as it does not save the result of the add.  Your other path with delays might be somewhat immune to bounce on press, but can suffer it on release unless the user releases the button enough before the end of the sequence of operations there.

counter +1; doesn't do anything as Chris says. As a result the value counter is always 0, and so the for loop will never do anything (and will probably be removed as dead code by the compiler). If correcting the line causes something else to break, it means something else in the code is broken.

Try adding Serial.println(counter); inside the if statements to see what the counter value is when buttons are pressed (also add Serial.begin(...) to the setup() if you are adding the print statements.).

So how do i change the value of "counter"? if i change "counter+1" above into "counter = counter+1", the green LED will keep flashing as a result

You change it to counter = counter + 1, which is what it needs to be to change the value of counter. Then you need to find out what is actually causing the green LED to keep flashing - printing debug info to the serial port will help you there.

The green LED is not the indicator on board..it's my user LED and doesn't show any status of the chip. So i think the problem would still be the logic of the program.

What is this doing? for ( counter; counter >= 1; counter -- ) - it makes more sense to initialize counter to something (the first item in the for loop). Eg.  for ( counter = 10; counter >= 1; counter -- )

@Nick Gammon counter already has a value before : - )  Look at the first button listener.

In that case you can write: for ( ; counter >= 1; counter -- ) - just using counter on its own looks like you forgot something

Your problems come down to the fact that in the first code you are trying to do things on level sensitivity rather than edge sensitivity.
To try and understand the difference, some examples. Level sensitivity is effectively:

Do 'x' while 'y'

In other words, if 'y' is true (for example an input is high), then keep doing 'x' (e.g. adding to a counter). This is what your code is doing at the moment, but not what you want it to be doing.
Edge sensitivity on the other hand is:

Do 'x' when 'y changed'

In other words, when the state of 'y' changes (for example from true to false), then doing 'x' once.
The key difference between the two is the difference between 'while' and 'when'.

So how do you do edge sensitivity in code?
The way you have done it requires that the button be high and then low at exactly the right moment for the code to catch it. What happens if the button goes low at the end of the loop? Your code will miss the edge because at the start of the next loop it is not high, so doesn't get in to the first if statement.
Lets think about what 'changes' means. It means when the current value is different from the previous value. That implies that we need to keep track of what the previous value is in order to compare it to the current value. In fact that is exactly what we do:
boolean oldButtonValue; //It would be better to use a static variable in loop, but for simplicity of the example lets use a global.

void setup() {
    oldButtonValue = digitalRead(buttonPin); //This line is executed once to initialise the variable.
}

void loop() {

    //Each loop we read our current value
    boolean newButtonValue = digitalRead(buttonPin);

    //Has it changed?
    if (newButtonValue != oldButtonValue) {

        //Do something on edge.

    }

    //Update the old button value to match the new one (so we can check it again next loop
    oldButtonValue = newButtonValue;
}

What this does is each loop it compares the current state of the button with the state of it from the previous loop. If the value changes, it does something.

Now the trouble with that code is it executes on any edge. That means that each time you press the button, it will run twice, once on press and again on release. So lets modify it slightly:
    ...

    //Has it changed?
    if (newButtonValue != oldButtonValue) {

        //Was it a rising edge?
        if (newButtonValue) {
            //If the button value is now high, it must have been a rising edge
        } else {
            //Otherwise it was a falling edge

        }
    }

    ...

The extra comparison allows us to determine whether it was a rising edge or a falling edge. So you can now do something either when the button is pressed, or when it is released (or both if you want).

You can have a second boolean variable to keep track of the old state for the second button. Then you use the same approach to do edge sensitivity detection approach for the second button.

i changed my code into this: link Because that the sencond button always works fine, i didn't touch that piece of code. But what happens now is when it is supposed to show the results, it showed nothing! What's wrong now?

@user56336  Try it, and if it works, there you go. It looks basically the same as what I put just with much harder to follow variable names. Except you are missing the bit where you set OB1V = NB1V; at the end of the loop which is a somewhat critical part. And really you should do the same with both buttons, otherwise you will end up with the same problem with the second one - it will execute the code multiple times if you keep the button held down.

There are a number of problems with your code.  Your code does not deal with releasing the button.  Once you press B1 (assuming pressing B1 causes the input to go high) the counter (if correctly implemented (that is, it should be counter++)) would count up to 32K then start over at zero and count up again. Only stopping when you release B1.  The value of counter could be any number between 0 and 32K.
Working with buttons is difficult.   And the 100nF capacitor will do little to help.  It would be better if you learned how to debounce buttons and treat both the press and the release with equal importance.
There is an Arduino library called Bounce that will do some of this for you.  It will not help with your logical errors.  You still need to treat pressing and releasing the button with equal importance.  But it will help debounce button presses so your results will more closely match your expectation.
added later...
Your altered code will still not work.  You need to keep track of the state of the button in order to increment the counter by one for each button press.  You can call it edge detection code or state machine code.   But the code needs history to decide what to do next.  Here is an example of code which does this.

the cap does help because i've tried to print messgaes on the serial monitor with "caped" buttons--perfectly one result each press. Also to deal with release, i put an "else" function at the end which turns the LED and the buzzer off. So it should trigger counter +1 (or counter ++ if u like) each time i press the button

@user56336 remember that it is in a loop. The whole loop() function will execute thousands of times per second, so unless you release the button in much less than a millisecond, it will repeatedly add 1 to the counter until the button is released. Try adding the print statement I suggested and you will see that.

In most cases when using a button, the software keeps track of 4 states.  1) Button released and action already taken, 2) Button pressed and action not taken yet, 3) Button pressed and action already taken & 4) Button released and action not taken yet.  You need to keep track of these 4 states if you want to count up by one for each button press.

well, what my code does is just add 1 to the "counter" value every time there's a HIGH signal from the button pin untill the second button is pushed, it'll show the results. So i don't think i'll have to listen all four status. The problem now is, after i changed "counter +1;" above into "counter = counter +1;" so that it'll keep the result as mentioned above, the LED keeps flashing when supposed to show the result. So there must be something wrong with adding or minusing.

Perhaps this would be more obvious in a real C code environment instead of in an Arduino environment.  In real C you would have to put your button press inside of an infinite loop.  Because you would want to use your button over an over again.  Not just once.  While inside an infinite loop, you would see that when the button was pressed, the computer would simply be adding 1 to counter over and over again as fast as it could.  Do this, after adding 1 to counter print out the value of counter.  I think you will see, when you press the button, an endless stream of " 1",  " 2", " 3", ...

@ Tom Carpenter i guess ur right. lemme try n figure that out

authors: Ареке Конарбай

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


text:
Nordic nRf905 (433MHZ) with arduino receive garbage data
I am interface Arduino with nRf905 in receive mode use 433 MHZ.
I Have follow this link http://www.electrodragon.com/w/NRF905_Transceiver_433MHz-Wireless_Module.
And for transmitter, I am use RF-Transmitter-Door-Window-Sensor which works on 433MHZ.
Now, Arduino receive garbage data I have attached snapshot of received data.
I am quarry about to set address and 433MHZ.
My config_buffer is:

unsigned char config_info_buf[10]={
      0x4C,
      0x01,                   //output power 10db, resend disable, Current
      0x44,                   //4-byte address
      0x20,0x20,              //receive or send data length 32 bytes
      0x21,0x11,0x11,0x00,
      0x18,
};

Question is there are 0x4C set exactly 433MHZ.

Any help will be appreciated.
Regards,
rajneesh

This is far too incomplete to be answered.  You must provide full details of wiring, power, and transmit and receive software.

Your question Question is there are 0x4C set exactly 433MHZ. doesn't make a lot of sense. You should try to be more specific in what you are asking.
However a couple of pointers for troubleshooting:

Is the TX side set to transfer ASCII/Text data ?
Are you sure the baud rate is the same on the RX arduino and the PC you using the serial monitor on ?

Thanks for reply, I have provided all details in above post.  Wiring connection with arduino and nRF905 => TXEN=5;
TRX_CE=4;
PWR=3;
CSN=10;
AM=9;
DR=8;
CD=7; MOSI = 11; MISO 1;SCK=13; Ya I have checked baud rate of arduino and pc bath are same. As a transmitter device I have used https://www.alibaba.com/product-detail/RF-100m-transmission-distance-wireless-Magnetic_60286055162.html?spm=a2700.7724857.0.0.ov1gVH  .This is work on 433MHz. Still I am confuse If AM and DR pin set to high then why I am receive garbage data?


text:
RF24 - Split data in payloads at sender and then rebuild on receiving end
I'm trying to send some data using nRF24L01+ transceivers, but I need to use 8 byte payloads for reliability. The data I'm sending is much bigger than that, so I need to split it into 8 byte packets and then reassembly on the receiving end. I wrote the following code to test it, but to no success.

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
RF24 radio(9,10);
const byte pipes[][7] = { "master", "slaves" };
#define PayLoad 8

void setup() {
  Serial.begin(9600);
  while(!Serial){}
  radio.begin();
  radio.setRetries(15,15);
  radio.setPayloadSize(PayLoad);
  radio.setPALevel(RF24_PA_LOW);
  radio.setDataRate(RF24_1MBPS);
  radio.setCRCLength(RF24_CRC_16);
  delay(100);
  radio.openWritingPipe(pipes[0]);
  radio.openReadingPipe(1,pipes[1]);
  radio.startListening();
  radio.printDetails(); //RF Debug
  delay(1000);
  //sendRF("Payload splitting test. 1234567890");
}

void loop() {
  if (radio.available()){
    fromRF();
  }
  if (Serial.available()){
    String dataIn = Serial.readString();
    sendRF(dataIn);
  }
}

void fromRF(){
  byte numPkgs;
  radio.read(&numPkgs,1);
  Serial.println(numPkgs);
  char rcvBuffer[numPkgs*PayLoad];
  for (byte pkg=1; pkg<=numPkgs; pkg++){
    char payloadBuff[PayLoad];
    radio.read(&payloadBuff,PayLoad);
    for (int charpos=0; charpos<PayLoad; charpos++){
      rcvBuffer[((pkg-1)*PayLoad)+charpos] = payloadBuff[charpos];
    }
    if (pkg < numPkgs){
      int timeout = 0;
      while(!radio.available() && timeout<100){
        timeout++;
        delay(1);
      }
      if (timeout >= 100){
        Serial.println("Package timed out.");
        return;
      }
    }
  }
  String msgRcvd(rcvBuffer);
  Serial.println(msgRcvd);
}

void sendRF(String msg){
  byte msgLen = msg.length();
  Serial.println(msg);
  Serial.println(msgLen);
  char msgBuff[msgLen];
  msg.toCharArray(msgBuff,msgLen);
  radio.stopListening();
  byte numIters = msgLen/PayLoad;
  if (msgLen%PayLoad > 0)
    numIters++;
  radio.write(&numIters, 1);
  Serial.println(numIters);
  char payloadBuff[PayLoad];
  for (byte iter = 1; iter <= numIters; iter++){
    for (byte i=0; i<=PayLoad; i++){
      payloadBuff[i] = (char)0;
    }
    byte initchar = (iter-1)*PayLoad;
    byte lastchar = (iter*PayLoad)-1;
    if (lastchar > msgLen)
      lastchar = msgLen;
    byte counter = 0;
    for (byte nextchar = initchar; nextchar <= lastchar; nextchar++){
      payloadBuff[counter] = msgBuff[nextchar];
      counter++;
    }
    radio.write(&payloadBuff, PayLoad);
    Serial.println(payloadBuff);
    delay(50);
  }
  radio.startListening();
  delay(100);
}

This code is intended to work for both master and slave, except that writing and reading pipes change places.
My splitting is working fine (as shown by the serial monitor), but it looks like I'm not able to receive it well. Any help would be greatly appreciated!!
EDIT:
I've got it working! (kind of). It still lacks managing lost packages, but it's working quite fine.
void fromRF(){
  byte numPkgs;
  radio.read(&numPkgs,1);
  //Serial.println(numPkgs);
  String rcvdStr = "";
  for (byte pkg=1; pkg<=numPkgs; pkg++){
    char rcvBuffer[PayLoad+1];
    delay(100);
    radio.read(&rcvBuffer,PayLoad);
    rcvBuffer[PayLoad] = '\0';
    String strBuffer(rcvBuffer);
    rcvdStr += strBuffer;
  }
  Serial.println(rcvdStr);
  //sendRF(rcvdStr);
}

void sendRF(String msg){
  byte msgLen = msg.length();
  Serial.println(msg);
  //Serial.println(msgLen);
  char msgBuff[msgLen];
  msg.toCharArray(msgBuff,msgLen);
  radio.stopListening();
  byte numIters = msgLen/PayLoad;
  if (msgLen%PayLoad > 0)
    numIters++;
  radio.write(&numIters, 1);
  Serial.println(numIters);
  char payloadBuff[PayLoad];
  for (byte iter = 1; iter <= numIters; iter++){
    for (byte i=0; i<=PayLoad; i++){
      payloadBuff[i] = (char)0;
    }
    byte initchar = (iter-1)*PayLoad;
    byte lastchar = (iter*PayLoad)-1;
    if (lastchar > msgLen)
      lastchar = msgLen;
    byte counter = 0;
    for (byte nextchar = initchar; nextchar <= lastchar; nextchar++){
      payloadBuff[counter] = msgBuff[nextchar];
      counter++;
    }
    radio.write(&payloadBuff, PayLoad);
    Serial.println(payloadBuff);
    delay(50);
  }
  radio.startListening();
  delay(100);
}

Gotta give a look at RF24Mesh.

What do you mean by not able to receive it "well"?

I'm not that into C but in the case of char rcvBuffer[numPkgs*PayLoad];, I'm not entirely sure that you can create an array with a dynamic size. Also, you method relies on never missing a single packet, and not turning on the receiver in the middle of a transmission of packets.

It would be maybe a good idea to use an existing solution like RF24Mesh that does it for you?

@Majenko It was not receiving the complete payload, only the first byte. It's fixed now, but I'd like to make improvements. I haven't found anything related, so I guess this could be helpful for others.

@Gerben Actually at the moment of creating the array, numPkgs*PayLoad acts as a constant. Anyway, I'm doing it differently now. And nope, still no lost package management. :S

@Avamander Gotta give it a try. ;)

@Gerben You only need to provide a constant as an array size when the array is global (or maybe static). When it's local it gets allocated on the stack dynamically and the size can be given at runtime, not compile time. Only when it needs to be allocated in the .bss or .data sections does the compiler need to know the size beforehand.


text:
Writing objects to PROGMEM
A few days ago I encountered memory problems (SRAM shortage) on my Arduino. I've read a lot and fixed the problem, now I have around 900 bytes free in SRAM. However, I still have difficulties understanding and using progmem.
The user is allowed to create up to 10 programs (a program in my case is just some object storing the user's preferences). As I don't want to run out of SRAM, I planned to store them in PROGMEM.
Consider the following class:

#define MAX_PROGRAMS 10
#define MAX_PREFS 10

class Program
{
  public:
    Program(String name, Preference* prefs[]); // ctor

    String getName();
    static byte getNoOfPrograms();
    static Program* getProgram(byte idx);

  private:
    const String _name;
    static int _programCtr;

    Preference* _preferences[MAX_PREFS];
    static Program* _programs[MAX_PROGRAMS];
};

One notices that a program can store up to 10 preferences, hence, if the user decides to make 10 programs, each with 10 different preferences, we will definitely run out of SRAM.
Therefore, can I store instances of the above Program class in PROGMEM if I define them as below?
const Program* const pgm PROGMEM = new Program(F("Test"), ...);
// ...
delete pgm;

I presume this is possible since the whole object is const and could never be changed. I actually tried this and had no compiler errors, however, I was stumbled by the fact that the above two lines of code use 22 bytes of SRAM, when I expected it not to use any.
In my case, would it be better not to store the whole object in progmem but only its constant fields, and do the same for all constants in Preference ? (i.e. change const String _name to const char name[] PROGMEM; etc.)

Are you aware that everything you store in progmem is going to be fixed at compile time? I ask because you wish to use progmem to store user defined programs, so that makes sense only if the user defines that programs before compilation occurs... which to me makes the whole thing a nonsense... but I believe it all comes down to what is a program for you...

@RobertoLoGiacco Wow, thanks! This indeed does not make sense if it is to be fixed at compile time, since, the user will make those programs at runtime. Does this imply that i can not avoid to run out of SRAM, apart from limiting the user to less programs and preferences?

Your example only puts the object pointer in program memory. "new" allocates the object from the heap. Please see this example that I put together a few years back. https://github.com/mikaelpatel/Sketchbook/tree/master/ProgramMemory

A more advanced example can be found in Cosa LCD Menu handler. The menu data structure is put in program memory; https://github.com/mikaelpatel/Cosa/blob/master/libraries/Menu/Menu.hh and example sketch, https://github.com/mikaelpatel/Cosa/blob/master/examples/LCD/CosaLCDmenu/CosaLCDmenu.ino

@MikaelPatel Right, i was not sure about dynamically allocating the object or not. Thanks for the examples, they are quiet useful, however, my program instances will be created at runtime. Hence, i think i will have no other option than limiting the user to a few programs..

@HyperZ Or cleaning up your system to a) not use String, and b) tokenize your program and store it as binary code.

It is possible for software running on the ATmega to write to program memory at runtime, and even to erase it in large blocks.  See bootloader sources for an example.

@Majenko Thanks, i cleaned up the whole system such that i don't use the String class anymore in order not to fragment the heap. Now, what do you mean by tokenizing my program and storing it as binary code? :)

I've marked this as a duplicate of Using PROGMEM to store array of structs. The question isn't the same, but the solution is.

Related: Can I write to flash memory using PROGMEM?


text:
Question regarding Servo including Serial monitor display
I tried to make code following your instruction about mills,
and it looks like this. Unfortunately, it is not working. Is there problem with my code?
Here is my code:

#include <LiquidCrystal.h>
#include<Servo.h>

Servo myservo;  // create servo object to control a servo

// These constants won't change. They're used to give names to the pins used:
const int analogInPin1 = A0;  // Analog input pin that the photosensor is attached to
const int analogInPin2 = A1;  // Analog input pin that the photosensor is attached to
const int analogInPin3 = A2;  // Analog input pin that the photosensor is attached to
const int analogInPin4 = A3;  // Analog input pin that the photosensor is attached to
int sensorValue1;
int sensorValue2;
int sensorValue3;
int sensorValue4;
unsigned long m;

//declare counter as an input
int Chactr =0;
int Disctr =0;

byte state;

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write(0);  // back to 0 degrees.
  delay(1000); // wait for a second.
  pinMode(13, OUTPUT); // initialize digital pin 13 as an output.
  Serial.begin(9600);  // initialize serial communications at 9600 bps:
  lcd.begin(16,2);

  delay(5000);
}

void loop() {

  // read the analog in value:
  sensorValue1 = analogRead(analogInPin1);
  sensorValue2 = analogRead(analogInPin2);
  sensorValue3 = analogRead(analogInPin3);
  sensorValue4 = analogRead(analogInPin4);

  delay(3000);

  // print the results to the Serial Monitor:
  Serial.print("sensor1 = ");
  Serial.print(sensorValue1);
  Serial.print("\n");

  Serial.print("sensor2 = ");
  Serial.print(sensorValue2);
  Serial.print("\n");

  Serial.print("sensor3 = ");
  Serial.print(sensorValue3);
  Serial.print("\n");

  Serial.print("sensor4 = ");
  Serial.print(sensorValue4);
  Serial.print("\n");

  Serial.print("Led State:  ");
  Serial.println(state);
  Serial.print("\n");

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250)
  {
    m=(millis()+60000);
  }

  if(sensorValue1 <=568 && sensorValue2 <=519 &&sensorValue3 <=418 && sensorValue4 <=249)
  {
    m=0;
  }

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250 && m==millis())
  {
    state=1;
    delay(5000);
    digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
    delay(5000); // wait for a second

    myservo.attach (9);
    myservo.write(30);
    delay(3000);
    myservo.write(0);
    delay(3000);

    myservo.detach ();
    delay (1000);

    Disctr = Disctr + 1;

    delay(900);

    Serial.print("Battery Full: Discharge ON");
    Serial.print("\n");
  }
  else if (sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4 ==0 )
  {
    m=(millis()+60000);
  }

  if(sensorValue1 >=1 && sensorValue2 >=1 && sensorValue3 >=1 && sensorValue4 >=1)
  {
    m=0;
  }

  if(sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4  ==0 && m==millis())
  {
    state=0;
    delay(5000);
    digitalWrite(13, HIGH ); // turn the LED On by making the voltage high
    delay(5000); // wait for a second

    Chactr = Chactr + 1;
    delay(900);

    Serial.print("Battery Empty: Charging ON");
    Serial.print("\n");
  }
  {
    lcd.setCursor(0,0);
    lcd.print("Charge Cycle: ");

    lcd.setCursor(13,0);
    lcd.print(Chactr);

    lcd.setCursor(0,1);
    lcd.print("Discha Cycle: ");

    lcd.setCursor(13,1);
    lcd.print(Disctr);

    delay(1000);
  }
}

What exactly is your problem with your sketch? What code have you written until now? How does your circuit look like (schematic)? Please give us more information. You can edit your question for that.

The point of using millis is to get rid of all of the delay calls.  You can't leave any of them.  While those delay calls are running your millis code isn't and will still miss doing what you want it to do.

So what you want to do is be able to activate the servo when 4 green bars appear over the course of one minute correct?
I think you would need to create three if statements and one new variable. The first if statement will be, if it detects four green bar, then m=(millis() + 60000). Then you will need to nest another if statement in here to say if it detects ONLY three bar, then m = 0.
Your third if the statement is if it detects the four green bars AND m == millis() then the servo will activate.
This is how I would do it, but I am not very experienced. I'm pretty sure others will have a cleaner and simpler code but this should work.

Thank you for the help.But one more question. Even there are only three bars, the LED sensor ckt still senses the 4th bar because the 4th bar is blinking and the servo will activate. The LED sensor ckt shoud ignore the blinking bars of the battery in order for the servo not to move. The servo should activate once the 4bars appear steadily and no more blinking.any idea?Thank you.

I understand that even with only three bars, the 4th one will blink. In terms of the logic of how this code will work it will be like this:
Once the fourth bar appears for less than a second, m = miillis() + 60000. Then it will disappear and only three bars will appear. This will then set m = 0 and the process will repeat UNTIL the fourth bar stays on. When the fourth bar stays on,  then m will not equal 0 anymore and m will be millis() + 600000.
As milis() continue to increase for up to a minute (at which m == millis()), then the servo will activate.

You've got a bug in this answer code if it runs past rollover.  Always handle millis by using subtraction to see how long it has been.  Never use addition to try to predict the time in the future.  Save the old timestamp and compare to that.


text:
Arduino does not see data from nodemcu
I’m trying to send data from a NodeMCU to an Arduino nano.
If I try to send data with one second delay - all working fine.
But if I try to send without delay or with a delay less than one second, then arduino sees data but nothing not does.
Arduino nano sketch:
#include <Servo.h>

Servo servo1;

int servo = 6;
int engine = 5;

void setup() {
Serial.begin(9600);
analogWrite(servo, 67);
servo1.attach(8);
}

void loop() {
if (Serial.available()) {
String model = Serial.readStringUntil(':');
i

f (model.equals("engine")){
String value = Serial.readStringUntil('c');
int power = value.toInt();
analogWrite(engine, power);
}
if (model.equals("servo")){
String value_servo = Serial.readStringUntil('c');
int power_servo = value_servo.toInt();
servo1.write(power_servo);
}
}
}

NodeMCU sketch:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "my_wifi_ssid";
const char* password = "my_wifi_password";

ESP8266WebServer server(80);

void get_vars(){
if (server.argName(0) == "engine"){
server.send(200, "text/plain", "Reading engine. Value: "+server.arg(0));
Serial.println("engine:"+server.arg(0)+"c");
}
if (server.argName(0) == "servo"){
server.send(200, "text/plain", "Reading engine. Value: "+server.arg(0));
Serial.println("servo:"+server.arg(0)+"c");
}
}

void setup(void){
main_stuff();
}

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

void main_stuff(){
Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");

// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}

server.onNotFound(get_vars);

server.begin();
Serial.println("HTTP server started");

}

In the Arduino IDE, press "Ctrl" + "T" that will make your code easier to read.

What does this mean "But if i try to send without delay or delay < one second, then arduino sees data but nothing not does.", could you elaborate?

@MatsK, when the NodeMcu sends something to the Arduino - the built-in LED on it blinks

nothing not does is a double negative ... it means something does .... it is unclear what you mean by that statement

the newline characters from println (\r\n) stay in the serial input buffer and you read them with Serial.readStringUntil(':');. then the string is not "servo" but "\r\nservo"
if you wait one second with sending, the the \r\n are discarded because the readStringUntil times out one second after reading them

And how to fix this?

Thank you very much! All work fine. I'am just change "Serial.println" to "Serial.print"


text:
Sampling stereo audio at greater than 40 Hertz using arduino
I am working on a project to make a speaker with reactive lighting. I need to be able to sample stereo audio at a decent rate for songs. The audioRead () function can do about 8 kHz and I have heard you can push it up till 35 kHz but than you can only use it for mono and you cannot use the arduino for anything else.

Someone recommended that I use an ADC. What can it do for me?
Is the arduino's operating speed a limitation?
If not the arduino which other micro-controller is suitable for this purpose.

If you are only interested in getting a reading of the sound intensity,
then 8 kHz may be enough. You can also convert the signal to mono
using a pair of resistors. If you want the Arduino to do other stuff
while taking the analog readings, then you should forego analogRead()
and access the ADC directly. This is more involved that typical Arduino
programming, as it involves configuring the ADC at low-level, in “free
running mode”. In this mode the ADC operates in an autonomous way, and
send you an interrupt every time a sample is ready.
I have written a program that does something similar: it samples an
analog input at 9.6 kHz (104 µs per sample) an periodically
sends the reading through the serial port: sound-meter.ino. You can
probably adapt it for driving LEDs instead of the serial port.

Thank you. I will do it using this method this time but is there any way I could do stereo and/or 50KHz +? Just curious.

@A.Shetye: For stereo, you could add something like ADMUX ^= _BV(MUX0); to the ISR in order to alternate between the A0 and A1 inputs, but then the per-channel sampling rate would be half as fast. For faster sampling, you could set the prescaler to 16 and get 76.9 kHz mono or half that in stereo, but I do not guarantee the Arduino will keep up with the processing load. A prescaler lower than 16 will likely give very noisy readings.

The first part of the speed limitation on the Arduino is that the ADC is painfully slow.  If you had a faster ADC chip then you could take analog readings faster so you can take more per second.  Once you're over that threshold then the next limitation you run into is the speed with which Arduino can communicate with that ADC.  So make sure you get something fast (like SPI).


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


text:
Arduino Yun restarts or stalls during operation
I have an Arduino Yun that I need to connect to a machine to detect whether the machine is working or is stopped.
The signal used as a flag for such behaviour is basically the presence or absence of current in one of the motors that work when the machine operates. The voltage going through the motor is 220VAC. So I figured I could use a standard AC to DC converter like the one used to charge the phones (since those converters usually take 100~240V at 50/60Hz and output 5V with 1A) and connect that to one of the digital ports in input mode. Then I would know if the machine is working or not if such pin is in HIGH state or LOW state respectively.
Well, this works up to certain point. For some reason, the YUN stalls or resets itself while the machine is operating. I've checked the voltage and even used a voltage regulator to make sure it doesn't exceed the 5V. I even connected the signal to an Analog pin and measured the input and it never read more than 4.9V. So I guess my question is, what might be causing this behaviour and how could I avoid it. I suspected it was a voltage/current spike but with the voltage regulator and the resistors I added before passing the signal to the Arduino I though the issue should be solved but the issue persists.
Attached is an image of the power adapters I'm using to both feed the arduino with current and convert the signal that goes to the pins to DC.
Basically, I know that the arduino stalls because it closes the telnet session I am using to monitor the values read by the pins and because the USB let goes off. Normally the arduino will have the USB and the ON leds on but once the issue happens it turns the USB led off and in some boards it turns on the WAN led on.
Interestingly enough, it seems that the issue happens when the machine is stopped (LOW voltage) and is preparing to start working.
Just as a note. I've tried different Arduino Yun boards and all have the same behaviour so I don't think it's a matter of the board being broken. Resetting the board allows it to continue reading the signal but eventually it stalls again

Yes, that's what I'm using it for. Not sure it that's the best way to do it though.

That makes sense. I'll try that out. Thank you.


text:
Error with libraries after setting up Code::blocks to work as an arduino IDE
I followed this guide: http://arduinodev.com/guide-to-arduino-development-environment-codeblocks/
Everything seemed to work until I compiled the example code:
#include <Arduino.h>

/*
  Turns on an LED on for one second, then off for one second, repeatedly.

  This example code is in the public domain.
*/

void setup()
{
    // initialize the digital pin as an output.
    // Pin 13 has an LED connected on most Arduino boards:
    pinMode(13, OUTPUT);
}

void loop()
{
    digitalWrite(13, HIGH);   // set the LED on
    delay(1000);              // wait for a second
    digitalWrite(13, LOW);    // set the LED off
    delay(1000);              // wait for a second
}

and it gave me this errors:
||=== Build: Simulator - Debug in test (compiler: GNU GCC Compiler) ===|
/home/meneses/.codeblocks/ardusim/include/util/delay.h|90|warning: #warning "Compiler optimizations disabled; functions from <util/delay.h> won't work as designed" [-Wcpp]|
/usr/include/x86_64-linux-gnu/sys/types.h|197|error: conflicting declaration ‘typedef long int int64_t’|
/home/meneses/.codeblocks/ardusim/arduino/cores/stdint.h|33|error: ‘int64_t’ has a previous declaration as ‘typedef long long int int64_t’|
/usr/include/unistd.h|267|error: conflicting declaration ‘typedef __intptr_t intptr_t’|
/home/meneses/.codeblocks/ardusim/arduino/cores/stdint.h|66|error: ‘intptr_t’ has a previous declaration as ‘typedef int intptr_t’|

If I click on those errors I go to this following libraries:
first error - type.h, on line 197:
__intN_t (64, __DI__);

second error: stdint.h, on line 33:
typedef long long  int64_t;

third error: unistd.h, on line 267:
typedef __intptr_t intptr_t;

forth error: stdint.h, on line 66:
typedef int intptr_t;

And there's also the warning, on the delay.h library, line 90:
# warning "Compiler optimizations disabled; functions from <util/delay.h> won't work as designed"

How can I fix this?
Thank you!
edit: I've also found this error if instead of running the simulation debugger I run arduino UNO for example:
library features.h, line 374, error:
fatal error: sys/cdef.h: No such file or directory

But none of the other errors above..
The line is: #  include <sys/cdefs.h>
Edit2: solved the previous error by running this command:
sudo apt-get install libc6-dev-i386
but now I'm running into 'uint_farptr_t' was not declared in this scope, I'll try to solve them.
edit3: fixed the previous item by going into code::block's settings -> compiler -> selected compiler -> GNU GCC compiler for AVR -> Search directories -> Compiler -> remove /usr/include
I don't know the consequences of this, but it fixed that error.
Now I'm getting 5 errors of this type:
/home/meneses/.codeblocks/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp|91|error: attempt to use poisoned "SIG_USART0_RECV"|

edit4: I feel like cryinggg
edit5: I'm now willing to install other IDE, all I want is to be able to run simulations.
I'm using Linux Mint 17.3.

Why are you compiling 64bit stuff for an 8 bit Arduino?  That seems really weird to me, is it possible you are picking up a header file or define from you Linux machine?  Can you run the IDE on a virtual machine running Windows?


text:
master slave control of 2wd robots using xbee
Hi there I just need to ask you how I can send command from master robot to slave to follow using XBee. I have configured both the XBee in AT mode, but I totally don't have the clue how the program.
I am using the following kit components (from DF ROBOT) to build this project,

Romeo V2-All in one Controller (Arduino based controller).
Differential drive chasis with caster ball.
Wheel Encoders.
XBee 2mW PCB Antenna - Series 2 (ZigBee Mesh)  Transceiver module for the communication between two robots.
IR sensors.

6.Micro DC Geared Motor w/ Back Shaft (180rpm 6V).
I have done the programming for obstacle detection, positioning of robot, but I have no idea how to do the master slave programming logic.
Please help me on this. Here attached the code I have done till now:

const int InfraredSensorPin1 = 6;//Connect the signal pin to the digital pin 6
int detected2;
int detected1;
const int InfraredSensorPin2 = 9 ;

int E1 = 5;     //M1 Speed Control
int E2 = 6;     //M2 Speed Control
int M1 = 4;    //M1 Direction Control
int M2 = 7;    //M1 Direction Control

#define LEFT 0
#define RIGHT 1
int value;
long coder[2] = {
  0, 0
};
int lastSpeed[2] = {
  0, 0
};

void stop(void)                    //Stop
{
  digitalWrite(E1, 0);
  digitalWrite(M1, LOW);
  digitalWrite(E2, 0);
  digitalWrite(M2, LOW);
}
void advance(char a, char b)         //Move forward
{
  analogWrite (E1, a);
  digitalWrite(M1, HIGH);
  analogWrite (E2, b);
  digitalWrite(M2, HIGH);
}
void back_off (char a, char b)         //Move backward
{
  analogWrite (E1, a);
  digitalWrite(M1, LOW);
  analogWrite (E2, b);
  digitalWrite(M2, LOW);
}
void turn_L (char a, char b)            //Turn Left
{
  analogWrite (E1, a);
  digitalWrite(M1, LOW);
  analogWrite (E2, b);
  digitalWrite(M2, HIGH);
}
void turn_R (char a, char b)            //Turn Right
{
  analogWrite (E1, a);
  digitalWrite(M1, HIGH);
  analogWrite (E2, b);
  digitalWrite(M2, LOW);
}

void setup(void)
{ Serial.println("Start!");

 pinMode(InfraredSensorPin1, INPUT);
 pinMode(InfraredSensorPin2, INPUT);

advance(200,200);
  Serial.begin(19200);      //Set Baud Rate//
  attachInterrupt(LEFT, LwheelSpeed, CHANGE);    //init the interrupt mode for the digital pin 2
  attachInterrupt(RIGHT, RwheelSpeed, CHANGE);   //init the interrupt mode for the digital pin 3
}
void loop(void)
{
  if((InfraredSensorPin1==LOW&&!InfraredSensorPin2==LOW)||(InfraredSensorPin1==LOW&&InfraredSensorPin2==LOW))
  turn_L (100,100);

  else if ((InfraredSensorPin2==LOW&&!InfraredSensorPin1==LOW)||(InfraredSensorPin2==LOW&&InfraredSensorPin1==LOW))
  turn_R (100,100);

  else
  advance (80,80);
  static unsigned long timer = 0;                //print manager timer
  if (millis() - timer > 5) {
    Serial.print("Coder value: ");
    Serial.print(coder[LEFT]);
    Serial.print("[Left Wheel] ");
    Serial.print(coder[RIGHT]);
    Serial.println("[Right Wheel]");

    lastSpeed[LEFT] = coder[LEFT];   //record the latest speed value
    lastSpeed[RIGHT] = coder[RIGHT];
    coder[LEFT] = 0;                 //clear the data buffer
    coder[RIGHT] = 0;
    timer = millis();
  }
}
void LwheelSpeed()
{
  coder[LEFT] ++;  //count the left wheel encoder interrupts
}
void RwheelSpeed()
{
  coder[RIGHT] ++; //count the right wheel encoder interrupts
}

You can format your code with the {} button in the post editor.


text:
Atmega328 xbee and softaware serial libraries
I use an atmega328 with fdti cable wired at rx/tx and i want to connect a zigbee s2 at diferrent pins. I have tried to use  SoftwareSerial library but i would like to use the xbee library too. Is there a way to use both libraries? If there is no way doing this, is it a problem to connect both fdti cable and zigbee at the same rx/tx? In the future, in opposition to fdti cable i will use a micro usb avr.


text:
How can I interface EEPROM in websocket via Arduino?
I am at beginner level and I wanted to implement EEPROM write after receiving data from a websocket. If the websocket doesn't receive any data within 5 seconds then I want to write to EEPROM the value I sent via websocket to turn on and off the led.
Here is my code please if you can help me out to solve this problem. Thank you. I have modified the code for my need, but I need EEPROM for websocket if possible.
#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

WiFiServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);

const int pin_led = 5;
unsigned int value;
String data;
const char *msg_toggle_led = "toggleLED";
const char *msg_get_led = "getLEDState";
char msg_buf[10];
int led_state = 0;
int counter = 0; // for EEPROM testing

char* ssid = "esp8266websocket_1";
char* password = "123456789";

void setup() {
  // EEPROM.begin(512);
  pinMode(pin_led, OUTPUT);
  digitalWrite(pin_led, LOW);
  Serial.begin(115200);
  Serial.println();
  Serial.println("Serial started at 115200");
  Serial.println();
  // Connect to a WiFi network
  Serial.print(F("Connecting to ")); Serial.println(ssid);
  WiFi.mode(WIFI_AP);
  IPAddress apLocalIp(10, 50, 1, 1);
  IPAddress apSubnetMask(255, 255, 255, 0);
  WiFi.softAPConfig(apLocalIp, apLocalIp, apSubnetMask);
  WiFi.softAP(ssid, password);
  WiFi.setSleepMode(WIFI_NONE_SLEEP);
  Serial.println("");
  Serial.println(F("[CONNECTED]")); Serial.print("[IP "); Serial.print(WiFi.localIP());
  Serial.println("]");
  // start a server
  server.begin();
  Serial.println("Server started");
  webSocket.begin();
  webSocket.onEvent(onWebSocketEvent);
  //Serial.print(webSocket.localIP());
}

void loop() {
  webSocket.loop();
}

// Called when receiving any WebSocket message
void onWebSocketEvent(uint8_t client_num, WStype_t type, uint8_t * payload, size_t length) {
  // Figure out the type of WebSocket event
  switch (type) {
    // Client has disconnected
    case WStype_DISCONNECTED:
      Serial.printf("[%u] Disconnected!\n", client_num);
      break;
    // New client has connected
    case WStype_CONNECTED:
      {
        IPAddress ip = webSocket.remoteIP(client_num);
        Serial.printf("[%u] Connection from ", client_num);
        Serial.println(ip.toString());
      }
      break;
    // Echo text message back to client
    case WStype_TEXT:
      Serial.printf("[%u] Text: %s\n", client_num, payload);
      webSocket.sendTXT(client_num, payload);
      // data = webSocket.getData(payload);
      Serial.printf("[%u] Received text: %s\n", client_num, payload);
      // Toggle LED
      if ( strcmp((char *)payload, "toggleLED") == 0 ) {
        counter++;
        led_state = led_state ? 0 : 1;
        //sprintf(msg_buf, "%d", led_state);
        Serial.printf("Toggling LED to %u\n", led_state);
        digitalWrite(pin_led, led_state);
        // webSocket.sendTXT(client_num, msg_buf);
        // Report the state of the LED
      } else if ( strcmp((char *)payload, "getLEDState") == 0 ) {
        sprintf(msg_buf, "%d", led_state);
        Serial.printf("Sending to [%u]: %s\n", client_num, msg_buf);
        webSocket.sendTXT(client_num, msg_buf);
        // Message not recognized
      } else {
        Serial.println("[%u] Message not recognized");
      }
      break;
    // For everything else: do nothing
    case WStype_BIN:
    case WStype_ERROR:
    case WStype_FRAGMENT_TEXT_START:
    case WStype_FRAGMENT_BIN_START:
    case WStype_FRAGMENT:
    case WStype_FRAGMENT_FIN:
    default:
      break;
  }
}

I am not using SPIFFS. I am calling a webpage in HTML which is:
<style>
input[type="text"]{
width: 90%;
height: 3vh;
}

input[type="button"]{
width: 9%;
height: 3.6vh;
}

.rxd{
height: 90vh;
}

textarea {
width: 99%;
height: 100%;
resize: none;
}

</style> <script> var Socket; function start() { Socket = new WebSocket('ws://10.50.1.1:81/'); Socket.onmessage = function(evt) { document.getElementById("rxConsole").value += evt.data; } } function enterpressed() { Socket.send(document.getElementById("txbuff").value); document.getElementById("txbuff").value = ""; } </script>

<textarea id="rxConsole" readonly></textarea>

Please help to implement EEPROM in websocket because if the websocket starts it stays there as long as clients are connected. So I need help to implement websocket for ToggleLED status to save data after 5 seconds if there is no data coming from the html webpage.

test and learn how to use the EEPROM on esp8266 with a separate test sketch without any other functions

Hello Juraj,I am at beginner level so i have done work around with EEPROM without any function but here its tricky because i am using TCP IP protocol in ESP-8266 and also websocket so if my device gets disconnected then only my EEPROM will initiate or else help me with interrupt ISR how to implement it.Kindly help thank you!

what ISR? in the sketch in the question there is no code working with EEPROM

Hello Juraj, I would like to implement it but i need some help regarding it i know i haven't used in code and that is my question sir. ISR is Interrupt Service Routine.

if you can use EEPROM in test sketch what is the problem to use it a sketch in question? and how should we know where and how in the sketch do you want to use it? and what has an ISR to do with this? there is no ISR in the sketch in question? this is a Q&A site not a forum for project guidance. https://arduino.stackexchange.com/tour

I am sorry sir but i required some guidance regarding EEPROM implementation inside my websocket sketch so kindly help me where should i have guidance regarding it. Thank you sir.

https://forum.arduino.cc/


text:
Why does my program stop working? (MPU6050)
I'm using the DMP example from Jeff Rowberg's MPU library (with Arduino UNO) and it works well. But with this simple modification it works for a while and then stops. I don't understand why this is happening. If someone knows this will help me a lot. Thanks!
//GND - GND
//VCC - VCC
//SDA - Pin A4
//SCL - Pin A5
//INT - Pin 2

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

MPU6050 mpu; //Declaramos el sensor en la dirección por defecto (0x68),AD0 a LOW

#define INTERRUPT_PIN 2 //Definir el pin de interrupciones
#define LED_PIN 13
bool blinkState = false;

//Variables de control y estado del MPU
bool dmpReady = false; // Es true si la inicialización del DMO es exitosa
uint8_t mpuIntStatus; // Mantiene el estado actual del byte de las interrupciones
uint8_t devStatus; // Devuelve el estado después de cada operación del dispositivo(0 = exitoso, !0 = error)
uint16_t packetSize; // Tamaño esprado del paquete (por defecto es 42 bytes)
uint16_t fifoCount; // Cuenta todos los valores actules en el FIFO
uint8_t fifoBuffer[64]; // Buffer de almacenamiento

//Variables de orientación y movimiento
Quaternion q;           // [w, x, y, z]
VectorInt16 aa;         // [x, y, z]
VectorInt16 aaReal;     // [x, y, z]
VectorInt16 aaWorld;    // [x, y, z]
VectorFloat gravity;    // [x, y, z]
float ypr[3];           // [yaw, pitch, roll]
float yaw;
float pitch;
float roll;
int izquierda = 0;
int derecha = 0;

volatile bool mpuInterrupt = false;
void dmpDataReady() {
  mpuInterrupt = true;
}

void setup() {
  //Iniciar comunicación con el bus I2C
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif
  Serial.begin(38400);
  // Iniciar MPU6050
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);

  // Comprobar  conexion
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  // Iniciar DMP
  Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();
  // Valores de calibracion
  mpu.setXGyroOffset(219);
  mpu.setYGyroOffset(75);
  mpu.setZGyroOffset(-19); //85
  mpu.setZAccelOffset(1688);
  // Activar DMP
  if (devStatus == 0) {
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);
    // Activar interrupcion
    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();
    Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;
    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }
}

void loop() {
  // Si fallo al iniciar, parar programa
  if (!dmpReady) return;
  // Ejecutar mientras no hay interrupcion
  while (!mpuInterrupt && fifoCount < packetSize) {
    // AQUI EL RESTO DEL CODIGO DE TU PROGRRAMA
  }
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();
  // Obtener datos del FIFO
  fifoCount = mpu.getFIFOCount();
  // Controlar overflow
  if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
  } else if (mpuIntStatus & 0x02) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);
    mpu.resetFIFO();
    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;
    // Mostrar Yaw, Pitch, Roll
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    yaw = -ypr[0] * 180 / M_PI;
    pitch = ypr[1] * 180 / M_PI;
    roll = ypr[2] * 180 / M_PI;
    if (yaw > 90) {
      izquierda = 1;
      derecha = 0;
    }
    if (roll > 90) {
      derecha = 1;
      izquierda = 0;
    }
    if (yaw < 90 && roll < 90) {
      derecha = 0;
      izquierda = 0;
    }
    Serial.print("ángulos\t");
    Serial.print(yaw);
    Serial.print("\t");
    Serial.print(pitch);
    Serial.print("\t");
    Serial.print(roll);
    Serial.print("\t");
    Serial.print("izquierda");
    Serial.print("\t");
    Serial.print(izquierda);
    Serial.print("\t");
    Serial.print("derecha");
    Serial.print("\t");
    Serial.println(derecha);
  }
}

What simple modification? And where does it stop? Have you tried to hunt down the problem by using Serial prints?

this is my modification:                                                                                yaw = -ypr[0] * 180 / M_PI;
pitch = ypr[1] * 180 / M_PI;
roll = ypr[2] * 180 / M_PI;
if (yaw > 90) {
izquierda = 1;
derecha = 0;
}
if (roll > 90) {
derecha = 1;
izquierda = 0;
}
if (yaw < 90 && roll < 90) {
derecha = 0;
izquierda = 0;
}

I've used the serial monitor to print the yaw, pitch and roll. I think it stops in this line :      if (!dmpReady) return;                                                                                But I don´t know why the dmp doesn't work.


text:
Modifying Print.h on a Mac
Most of my Arduino work has been on a PC, but now I am on a Mac. I need to modify Print.h to give me printf facilities, as detailed here.
I can find Print.h buried within my application files, but changing it has no effect. A search across my disk reveals no further Print.h files.
Where on a Mac should I find and edit the Print.h file?
Can someone tell me what I am missing please?
Thanks,
Martin

We don't know what you've done, so we can't tell you what you've done wrong.

I don't much like their way of allocating a fixed 128 byte buffer in their wrapper in that code. Nasty. Better (though maybe slightly slower) would be to use vsnprintf() twice - once with a size of 0 to calculate how much space is needed, then alloca() that space (plus 1), and then call vsnprintf() again with the buffer and its proper size to fill it. Only uses the memory required then...

There must be a print.h in the Arduino IDE. Try to reinstall. In this webpage, there is no specification about the platforms where it is neither where it's not.
And, of course, you don't need to edit anything: use a medium/big sized string with sprintfand you could use the printf capabilities.

Each hardware package has its own version of Print.h in the cores folder. The Arduino IDE installation includes a copy of the Arduino AVR Boards hardware package but that package will not be used if you installed a different version via Boards Manager (Tools > Board > Boards Manager) or if you have a board selected from the Tools > Board menu that is not part of the Arduino AVR Boards package. Operating systems seem to like to hide the folder that Boards Manager installs the hardware packages to by default, which makes things more confusing.
The easiest way to find the location of the active hardware package, and thus the Print.h you want to edit is this:

Select a board of the hardware package you want to locate from the Tools > Board menu.
File > Examples > SPI > BarometricPressureSensor (or any other example sketch of the SPI library)
Sketch > Show sketch folder - this will open the BarometricPressureSensor example sketch folder.
Navigate up 4 folder levels to the architecture folder.
Open the cores subfolder of the architecture folder.
If there are multiple folders inside the cores folder you will need to open boards.txt (which is located in the architecture folder) and find which core library your board is using, which is specified by the build.core property. Most hardware packages only have a single core library so this should not be necessary.
Open the core folder. There you will find Print.h.

The reason I selected the SPI library example is because this is a hardware specific library that is bundled with all hardware packages I've encountered. If you encounter a hardware package that does not bundle an SPI library you would want to open the example for another hardware specific library such as Wire, SoftwareSerial, or EEPROM.


text:
External Flash Memory for ATtiny85
I'm designing a lightweight circuit, but the ATtiny85 micro-controller I'm using to power it doesn't have nearly enough flash memory to store the code for the devices I'll have hooked up to it (It has 8kb of flash). I was wondering if it'd be possible to have the ATtiny use compiled code from an external flash memory chip of larger capacity elsewhere on the board like its own internal memory. Thanks in advance.

No, it's not possible.
AVR chips can only execute code from their internal flash.

Although you can put a VM in the internal flash and then run bytecode from anywhere.

Well, yes, but only if you're a complete psychopath. Talk about resource wastage on an already resource starved chip...

You could write a small bootloader and load code segments when needed. The internal flash can be written at least 10,000 times so you cannot swap segments too often.
To do this you need to 1) write a bootloader that can load segments from the external flash, 2) partition your sketch into segments, 3) compile and link them to the same address space in program memory, 4) write the segments to the external flash memory.
Extra is handling segment to segment calls as special care is needed by the loader.
An even more elaborate scheme is to allow multiple modules and swap them depending on the execution path (e.g. module to module calls). Segments would be built up of modules, and modules would be reusable between segments. What modules are in memory would depend on some "statistics". This is basically what the instruction cache does in modern processors.
Typical segments could be application level sub-functions such as printing, uploading measurements, etc. Typically functions that are not used very frequently, and where the "background" application is stopped, e.g. data collect.

Although you cannot run code from external (S)RAM, you can:

optimize your code (reducing the number of lines of code by):

use parameterized functions instead of copying/paste code
reduce the type (storage) variables (like constants) which are kept in memory, e.g. instead of 200 integers of 2/4 bytes use 200 bytes
instead of storing const calculated array values, calculate them runtime (causing a performance reduction)
remove unused libraries
strip down used libraries (not needed to remove unused functions)


text:
Confused between SPI and I2C for SSD1306 OLED
I recently got myself an SSD1306 OLED display:
I haven't been able to successfully wire it to an Arduino (Mega 2560) however. I have been reading up on I2C and SPI and checked some libraries from Adafruit and U8G2.
However, I'm confused, since most of the Internet is talking about a similar OLED display with GND - VDD - SCL - SDA labelled pins, where mine has SCK instead of SCL.
Now, the number of pins make me believe I need to interface with I2C, but the SCK label points to SPI, right?
One person seemed to have the same problem as me, but the solution he got (pull-up resistors) didn't do the trick for me, I'm afraid.
So, my question remains: how to wire this OLED display to the Mega 2560?
Much appreciated if someone could point me to the right direction.
Thanks!

manufactures are terrible about printing the right labels on those interface pins. i've seen SPI MOSI labeled: MOSI / SPI / DO / SDI / SDA / AD / A0 and DC; some of those aren't even close! there's only 2 wires, so that's a I2C. try flipping the pins if it doesn't work; ive seen them labeled backwards too.

SCK and SCL are the same thing.

Serial ClocK
Serial CLock

They seem to be interchangeable. The fact you have SDA (Serial DAta) as opposed to separate SDI / SDO or MOSI / MISO pins means it's I2C.
Wire it like you would any other I2C device.

It is i2c, but these display are known for disturbing the i2c bus. They might be 3.3V i2c, or missing an acknowledge. Adafruit adds a i2c level shifter to similar oled displays. The U8g2 has an option for software i2c without acknowledge.

thanks a lot, that works (also, for reference: the I2C address for this display is 0x3C)

U8g2 in software I2C mode works well on the GM009605 v4. I can pretty much use any pin. Looks stable too.

I have what appears to be the same display (GM009605 v4) and while both SCL and SCK both stand for Serial Clock many development boards have different SCK and SCL pins that you'd need to interface. On a Wemos d1 mini for example I have this display plugged into SDA => D2 & SCK => D5 where as if it was SCL it would to to D1.
FWIW I use the Wire.h and SSD1306.h libraries (https://github.com/ThingPulse/esp8266-oled-ssd1306) to interface with the display using the Wemos D1 mini.


text:
RFID-RC522 Can't read from MIFARE Ultralight
I tried many ways to get and print UID and other data from a MIFARE Ultralight, but it always ends with an error. I am using the RFID-RC522 reader with an Arduino UNO and thr MFRC522 Library.
I can normally get and print the PICC type of the chip, but that's the only thing that works.
This is how I have connected my RC522 reader:

(source: ytimg.com)
This is my code:
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN 9
#define SS_PIN 10

MFRC522 rfid(SS_PIN, RST_PIN);

unsigned long noSignal = 0;

bool lastState = true;
bool read = true;

void setup()
{
    pinMode(2, OUTPUT); //Red led
    pinMode(3, OUTPUT); //Green led

    Serial.begin(9600);
    SPI.begin();
    while (!Serial);

    rfid.PCD_Init();
    Serial.println("RFID ctecka byla uspesne spustena."); //Prints "RFID Reader succesfully started"
    Serial.println();

    changeLed(true);
}

void changeLed(bool red)
{
    digitalWrite(2, red);
    digitalWrite(3, !red);
}

void loop()
{
    if (millis() - noSignal >= 300)
    {
        changeLed(true);
        read = true;
    }

    bool state = !rfid.PICC_IsNewCardPresent() && !rfid.PICC_ReadCardSerial();

    if (state != lastState)
        if (state)
            noSignal = millis();
        else if (read)
        {
            read = false;

            changeLed(false);
            noSignal = millis();

            Serial.println("---------Cip detekovan----------"); //Prints "Chip detected"
            Serial.println();

            MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);

            Serial.print("Znacka cipu: ");//Prints chip type
            Serial.println(rfid.PICC_GetTypeName(piccType));

            rfid.PICC_DumpToSerial(&rfid.uid); //Here is the error

            Serial.println();
            Serial.println("---------Cteni skoncilo----------");//prints "Read ended"
            Serial.println();

            rfid.PICC_HaltA();
            rfid.PCD_StopCrypto1();
        }

    lastState = state;
}

Serial monitor snapshot:

Maybe an important thing is that when I call PCD_DumpVersionToSerial() I get:
Firmware Version: 0x12 = (unknown)

Somewere I read that my Arduino isn't compatibile with MIFARE Ultralight and I need MIFARE Classic cards. Is that true? Can I solve this problem by using another library or is it a hardware problem?
EDIT:
I asked my friend, who has an Arduino too from the same shop as me, if he can read MIFARE Ultralight cards. He said that it's working for him. So my problem will be probably on the hardware side. We both have unofficial Arduinos from AliExpress.

In the first lines of code there are two lines that say:
#define RST_PIN 9
#define SS_PIN 10

They define the RESET pin to be on the D9 pin and the SDA on the D10 pin.
So you have an connection error try connecting like shown and you should be good to go.

Sorry, I made mistake. I have connected pins like in your picture. I will update my question.

@DavidMoškoř have you tried the original example?

Yes, same result

Is it possible that my cards are using encryption DES3 that my arduino cannot decrypt?

@DavidMoškoř it is possible that your card use a different frequency.


text:
Arduinino & Max7219
I'm using a MAX7219 and 6 (six) seven segment displays
I used my own board and two purchased on ebay - no difference in operation.
MOSI, and CLK are correct and verified with my scope (Tektronics)
CS (chip select) is pin 22 (for no particular reason) SPI is set to Mode0
Yes, I have tried other pins as CS - all work the same.
My MEGA board can be powered by USB or 9.9 VDC wall-wart - no difference
Trial code is shown below, and works properly.
Placed 47 uF 50V cap on display board between +5 and GND - no effect
Placed 220 uF 35V cap on display board between +5 and GND - no effect
MOSI, SCK and CS are verified with scope to be 5 VDC. Compiler and D/L applications are set to MEGA and seem to work properly.
PROBLEM IS THIS:
Code compiles and D/L properly into Mega. Mega resets, and about 50% of the time all digits illuminate (not executing code properly?) Digit 0 (most right hand digit is enabled) never works. I can press the reset on the Mega as many times as I want - no effect.
HOWEVER if I pull either +5 or GND to the MAX7219 module, and reset my Mega, it works perfectly. Yes, this is obviously a reset problem, but I've never seen a reset problem before with the MAX7219. I put delays at the beginning at short delays in the SPI communications to no effect.
Has anyone ever seen anything like this before? I have no hair left to pull. I'm thinking maybe to use a MOSFET to turn the MAX7219 on after the MEGA is up and running. Any suggestions are appreciated.
 //version 0.1
 #include <SPI.h>
 #define LOAD_PIN 22

 void maxTransfer(uint8_t address, uint8_t value) {

 digitalWrite(LOAD_PIN, LOW);      // Ensure LOAD/CS is enabled (LOW)
 SPI.transfer(address);            // Send the register address
 SPI.transfer(value);              // Send the value
 digitalWrite(LOAD_PIN, HIGH);     // Tell chip to toggle in data

}

void setup() {

 pinMode(LOAD_PIN, OUTPUT);          // Set port pin to output

                 // Reverse the SPI transfer to send the MSB first
 SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));

                 // Start SPI with attributes in "SPI.beginTransaction"
delay(250);
SPI.begin();
 maxTransfer(0x09, 0xFF);           // Enable mode B
 maxTransfer(0x0A, 0x0F);            // Use highest intensity
 maxTransfer(0x0B, 0x00);           // Only scan digit 0
 maxTransfer(0x0C, 0x01);            // Turn on chip
}

void loop() {

  // Loop through each code
  for (uint8_t i = 0; i < 0x10; ++i)
  {
    maxTransfer(0x01, i);
    delay(50);
  }
}

Try adding a pull-down resistor to the CS pin. That way the pin isn't floating during power-up.

@Gerben - I added a pulldown resistor and it improved the reset about 50% of the time. Under SPI.begin I added:
maxTransfer(0x00, 0x0);           // flush SPI
and now it resets properly each time. I don't know how I missed these things! Thank you very much for your help.


text:
Arduino Mega + ESP8266 - Post Data to website issue
I'm trying to post data to my SQL database and it seems that I'm not sending the data correctly. My PHP file is working since I have tried it and it writes to the database.
I am getting an esp.find("SEND OK") but I must be sending it wrong or something.
Here is the code:
DT 0050 - GLASSES - from sun to sound - chk oil filter malibu old or new?
void loop() {
    // call sensors.requestTemperatures() to issue a global temperature
    // request to all devices on the bus
    Serial.print(" Requesting temperatures...");
    sensors.requestTemperatures();  // Send the command to get temperatures
    char tempC = sensors.getTempCByIndex(0);
    char buffer[10];
    Serial.println("DONE");
    Serial.print("Temperature for Device 1 is: ");
    // You can have more than one IC on the same bus.
    // 0 refers to the first IC on the wire
    Serial.print(sensors.getTempCByIndex(0));   // "byIndex"
    delay(5000);
    data = "temperature=" + tempC;  // d
    httppost();
    delay(1000);
}

void httppost() {
    esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");   //start a TCP connection.
    if (esp.find("OK")) {
       Serial.println("\r\nTCP connection ready");
    }
    delay(1000);
    String postRequest =
        "POST /http://manilla.technoaid.net/esp8266.php HTTP/1.1\r\n"
        "Host: 66.96.134.25\r\n" "User-Agent: Arduino/1.0\r\n"
        "Connection: close\r\n"
        "Content-Type: application/x-www-form-urlencoded\r\n"
        "Content-Length: \r\n" "data";
    **String sendCmd = "AT+CIPSEND=";
    esp.print(sendCmd);
    esp.println(postRequest.length());
    delay(1000);
    if (esp.find(">")) {
        Serial.println("Sending..");
        esp.print(postRequest);
        if (esp.find("SEND OK")) {
            Serial.println("Packet sent");
            while (esp.available()) {
                String tmpResp = esp.readString();
                Serial.println(tmpResp);
            }
            // close the connection
            esp.println("AT+CIPCLOSE");
        }
    }
}

Your **String and your empty Content-Length look suspicious. Also, there should ne \r\n\r\n between the headers and the actual data.


text:
Arduino "Maximum Power point tracker" (MPPT) Problem
I need an IV curve for a solar panel. As far I know, solar-panel and Diode IV curve pretty much the same. Here, I am using diodes(6A10-1) as a solar-panel. Where each Diode voltage drops 0.6volt. I provide 4.8v across the diodes from a power supply and limited the current at 1amp of the power supply for acting like a solar panel.
The number of diodes is 8 for a 4.8V drop. A 1-ohm resistor for measuring the current. I am using Arduino to measure the value of current and voltage by varies the MOSFET(IRF540) gate voltage. A low pass filter is connected between D2 and Mosfet Gate. A0 for measuring the solar voltage and Current, Id=A0-A1.
But Arduino gives incorrect values of A1 and current, Id, and sometimes negative values with respect to a multimeter.
[
const int V1 = A0;
const int V2 = A1;
float SolarVolt = 0.0;
float V1_VOLT = 0.0;
float V2_VOLT = 0.0;
float Id  = 0.0;
int V1_value = 0;
int V2_value = 0;
double gateVoltage=150; //For Gate volt
double mstep=5.1;
int GatePin=2;

void setup() {
  pinMode(GatePin,OUTPUT);
  Serial.begin(9600);
  pinMode(V1,INPUT);
  pinMode(V2,INPUT);
}

void loop() {
  analogWrite(GatePin,gateVoltage);
  gateVoltage=gateVoltage+mstep;
  Serial.print("GateVolt = ");
  Serial.print(gateVoltage);
  Serial.print("    ");
  if (gateVoltage <= 0) {
    mstep = 1;
  } else if (gateVoltage>=255){
    gateVoltage = 255;
    mstep = -1;
    delay(50);
  }

  V1_value = analogRead(V1);
  V1_VOLT = (V1_value * 5.0) / 1024.0;

  Serial.print("V1_VOLT= ");
  Serial.print(V1_VOLT);
  Serial.print("    ");

  V2_value = analogRead(V2); // for Id1
  V2_VOLT= (V2_value * 5.0) / 1024.0;

  Serial.print("V2_VOLT= ");
  Serial.print(V2_VOLT);
  Serial.print("    ");

  Id=V1_VOLT-V2_VOLT;

  Serial.print("ID= ");
  Serial.print(Id);
  Serial.println();

  delay(1000);
}

The garbage values like -0.5V,-0.02,-1.2V,+4V. I measured with a multimeter and the multimeter shows the correct values. PWM signal passed through a low pass filter, which gives a triangular DC voltage to the gate. No, I did not use any external DAC.

What values are you seeing? Have you measured the voltages with a multimeter? You do realise you are trying to send a PWM signal to the FET's gate, or do you somehow have a DAC on pin 2?

What raw Vx_value-s are you getting from the analogRead(Vx)? BTW Id = (V1-V2)/R.

Here R is one ohm. That's why  Id = (V1-V2). Vx values are some times positive some times negative. But I didn't get the correct values with respect to multimeter.

Are you getting negative values for V1_value and V2_value?

Your current signal will also show PWM, so you will need to filter that before measuring.  It would be much simpler if you could rearrange your circuit to put the sense resistor on the ground side of the MOSFET, since then you can use a simple RC filter and a single A0 measurement.   Also, you wouldn't have to worry about the no-load voltage from the solar panel (when the MOSFET is off) going above the 5V limit of the A0 pin.

A low pass filter is connected between D2 and Mosfet Gate. Yes, I also told my faculty to put the sense resistor on the ground side of the MOSFET. But he told me to not connect it there. But  I forget the reason. Thank you.