text:
What's wrong with my keypad and time program?
I really need help here. I'm a total noob in Arduino and this is my first Arduino project. I've been trying to get the keypad to be able to input time for my alarm clock project but I only managed to get the welcome part of the program. But then the display stuck at the welcome part only. I want to set alarm time by using the keypad only, and if the alarm time is the same as the time display, the buzzer should ring.
Plus, the deadline is in two days. I'm certain that there's no problem with hardware since all of the components (16x2 LCD, RTC DS1307, buzzer, 4x4 keypad) work properly when I use some basic tutorial coding for the components.
Please check what could be wrong in my code? I've tried to replace some of the codes but it had no change; the display's still stuck at the welcome part.
[Edit]I've added the "milli" code at the timedate() part. But I'm not sure, how to improve the alarm() part of this code? I can't input any key to insert the alarm time at this part.
If there's any update on what I've edit to my code later, I will edit this question's body. Thank you in advance.
#include <EEPROM.h>
#include <Keypad.h>
#include <DS1307.h>
#include <Wire.h>
#include <LiquidCrystal.h>
DS1307 rtc(SDA, SCL);
LiquidCrystal lcd(A3, A2, A1, A0, 5, 4);
Time t;

#define buz 3

int Hor, Min, Sec, h, m, s;
int ASCII = 48;
char* tim;
char* dat;
char buffer[3];
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {6, 7, 8, 9};
byte colPins[COLS]= {10, 11, 12, 13};
Keypad keypad= Keypad(makeKeymap(keys),rowPins, colPins, ROWS, COLS);

unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {
Wire.begin();
rtc.begin();
pinMode(buz, OUTPUT);
lcd.begin(16, 2);
welcome();

rtc.setDOW(TUESDAY); //Set Day-of-Week to SUNDAY
rtc.setTime(18, 20, 00); //Set the time to 12:00:00     (24hr format)
rtc.setDate(18, 12, 2018); //Day, Month, Year
}

void loop() {
t = rtc.getTime();
Hor = t.hour;
Min = t.min;
Sec = t.sec;
tim = rtc.getTimeStr();
dat = rtc.getDateStr();
char key = keypad.getKey();

if(key == 'A'){
alarm();
}

if (key == 'C'){
digitalWrite(buz, LOW);
EEPROM.write(2, ASCII+6);
EEPROM.write(3, ASCII);
}
changealarm();
checkalarm();
timedate();
}

void checkalarm(){
if( Hor == h && Min == m)
{
delay(3000);
lcd.setCursor(0,1);
lcd.print("Hold C");
digitalWrite(buz, HIGH);
delay(3000);
}
}

void changealarm(){
buffer[2] = 0;
buffer[0] = EEPROM.read(0);
buffer[1] = EEPROM.read(1);
h = atoi(buffer);
buffer[0] = EEPROM.read(2);
buffer[1] = EEPROM.read(3);
m = atoi(buffer);
buffer[0] = EEPROM.read(4);
buffer[1] = EEPROM.read(5);
s = atoi(buffer);
}

void timedate(){
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Date: ");
lcd.print(rtc.getDateStr());

lcd.setCursor(0,1);
lcd.print("Time: ");
lcd.print(rtc.getTimeStr());
delay(3000);
lcd.setCursor(0,1);
lcd.print("Alarm: ");
lcd.print(h);
lcd.print(":");
lcd.print(m);
lcd.print(":");
lcd.print(s);
}
}

void welcome(){
lcd.setCursor(0,0);
lcd.print("Welcome");

lcd.setCursor(0,1);
lcd.print("To");
delay(2000);

lcd.setCursor(0,1);
lcd.print("TIMe Project");
delay(2000);
}

void alarm()
{
int j=0;
char key = keypad.getKey();
lcd.clear();
lcd.print("Enter Alarm Time: ");
lcd.setCursor(0,1);
while(j<4)
{
lcd.print(h);
lcd.print(":");
lcd.print(key);
lcd.print(m);
lcd.print(":");
lcd.print(key);
lcd.print(s);
lcd.print(key);
key=0;
}
delay(500);
}

Your function timedate() is called every time through loop() and it has a total of 6000ms of delay. During a delay, NOTHING can happen, not even checking for a keypress.
So, you would have to hold the desired key down until the key = keypad.getKey() statement is executed, which is a minimum of every 6 seconds.
Use of delay() for an interactive program in which user input can happen any time is not desired. Instead, there is a popular example Arduino sketch called "BlinkWithoutDelay" which us used as an explanation of how to avoid using delay() by letting your loop() function run at very high speed and only taking the desired action if the desired time has elapsed since some initiating action.
The more generic concept is called a "State Machine" and there are numerous websites that attempt to teach it, such as this one.
Be prepared to make significant changes to the structure of your program, however, as moving from delay() usage to state machine usage means a re-thinking of your loop() function -- you have to consider it running tens of thousands of times per second, and most of those times it doesn't do anything but check if something needs to be done -- most often the answer is "no, nothing needs to be done this time."

Thank you sir, I'll try to understand the concept first. I've edited the question as I'm quite not sure regarding the alarm() code part.

No, your alarm() function has an infinite loop, where you loop while j<4, but never adjust j.


text:
Sketch starts and keeps counting on external power supply but not usb
Thank you for the add, total newbie here (electronics and arduino) on his first project.
Trying to make a counter for a hay baler with two HAL effect sensors, (pin 5 & 6) and outputting to an I2C display.
One counts the amount of flakes per bale and the other the amount of bales (resetting the flakes on each bale and displaying an average)
I works perfectly whilst powered through USB, plug the 12v in and the counter just goes nuts and keeps counting without the magnet passing by the sensor.

I have checked if there is 5v at the 5v pin.
As soon as you take the trigger out of pin 5 or 6 the corresponding counter stops, put anything in the pin (even a bit of wire or a diode) and the counter starts taking off again.

//Bale and flake Counter
//Lourens Houttuin
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
//i2c pins
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); //
// set up a constant for the tilt switchPin
const int flakePin = 6;
const int balePin = 7;

int bales = 0;
int flakes = 0;
int avflakes = 0;

// variable to hold the value of the flakePin & bale pin
int switchState = 0;
int baleswitchState = 0;

// variable to hold previous value of the flakepin
int prevSwitchState = 0;
int prevBaleswitchstate = 0;

void setup() {
  // set up the number of columns and rows on the LCD
  lcd.begin(16, 2);

  // set up the switch pin as an input
  pinMode(flakePin,INPUT);
  pinMode(balePin,INPUT);

 lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Flakes: 0");
}

void loop() {
  // check the status of the switch
  switchState = digitalRead(flakePin);
  baleswitchState = digitalRead(balePin);

  // compare the switchState to its previous state
  if (baleswitchState != prevBaleswitchstate){
    if (baleswitchState == LOW) {
      bales = bales + 1;
      flakes = 0;
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Flakes:");
      lcd.setCursor(8, 0);
      lcd.print(flakes);
      lcd.print("/");
      lcd.print(avflakes/bales);
      lcd.setCursor (0,1);
      lcd.print("Bales:");
      lcd.setCursor (8,1);
      lcd.print(bales);
    }
  }
  if (switchState != prevSwitchState) {
    if (flakes>13){
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Flakes:");
      lcd.setCursor(8, 0);
      lcd.print("Speed UP");
    }
    if (switchState == LOW) {
      flakes = flakes + 1;
      avflakes=avflakes+1;
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Flakes:");
      lcd.setCursor(8, 0);
      lcd.print(flakes);
      lcd.print("/");
      lcd.print(avflakes/bales);
      lcd.setCursor (0,1);
      lcd.print("Bales:");
      lcd.setCursor (8,1);
      lcd.print(bales);
    }
  }
  // save the current switch state as the last state
  prevSwitchState = switchState;
  prevBaleswitchstate = baleswitchState;
}

Edit your code to post properly - indent the lines with 4 spaces I think will do it. Is it 12V DC, not AC? The regulator and caps aren't really set up for heavy duty AC/DC conversion.

Can you show your wiring? What sort of 12V supply is it? Perhaps the supply is outputting noise which is triggering the Hall effect sensors.

Are your Hall Effect sensors logic output or analog?I have seen both types -- logic output will have HIGH or LOW only, but analog will vary the output voltage in accordance with the strength and polarity of the magnetic field. If a logic output, then is it open-collector and thus needs a pull-down or pull-up?

I'll try fix the code and upload schematic when I get to my computer.
I have 12v dc 1.25A
I believe The HAL Sensors are analog ( correct me if iam wrong) because I was told I had to put a 10 k resistor in to stop the fluctuations in voltage as the magnet approaches. But it doesn't matter if it's the sensor plugged in or a bit of wire as soon as either pin has anything in it the sketch starts running and continues to count until that wire is pulled out of the pin

Hope the schematic is right, I used fritzing  as I don't know yet how to do them any other way.
I have put a 9V battery instead of the 12v power supply, it seems to be working ok, so next try it out on vehicle 12v.

Is the 12v supply from a running vehicle? And the USB is from a computer? Is the Arduino in the same location for both tests or is it on your desk with the USB and on the vehicle for the 12v test?
Vehicle power is notoriously noisy - varying voltages, voltage spikes. I have run an Arduino successfully in my car supplied from a 5v USB charger in the cigarette lighter socket. Even with a thermo-sensor on a piece of Cat-5 cable coming out of the hood and through the driver's window (don't ask! :) I had quite steady readings and my display (I2C OLED) was solid. But do expect most external wiring to act like an antenna and pick up some of that noise. You might have to do some data smoothing or averaging to clean it up.
Update:

The eventual finished unit will be mounted in a tractor with the sensors about 4 meters back

See if a car-USB charger fixes the problem on the bench. Does the tractor have a "cigarette lighter socket" power-point as a car does? If not, they are available as a standalone part.
Is it ignition-suppressed to not interfere with a radio, the way a car is? Or does the baler have its own engine (which is most probably not suppressed)? If no suppression, you may need to put the Arduino in a metal box, grounded to the tractor frame, and use a shielded cable between the box and the sensors. And if it's still noisy, possibly even locate the box closer to the sensors - that cable will be like an antenna for noise; you'll need to minimize it.

At the moment a fixed power supply in same location.

The eventual finished unit will be mounted in a tractor with the sensors about 4 meters back on a baler to count the plunger strokes and bale numbers, so as long as the power is filtered iam hoping it all be good (dont know about the cheapy light bar but)

source: Stack Exchange

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

sort: votes


text:
Elapsedtime variable not resetting
I am new to Arduino programming. Let me describe the application I am working on. I am pressing a button for a certain period of time (30 sec). I can not hold it in a pressed position for all the time. I want to avoid accidental transition from button state going from logic HIGH to LOW. I am trying to drive a solenoid valve only at the end of the event.
The algorithm I am using is if once the system detects a HIGH from the sensor it goes in a loop and looks for transition to LOW. It checks if there is continuous LOW for more than 5 sec. If NO then it resets to start checking LOW again. If YES that means end of event and drives the solenoid valve.
The problem I am facing with the code is although the transition to LOW and remaining in LOW is less than 5 sec, the system is sending pulse to drive the solenoid valve. I have incorporated Serial.print() function to observe the value of the sensor input state and elapsed-time. The elapsed-time variable does not reset and keep increasing even though the button state reverts from LOW to HIGH.
I am incorporating part of the code here which is related to the algorithm. I will greatly appreciate if you kindly take a look at the code and the output file and help me detect the bug.
Thanks again!
Niloy.
void loop() {

      buttonstate = digitalRead(button);   // read the state of the microswitch value: HIGH "on" or LOW "off"

      if (buttonstate == HIGH ){
          countstart = 1;

          while(countstart == 1) {
          buttonstate = digitalRead(button);   // read the state of the microswitch value: HIGH "on" or LOW "off"

          if ( ( buttonstate == LOW ) && ( startFlag == 0 ) ) { //start new time sequence
                  startFlag = 1;
                  startTime = millis();
            }
          if ( ( buttonstate == LOW ) && startFlag == 1 ){
                  endTime = millis();
                  elapsedTime = endTime - startTime;
          }

          if ( ( buttonstate == HIGH ) && startFlag == 1 ){
                  startFlag == 0;
                  endTime = startTime =0;
                  elapsedTime = endTime - startTime;
                  countstart = 0;
          }

          Serial.print(buttonstate);
          Serial.print("\n");       // Print tab space
          Serial.print(elapsedTime);
          Serial.print("\n");       // Print tab space

      if ( elapsedTime >= 5000)
      {
          delay(2000);  //2 sec delay
          solenoid->run(FORWARD);
          delay(40);
          solenoid->run(RELEASE);

          delay(500);

          solenoid->run(BACKWARD);
          delay(40);
          solenoid->run(RELEASE);

          countstart = 0;
          endTime = startTime =0;
          elapsedTime = endTime - startTime;
          buttonstate = LOW;
          delay(15000); //wait for 15 sec

      }
     }

    }
}

Why don't you use a debounce library?

@Edgar, Can you please elaborate?

Your problem looks very similar to button bounce, albeit with longer time scales. The are ready made libraries meant to solve this problem reliably.

@Edgar, thank you so much for explaining. I am happy to learn about debounce. Let me take a look at that. Happy holidays!

startFlag variable never goes to zero because there is a bug in this part of code:
 if ( ( buttonstate == HIGH ) && startFlag == 1 ){
          **startFlag = 0;**
          endTime = startTime =0;
          elapsedTime = endTime - startTime;
          countstart = 0;
  }

4 parens on second IF, 3 on third, 3 on fourth.

@leoc7, yes that was the bug which restrained elapsed-time from resetting. I misplaced an extra equal sign. Thanks a lot for pointing it out. The system is working as expected now! Happy holidays a thanks again!

@user141512 you’re welcome!

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


text:
Why is Wire.endTransmission(true) returning 10?
Question:
The follow code is printing 10 over and over again (with spaces in between). I have an I2C device connected at 0x60, and nothing connected at 0x61. I'm confused by this because the Wire.endTransmission(bool) docs say the only valid return types are 0,1,2,3, and 4. These return types are further supported by the Wire.endTransmission(), and the source code of the twi_writeTo function calls.
Code:
```
#include <Wire.h>

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

}

void loop() {
  // put your main code here, to run repeatedly:
  shieldConnected(0x60);
  Serial.println("\n");
  shieldConnected(0x61);

  delay(2000);

}

/**
 * Checks if an I2C device is connected at shieldAddr. This effectively checks if a
 * motor shield exists at that location.
 *
 * Note, this only works when everything's imported for some reason.
 */
void shieldConnected(uint8_t shieldAddr){
  Wire.beginTransmission(shieldAddr);
  Wire.write(1);
  uint8_t end = Wire.endTransmission(true);
  //shieldAddressValidator(shieldAddr);
  Serial.println(end);
}

```

Which arduino board do you use? Is that a working sketch? Are there spaces in between or new lines? Can you print it as a int.

Genuino 101, Yes, yes, and I can change it to printf if that's what you mean?

I'm sorry but I have bad news. The Arduino/Genuino 101 uses a Intel processor and it was a shame. There are different parts (serial, i2c) that never became fully compatible. There might be no solution to your problem or any problem with the 101. Buy a normal board that is compatible with the adafruit motor shield v2.


text:
Multiple I2C slave devices on Arduino - Pull-up values
This question is asked a lot and I've found many usable details on different forums regarding adding pull-up resistors on SDA/SCL lines. I know that only one resistor should be added on these lines regardless of how many devices are attached.
One thing that is not clear for me is that what if I2C devices are powered on from different sources, at different timing?
In following schematic, I have used pull up resistors for both I2C devices. Considering devices might be turned on and off at different timing, or even one device might be absent, is it fine to remove the second pull up resistors (second I2C device) and connect them directly to SDA/SCL pins on uC? In this case (removing pull-up resistors from second device), what happens if device 1 is not available and only second device is connected?
---edit:

Schematic was updated to include only one pair of pull up resistors connected to master side.
I will not how swap or hot plug I2C devices.
I2C devices are sensors (BME280 here, and Chirp capacitive soil moisture, here), not on breakout boards with preset pull up resistors.
Is it possible to just connect resistors on master side and not slave side? In this case, would it be fine for both sensors?

simulate this circuit – Schematic created using CircuitLab

A pullup resistor is between sda (or scl) to vcc. The pullup resistor pulls the signal high. You have resistors in the signal, they should not be there. It is not possible to turn off a i2c device and keep the i2c bus working.

@ Jot, Oops. It was my mistake in wiring. I corrected it. Thanks for mentioning.

It is possible to hot-swap I2C devices with a special circuit (for instance TCA4311A, http://www.ti.com/product/TCA4311A#).

What if both devices are connected and powered on all the time, from different power sources. Do I need resistors on both devices?

You can use a single pair of pullup resistors or many everywhere in your circuit, as long as the combined pullup value is within the specifications for the i2c bus.

Please tell us why you want to control both voltage regulators with the enable pin. Have you read the bme280 datasheet for the minimal power usage? Are you trying to save 100nA? (that is 100 nano amps). When you turn off a i2c device, the i2c bus is no longer working, because most sensors have internal protection diodes to vcc.

@ Jot, you're right. Regarding BME280, I will put it on the same power rail as MCU. But asking in this way was more about my curiosity to know how the two  could be controlled separately.

You should consider adding some bus isolation between each slave and the master. The reason being is that the ESD diodes in the SCL/SDA pins of a slave that is powered down could be interfering with the I2C bus as they leech power from the bus to feed through the internals of the slave.  Given the low current imposed by the pullup resistors being the only power source this shouldn't cause any damage to the slave, but it may well cause the I2C bus to be seen as LOW when it shouldn't, causing communication to fail.
You should add a buffer with an "enable" pin of its own between each slave and the bus.  My device of choice is the PCA9306 from Texas Instruments.  It also means that the slave has its own separate pullup resistors powered by its own 3.3V rail, keeping all the power separate.
You would then have sequences such as:

Power up slave
Give short powerup delay (if needed)
Enable PCA9306
Do I2C transactions
Disable PCA9306
Power off slave

The PCA9306 can also be used to connect 3.3V slaves to a 5V MCU if needed.

simulate this circuit – Schematic created using CircuitLab

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

I would include one resistor on each line at the master, powered by the master. That isn't the only option, just what I consider a cleaner simpler option.
The resistance is needed to provide the high seen on the line. The value of the resistance can vary. There is no one correct value. The pull up resistance needs to provide a high in the required time. There are specifications for this.
https://www.i2c-bus.org/specification/
If the lines do not have a lot of capacitance (wire and device capacitance) then a higher value resistance may be sufficient to meet the timing specification. If there is more capacitance then a lower resistance would be required to provide the stronger pull up in order to meet the timing requirements.
As far as multiple resistances. Yes there can be more than one on the line. But the accumulated resistance must be taken into account.
Many I2C devices mounted on a breakout board have pull up resistors. Typically these are around 5K Ohms. So if there are two devices, each with their own resistors, the combined total will still be within the lowest resistance that would be acceptable.
One thing to note. The specification does not list a lowest resistance that can be used. Instead it specifies the minimum sinking requirement of a device that would need to pull the voltage low enough. So a current is specified, and this current can be used to calculate the minimum resistance on the line.
The current spec (somewhere about 3ma I think, or maybe 2ma??) would calculate to being a 1k6 resistance when used with a 5 volt supply. With a 3.3 volt supply the calculated value would be about 1k1 Ohms. (again, this is a rough calculation, close enough for handgrenades)
This is enough of an answer considering what was asked. There are different modes/speeds and different combinations that can be applied and things can get very involved. And then you must spend the time and look at the specifications. But for most Arduino work this rough guide should cover most "normal" situations.
It really is quite an interesting technology.

For the normal i2c bus (100kHz to 400kHz) every device should at least be able to sink 3mA, but is allowed to sink more. Some manufacturers make devices that barely can do 3mA, so the pullup resistor should keep the current to pull the signal low to 3mA or less.

Thanks. Based on your suggestion, I connected a pair of pull up resistors to main power supply (U3), instead of connecting them to U1 and U2. Is it correct?
One of my confusions was that which side to connect resistors? master or slave? and if slave, then what happens if one of devices are absent.

Yes, connect to the main supply. Whatever supply is going to be there. I consider this to be the supply that the master is on. For 5 volt power I will use 2k2 for the pull ups. For 3.3 volts I use 1K-1K5. I have done many products this way, thousands of products shipped without problem. One product has 14 modules talking over I2C.

I wanted to add this as a comment but I ran out of characters, so this isn't an answer, just more comment.
@Majenko "I would never suggest using I2C over anything other than short PCB traces. i2C + wires = no thank you sir."

And that made me write the following.
We had one product that needed an external radio module. I put a connector in to extend the I2C bus. Total length of the additional cable was about 4 feet. Enough to route it outside the box and mount the radio close by.
Much later I am asked to look at why the communications is failing. The engineering manager had the cable extended to 20 feet. It worked for him on the bench when he tested it. No scope check on waveforms. No calculations. (he was a firmware programmer with just enough hardware knowledge to do his job)
I looked at the waveforms with a scope and I was shocked that it worked at all. The I2C lines were cpu to cpu. The radio had a microcontroller that acted as a slave I2C device.
I put a couple of buffers on either end and all was back in spec and it worked reliably after that, in the field and not just on the bench.
We have a bigger control box that uses I2C to communicate to modules in the back of the box. I have a buffer at the CPU end. The cpu is 3.3v, the modules are 5 volts. The buffer does a level conversion and stronger drive than the cpu could handle. The back of the boxes are shown below. Space for 14 modules. The bigger box is about 2 feet wide and 3 feet tall. The I2C lines run vertically down the center of each of the columns on the back of the board.

There also can be a secondary slave box for an additional 14 modules. The same back board. I used a second I2C port with and isolated I2C buffer for driving the lines. The slave boax was to be mounted beside the main box. Again I specified a short cable, this time six feet in length.
So one day I am asked if the cable can be extended. The contractor installing the panels wanted to put the slave boax on the other side of the hall by another electrical panel. I ask how long do they need. I'm told it is ten feet away. Yeah, ten feet line of sight. Once the cable was touted up into the ceiling, across the hall, and then down to the other box, the 10 feet turned into 30 feet.
I did a check with a scope. The rise times were still in spec, it seemed to work, so we made up a cable and told them that it may or may not work. Use at their own risk. I told them this was an exception and it is not to be a part of the product offering. But I'm sure there will be more exceptions.
And while it can work over those kind of distances the following shows how I2C can fail over short distances.
Same equipment. The smaller box in the picture was expanded with an additional larger box. The smaller box was mounted eight inches above the bigger box. (display and main cpu in the front panel of the product) Only temperature input into the modules in the smaller box. The bigger box was loaded with modules with control relays. Four 17 amp relays per module.  Same electronics as in the exception described above. But they were having lots of sporadic behaviour. Pictures of the wiring, the installation, looked clean and well done. I had no idea why it was failing.
After this had been going on for a couple of months I asked our customer service person to ask what they have connected to our relays. Normally it would be motor up to 1 hp. They were controlling bigger motors and they had our relays turning on power contactors in a different panel. Lots of power contactors. All generating voltage spikes when they were turned off. I had them put snubbers across the contactor coils and the problems went away.
So I2C can work over longer distances, and it can fail over shorter distances. The whole picture needs to be taken into account. The problem is the whole picture often is hard to see.


text:
Adafruit Feather M0 Basic update bootloader
I bought a Feather M0 Basic from a reseller Lawicel however I'm missing the
UF2 boot feature. When I press the reset button two times I just
get a serial and have to program circuitpython using Bossa. The UF2
FEATHERBOOT usb storage drive as described  here doesnt show up.
I have a ARM-ICE and wired up the Feather board via SWD. I
can re-program the bootloader (first setting fuse to NVMCTRL_BOOTPROT 0x7
as described here ) via ARM-ICE.
However it seems that the Arduino bootloader featherm0bootloader_160305.zip is an old one that doesnt support the UF2 usb storage device programming protocol.
Where can I download a more recent bootloader that supports UF2 ?

this? https://learn.adafruit.com/installing-circuitpython-on-samd21-boards/installing-the-uf2-bootloader

post a link of the actual product, not the homepage of the retailer

@Juraj : Thanks, that was the one I was looking for. Programmed it and now FEATHERBOOT is appearing.


text:
String and heap confusion
I hope you all well.
Recently after view unknown crashes I decided it can be related with me messing with "heap"
After reading few sources on heaps and how it works it kind of confusing. Some sources mention that you can F() everything and it will be fine and others mention reserving space for strings with "reserve()"
I am looking for suggestions how possibly eliminate or or control?
I will post snapshot of code below where the evil "String" is used few times.
////////sending data
    senddata(String(temp), String(hum), String(dis), String(flood), String(heaterstatus), String(humidifierstatus));
    //////////sending data

void senddata(String temp1, String hum1, String dis1, String flood1, String heater1, String humid1) {   /////sending all field values in one go
  //////////sending data
  String getData = "GET /update?api_key=" + API + "&field1=" + temp1 + "&field2=" + hum1 + "&field3=" + dis1 + "&field4=" + flood1 + "&field5=" + heater1 + "&field6=" + humid1;
  sendCommand("AT+CIPMUX=1", 5, "OK");
  sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
  sendCommand("AT+CIPSEND=0," + String(getData.length() + 4), 4, ">");
  esp8266.println(getData); delay(1500); countTrueCommand++;
  sendCommand("AT+CIPCLOSE=0", 5, "OK");
}

Yes, you could make a global String for getData and reserve space and reuse it every time the function is called. But what with String(getData.length())?
And the parameters? You create a new String for every parameter. And the function senddata doesn't take a reference to the String (String&), but it makes a new copy of each String parameter. So you create 12 small Strings with every call to this function. This is the evil of String. It does everything no matter at what cost.
And your sendCommand takes String too. That is why you can do "AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT and "AT+CIPSEND=0," + String(getData.length() + 4) as parameter to it. So every call to sendCommand creates two small Strings. That is 8. And every + on String can trigger a reallocation on heap.
Use C strings
void senddata(int temp1, int hum1, int dis1, int flood1, int heater1, int humid1) {
  char getData[256];
  snprintf(getData, sizeof(getData), "GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d",
      API, temp1, hum1, dis1, flood1, heater1, humid1);
  sendCommand("AT+CIPMUX=1", 5, "OK");
  char buff[32];
  snprintf(buff, sizeof(buff), "AT+CIPSTART=0,\"TCP\",\"%s\",%d" , HOST, PORT);
  sendCommand(buff, 15, "OK");
  snprintf(buff, sizeof(buff), "AT+CIPSEND=0,%d" , strlen(getData) + 4);
  sendCommand(buff, 4, ">");
}

void sendCommand(const char* command, const int timeout, const char* find) {

F macro optimizes memory use, by using data stored in flash memory. The snprintf_P function is a version of snprintf for format string from flash.
snprintf_P(getData, sizeof(getData), (const char*) F("GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d"),
  API, temp1, hum1, dis1, flood1, heater1, humid1);

One of the classes of my StreamLib is CStringBuilder. With it the code could be:
char getData[256];
CStringBuilder sb(getData, sizeof(getData));
sb.printf(F("GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d"),
    API, temp1, hum1, dis1, flood1, heater1, humid1);
sendCommand("AT+CIPMUX=1", 5, "OK");
char buff[32];
CStringBuilder sb2(buff, sizeof(buff));
sb2.printf(F("AT+CIPSTART=0,\"TCP\",\"%s\",%d") , HOST, PORT);
sendCommand(buff, 15, "OK");
sb2.reset();
sb2.print(F("AT+CIPSEND=0,"));
sb2.print(sb.length() + 4);
sendCommand(buff, 4, ">");

Hello @Juraj and thanks for getting involved. The snprintf function seems to be very interesting and suitable. I had a good look for a good guide on the function, however, limited answers. What i would like to find out is what does it mean when you use %d and %s or how they are diffent?

printf is 50 years old. http://www.cplusplus.com/reference/cstdio/printf/

Thanks for that, its a great reference. Do you know if there are any limitations to where i can use it? It seems to be that any floats cant be used? Is there any common functions that may conflict?

using printf versions takes a little more of flash memory. float support can be enabled, but it takes even more program memory. Alternative is to use my CStringBuilder class, which builds a C string using the same simple functions like Serial


text:
What could cause data to be printed correctly, then incorrectly and then repeated? CAN bus / general transmission
I am attempting to send data from an MPU6050 connected to an arduino uno to another uno via CAN bus, however i don't think this is a CAN bus specific issue.
In short, i am sending two packets of 8 bytes in the following formats
Packet 1 - (uint32_t/ int16_t/ int16_t)
Packet 2 - (int16_t/ int16_t/ int16_t/ int16_t)

all converted into bytes in this sort of fashion;
int16_t byte2Int(int16_t output, int pos, uint8_t data[2]){
      for (int i = 0; i < 2; i++)
    {
      output += ((int16_t)data[i + pos]) << (i * 8);
    }
    return output;
}

where everything should make sense apart from the "int pos" part which is just where in the buffer i want to start putting the data as packet 1 and 2 are different structures.
My issue is that with just one packet, i can print the values just fine, with the second packet added in i get the following on the serial monitor;
AccX    AccY    AccZ  GyX    GyY     GyZ

16832   -816    928 -440    16832   -816
16984   -940    992 -449    16984   -940
16896   -804    988 -462    16896   -804
209 55  0   0   209 55
16900   -852    1080    -471    16900   -852
16900   -852    1080    -471    16900   -852
16984   -760    948 -481    16984   -760
16880   -824    896 -459    16880   -824
230 102 0   0   230 102
16928   -860    996 -422    16928   -860
16928   -860    996 -422    16928   -860
17004   -856    864 -466    17004   -856
17004   -856    864 -466    17004   -856
214 105 0   0   214 105
16964   -828    944 -446    16964   -828
16964   -828    944 -446    16964   -828

As you can see i get some coherent messages, then some scrambled which don't make sense, then coherent again and the cycle continues. Not sure of relevance, but when i first start the serial monitor this doesn't happen, then after varying time, but around 5 seconds or so, it starts going amiss.
I believe this is down to my programming, and me not being able to code in a reliable way to wait for the first message to complete, then send the next one and them being read correctly. Below is my embarrassing attempt at sending an ACK message to the sender to say that the message has been received and to progress to the next message. I am not a programmer by nature and i am putting up this shoddy code that i've spent days trying to sort in the hope someone can point me in the right direction.
Apologies in advance.
// CAN Send Example
//

#include <mcp_can.h>
#include <SPI.h>
#include <Wire.h>

const int MPU_addr = 0x68; // I2C address of the MPU-6050
uint32_t TimeMicro;
int16_t AccX, AccY, AccZ, Tmp, GyX, GyY, GyZ;
int8_t data1[8], data2[8], rxBuf[8];
int Switch = 7;
long unsigned int rxId;
unsigned char len = 0;

#define CAN0_INT 2                              // Set INT to pin 2
MCP_CAN CAN0(10);     // Set CS to pin 10

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

  // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
  if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK) Serial.println("MCP2515 Initialized Successfully!");
  else Serial.println("Error Initializing MCP2515...");

  CAN0.setMode(MCP_NORMAL);   // Change to normal mode to allow messages to be transmitted

  pinMode(Switch, OUTPUT);
  digitalWrite(Switch, HIGH);

  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);

}

void loop()
{

  TimeMicro = millis();

  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
  AccX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AccY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AccZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp = Wire.read() << 8 | Wire.read();
  GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

  double2Byte(TimeMicro, 0, data1);
  int2Byte(AccX, 4, data1);
  int2Byte(AccY, 6, data1);

  int2Byte(AccZ, 0, data2);
  int2Byte(GyX, 2, data2);
  int2Byte(GyY, 4, data2);
  int2Byte(GyZ, 6, data2);

  // send data:  ID = 0x100, Standard CAN Frame, Data length = 8 bytes, 'data' = array of data bytes to send
  byte sndStat = CAN0.sendMsgBuf(0x100, 0, 8, data1);

  if(!digitalRead(CAN0_INT))                         // If CAN0_INT pin is low, read receive buffer
  {
    CAN0.readMsgBuf(&rxId, &len, rxBuf);      // Read data: len = data length, buf = data byte(s)

    while(rxBuf[0] != 0x0A)
    {
      continue;
    }

  }
  delay(10);
  byte sndStat2 = CAN0.sendMsgBuf(0x100, 0, 8, data2);

    while(rxBuf[0] != 0x0A)
    {
      continue;
    }

  for(int i = 0; i < 8; i++)
  {
    data1[i] = 0;
    data2[i] = 0;
  }

}

//===================================================================================
//                                  FUNCTIONS
//===================================================================================
uint8_t int2Byte(int16_t input, int pos, uint8_t data[2]){
  for (int i = 0; i < 2; i++)
  {
    data[i+ pos] = ((input >> (i * 8)) & 0xff);
  }
return data[2];
}

uint8_t double2Byte(uint32_t input, int pos, uint8_t data[4]){
  for (int i = 0; i < 4; i++)
  {
    data[i+ pos] = ((input >> (i * 8)) & 0xff);
  }
return data[4];
}

/*********************************************************************************************************
  END FILE
*********************************************************************************************************/

Receiver
// CAN Receive Example
//

#include <mcp_can.h>
#include <SPI.h>

long unsigned int rxId;
unsigned char len = 0;
unsigned char rxBuf1[8];
unsigned char rxBuf2[8];
unsigned char txBuf[8];
char msgString[128];                        // Array to store serial string
uint32_t TimeMicro;
int16_t AccX, AccY, AccZ, GyX, GyY, GyZ;

#define CAN0_INT 2                              // Set INT to pin 2
MCP_CAN CAN0(10);                               // Set CS to pin 10

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

  // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
  if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK)
    Serial.println("MCP2515 Initialized Successfully!");
  else
    Serial.println("Error Initializing MCP2515...");

  CAN0.setMode(MCP_NORMAL);                     // Set operation mode to normal so the MCP2515 sends acks to received data.

  pinMode(CAN0_INT, INPUT);                            // Configuring pin for /INT input

  Serial.println("MCP2515 Library Receive Example...");
}

void loop()
{
  if(!digitalRead(CAN0_INT))                         // If CAN0_INT pin is low, read receive buffer
  {
    CAN0.readMsgBuf(&rxId, &len, rxBuf1);      // Read data: len = data length, buf = data byte(s)
  }

  for(int i; i < 8; i++){
    txBuf[i] = 0x0A;
  }

  byte sndStat = CAN0.sendMsgBuf(0x101, 0, 8, txBuf);

  if(!digitalRead(CAN0_INT))                         // If CAN0_INT pin is low, read receive buffer
  {
  CAN0.readMsgBuf(&rxId, &len, rxBuf1);      // Read data: len = data length, buf = data byte(s)
  }

  byte sndStat2 = CAN0.sendMsgBuf(0x101, 0, 8, txBuf);

  TimeMicro = byte2Double(TimeMicro, 0, rxBuf1);
  AccX = byte2Int(AccX, 4, rxBuf1);
  AccY = byte2Int(AccY, 6, rxBuf1);
  AccZ = byte2Int(AccZ, 0, rxBuf2);
  GyX = byte2Int(GyX, 2, rxBuf2);
  GyY = byte2Int(GyY, 4, rxBuf2);
  GyZ = byte2Int(GyZ, 6, rxBuf2);

  Serial.print(TimeMicro);
  Serial.print("\t");
  Serial.print(AccX);
  Serial.print("\t");
  Serial.print(AccY);
  Serial.print("\t");
  Serial.print(AccZ);
  Serial.print("\t");
  Serial.print(GyX);
  Serial.print("\t");
  Serial.print(GyY);
  Serial.print("\t");
  Serial.println(GyZ);

  TimeMicro = 0;
  AccX = 0;
  AccY = 0;
  AccZ = 0;
  GyX = 0;
  GyY = 0;
  GyZ = 0;

}

//===================================================================================
//                                  FUNCTIONS
//===================================================================================

uint32_t byte2Double(uint32_t output, int pos, uint8_t data[4]){
      for (int i = 0; i < 4; i++)
    {
      output += ((uint32_t)rxBuf1[i + pos]) << (i * 8);
    }
    return output;
}

int16_t byte2Int(int16_t output, int pos, uint8_t data[2]){
      for (int i = 0; i < 2; i++)
    {
      output += ((int16_t)rxBuf1[i + pos]) << (i * 8);
    }
    return output;
}
/*********************************************************************************************************
  END FILE
*********************************************************************************************************/

I've tried debugging this by the following;

check that the MPU is sending correctly (Fine)
check if it happens with just one packet (no problems)
check if the packets are assembled correctly on the sender ( got the data,
broke it into bytes and reassembled and printed that result. did what i
expected)
removed time from being sent incase that was causing an issue (same problem
as illustrated above)
removed all serial prints and just did one value (still an issue)

So i believe that it is down to a terrible and non working attempt at sending an acknowledgment message. I have tried researching but i couldn't find an example for CAN bus, and all the others were using protocol specific interrupt routines which i tried to implement but didn't work. obviously.
Thankyou for your patience

Did you check that you have always enough available RAM? I had some crazy, seemingly random issues, and it was connected with running out of RAM from time to time.

send fixed bytes for both packets .... we have no way of knowing if the data is actually corrupted by the transmission ..... gyro could be producing corrupted  values

DISCLAIMER: Ok, I never worked with CAN on arduino, so I may be terribly wrong, nor I have the required boards to test this, so I may make a lot of errors; if you find any issue, please point them out, so I can fix them (or if you fixed them notify me, so I can update the reply for the future readers).
Ok, from what I can read you are have two packets, but only one CAN frame. This seems to me a huge inefficiency, because how can you know which frame have you just received?
To fix this, you can either use two frames or use something in the payload that informs you which frame you have received. In my opinion, since there are a lot of free IDs, you can use the first approach.
Moreover you are performing some checks in the processing (e.g. "did I receive an ack?"),  but if this fails you go on without further checking. For instance, when in the sender you write:
byte sndStat = CAN0.sendMsgBuf(0x100, 0, 8, data1);
if(!digitalRead(CAN0_INT))
{
  ...
}
delay(10);
byte sndStat2 = CAN0.sendMsgBuf(0x100, 0, 8, data2);

what happens when CAN0_INT is still high? Yes, it sends the data immediately.
I could not understand the while(rxBuf[0] != 0x0A) part; it will block your program forever...
Finally when you receive a message you never check the ID; this means you will check all the messages on CAN, and when you add another device on the net you will not be able to send any other message.
Ok, so this is what I'd try for your needs:

The TX board will always transmit data, while the RX board will always receive it. No ack frames is needed
There will be two frames on the network: frame 0x100 will have packet 1, while frame 0x101 will have packet 2
The TX board will send one message every 100ms; this can be reduced, but specify a time rather than having the part send frames "continuously"
The RX board will consider the data valid only after a 0x101 packet is received and a 0x100 packet was received before.

So, here is the code. Please note that I refactored some parts for easier understanding (putting some code in functions to have a smaller "higher level" setup and loop functions.
BTW what is the "Switch" in the sender? It is never used...
Sender:
// CAN Send Example
//

#include <mcp_can.h>
#include <SPI.h>
#include <Wire.h>

const int MPU_addr = 0x68; // I2C address of the MPU-6050

uint32_t lastTimeSent;
uint32_t currMillis;
const uint32_t intervalSendMs = 100; // Send period in milliseconds

int16_t AccX, AccY, AccZ, Tmp, GyX, GyY, GyZ;
uint8_t data1[8], data2[8];
int Switch = 7;

#define CAN0_INT 2    // Set INT to pin 2
MCP_CAN CAN0(10);     // Set CS to pin 10

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

    initializeMCP2515();

    pinMode(Switch, OUTPUT);
    digitalWrite(Switch, HIGH);

    initializeMPU6050();
}

void loop()
{
    currMillis = millis();

    if ((currMillis - lastTimeSent) >= intervalSendMs)
    {
        lastTimeSent += intervalSendMs;

        readFromMPU6050();

        convertDataToPackets();

        // Send the two frames; if the first sending is successful send also the second, otherwise abort
        // send data frame 1:  ID = 0x100, Standard CAN Frame, Data length = 8 bytes, 'data' = array of data bytes to send
        // send data frame 2:  ID = 0x101, Standard CAN Frame, Data length = 8 bytes, 'data' = array of data bytes to send
        if (CAN0.sendMsgBuf(0x100, 0, 8, data1) == CAN_OK)
            CAN0.sendMsgBuf(0x101, 0, 8, data2);
    }
}

//===================================================================================
//                                  FUNCTIONS
//===================================================================================
void initializeMCP2515()
{
    // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
    if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK)
        Serial.println("MCP2515 Initialized Successfully!");
    else
        Serial.println("Error Initializing MCP2515...");

    CAN0.setMode(MCP_NORMAL);   // Change to normal mode to allow messages to be transmitted
}

void initializeMPU6050()
{
    Wire.begin();
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
}

void readFromMPU6050()
{
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
    AccX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AccY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AccZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp = Wire.read() << 8 | Wire.read();
    GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
}

void convertDataToPackets()
{
    long2Byte(currMillis, 0, data1);
    int2Byte(AccX, 4, data1);
    int2Byte(AccY, 6, data1);

    int2Byte(AccZ, 0, data2);
    int2Byte(GyX, 2, data2);
    int2Byte(GyY, 4, data2);
    int2Byte(GyZ, 6, data2);
}

void int2Byte(int16_t input, int pos, uint8_t *data)
{
    for (int i = 0; i < 2; i++)
    {
        data[i + pos] = ((input >> (i * 8)) & 0xff);
    }
}

void long2Byte(uint32_t input, int pos, uint8_t *data)
{
    for (int i = 0; i < 4; i++)
    {
        data[i + pos] = ((input >> (i * 8)) & 0xff);
    }
}

/*********************************************************************************************************
  END FILE
*********************************************************************************************************/

Receiver:
// CAN Receive Example
//

#include <mcp_can.h>
#include <SPI.h>

long unsigned int rxId;
unsigned char len = 0;
unsigned char rxBuf[8];
uint8_t receivedFirstFrame;

char msgString[128];                        // Array to store serial string
uint32_t TimeMicro;
int16_t AccX, AccY, AccZ, GyX, GyY, GyZ;

#define CAN0_INT 2  // Set INT to pin 2
MCP_CAN CAN0(10);   // Set CS to pin 10

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

    initializeMCP2515();

    Serial.println("MCP2515 Library Receive Example...");
    receivedFirstFrame = 0;
}

void loop()
{
    if(!digitalRead(CAN0_INT))
    {
        // Received a message
        if (CAN0.readMsgBuf(&rxId, &len, rxBuf) == CAN_OK)
        {
            // Note: the above line is not like in the examples, but looking at the code the
            // function may return if no message was in the queue, so I think this is safer

            // Let's check if it is one of the known messages
            switch (rxId)
            {
            case 0x100:
                { // Received first frame
                    // Decode the content and store that the first frame was received
                    decodeFirstFrame(rxBuf);
                    receivedFirstFrame = 1;
                }
                break;
            case 0x101:
                if (receivedFirstFrame)
                { // Received second frame after a first frame
                    // Decode the content
                    decodeSecondFrame(rxBuf);

                    printDataToSerial();

                    receivedFirstFrame = 0;
                }
                break;
            }
        }
    }
}

//===================================================================================
//                                  FUNCTIONS
//===================================================================================

void initializeMCP2515()
{
    // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
    if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK)
        Serial.println("MCP2515 Initialized Successfully!");
    else
        Serial.println("Error Initializing MCP2515...");

    CAN0.setMode(MCP_NORMAL); // Change to normal mode to allow messages to be transmitted

    pinMode(CAN0_INT, INPUT); // Configuring pin for /INT input
}

void decodeFirstFrame(uint8_t *buffer)
{
    TimeMicro = byte2Double(0, buffer);
    AccX = byte2Int(4, buffer);
    AccY = byte2Int(6, buffer);
}

void decodeSecondFrame(uint8_t *buffer)
{
    AccZ = byte2Int(0, buffer);
    GyX = byte2Int(2, buffer);
    GyY = byte2Int(4, buffer);
    GyZ = byte2Int(6, buffer);
}

void printDataToSerial()
{
    Serial.print(TimeMicro);
    Serial.print("\t");
    Serial.print(AccX);
    Serial.print("\t");
    Serial.print(AccY);
    Serial.print("\t");
    Serial.print(AccZ);
    Serial.print("\t");
    Serial.print(GyX);
    Serial.print("\t");
    Serial.print(GyY);
    Serial.print("\t");
    Serial.println(GyZ);
}

uint32_t byte2Double(int pos, uint8_t *data)
{
    uint32_t output = 0;
    for (int i = 0; i < 4; i++)
    {
      output += ((uint32_t)data[i + pos]) << (i * 8);
    }
    return output;
}

int16_t byte2Int(int pos, uint8_t *data)
{
    int16_t output = 0;
    for (int i = 0; i < 2; i++)
    {
      output += ((int16_t)data[i + pos]) << (i * 8);
    }
    return output;
}
/*********************************************************************************************************
  END FILE
*********************************************************************************************************/

Please let me know if you have any comments or find some issues with this.

Code works perfectly after a few compiling issues. Only interesting one is that I had to serial. Print the data directly after the "CAN0. readMsgBuf" function. Could it be because the data is being overwritten in rxBuf after the "decodeSecondFrame"? I've now got the file to work though. Thankyou for taking the time to help teach me. And what should I do with the code that works? Put it at the bottom of the question?

@RossHanna If you tell me the compiling issues I can fix the code so that future readers don't have to figure out what is wrong ;) About the issue you are having, it's my fault. I should have learned not to call variables in similar way. Please correct the code with the two decode functions I edited above, and put back the print in the position it was before (after the readMsgBuf is wrong, since it does not print valid data but also partial). As for the code, it is enough to accept this answer like you did

1 - changed data 1 to variable type to uint8_t. 2 - define currentMillis in "convertDataToPackets". 3 - remove data array size "[2][i + pos]". 4 - set all variables to zero at end of main loop or they just increment. then move serial prints to after decode functions.

For the sake of fixing the code: the functions byte2Double and byte2Int in the receiver sketch still contain the original code with the error as mentioned in my answer.

@RossHanna I should have fixed the code for issues 1, 2 and (if I understood correctly) 3. The point 3 was related to data[4] and data[2] in the byte2Double and byte2Int functions? Point 4 is also solved, but not in the way you think (the old functions were wrong; I fixed them in the "correct" - IMHO - way)

@oh.dae.su Thank you, I missed that point (fixed it in the sender, not in the receiver); I integrated this in the code in the answer

There are indeed a few coding issues in your sketch, especially in the receiver part. I will try to list them and suggest changes.

If you look closely to your received data, you will see that AccX==GyY and AccY==GyZ on every line of your output. This is because you use the global variable rxBuf1 in your byte2Int and byte2Double functions on the receiver side. This causes the output to consume rxBuf1 also for the second CAN frame. Instead you should use the pointer to data that you have prepared in the inputs for this purpose.
In the receiver sketch, for both times you read in the CAN message with  CAN0.readMsgBuf you write the result to rxBuf1, although for the second read you most likely intended to write to rxBuf2. Now you simply overwrite rxBuf1 and therefore the content of the first received CAN message in the loop is never evaluated.
The switched outputs every few lines, in my opinion, are most likely due to a mixed order of both messages on the receiver side, when you receive CAN message 2 before CAN message 1. In order to avoid this, please follow the nice suggestions by @frarugi87 to send both messages with separate CAN IDs and to check for receiption of both before printing them.
I also agree that you can get rid of the acknowledge reply from the receiver. The can protocol already contains an acknowledge mechanism on the CAN transceiver that will notify the sender that at least one listening node has correctly received the message. If the sender does not get this acknowledge indication, it will repeat to send the message for some time.

I used frarugi87's code changes and it works great. My only remaining question. Using two separate ID's for each packet? is that how it would be done in a real system? i was attempting to get all the data in one transmission as i thought that is the way it would be done in a real system?

Typically, one CAN-ID is used for a fixed payload of up to 8 byte. So normally when you retransmit a CAN-ID it contains the same variables (however with updated values). When you have more than 8 byte of information that you want to transmit regularly, you either split it up into several CAN-IDs or you use a transport protocol such as SAE J1939 on top of the regular CAN-protocol in the data-link layer.


text:
Bad Communication with Multiple I2C Devices
I have an Arduino Micro connected to two I2C devices. An MPU-6050 that is powered by 5V (though it has its own voltage regulator on it) and a Altimeter that is powered by 3.3V. They are both connected to the SDA and SCL.
I noticed that when I have the MPU powered on but don't power the 3.3V altimeter, the MPU does not communicate with the Arduino. I need to have the 3.3V power on to just communicate with the MPU through I2C. Why does this happen?
Then unfortunately, I believe I may have shorted the 3.3V rail and broke the altimeter. When I remove the MPU from the equation and try to just communicate with the Altimeter, I get nothing. Does this mean that I did short the device, or is there something else going on with I2C that I don't understand?
I have attached a schematic below of how the devices are connected.

so ... you connect the scl/sda on the "pressure sensor" to the MPU6050 using 1k resistors? why? and how are these two components connected to the arduino? as a schematic, that leaves a lot of unanswered questions

They are connected to the Arduino Micros SCL and SDA pins. I did have both devices working before I shorted the device. I would like to know why when one device is bad (or not powered) on I2C, it screws up the other devices.

because they're connected

Do all devices use 3.3 V or all 5V for I2C communication? You will get problems when connecting a 3.3V device to a 5V bus or vice versa. At that point you would need a level shifter.

I would like to know why when one device is bad (or not powered) on
  I2C, it screws up the other devices.

The I2C lines need to have a pull up resistor to provide the high. The master device, and the slave devices, ground the line to provide a low, but they release the line, and not drive it at all, in order to provide the high.

Consider switches a and b to be inside the I2C device. When the switch a is open point A will be at 5 volts. When switch a is closed, point A will be at 0 volts.
Now if you had a second set of R resistors on the same line, but powered from their own 5 volt power supply, the same voltages will be seen at A when switch a is open (5 volts) and switch a is closed (0 volts).
But now if we kill the supply feeding the second set of R resistors (sorry that I can't show them in a picture) instead of pulling up to 5 volts (because we killed the 5 volts) the resistors will be pulling down due to whatever other loads there are on the killed 5 volt supply. And just for argument sake, let's say the killed 5 volt supply was at 0 volts.
So if one set of resistors is pulling up to 5 volts (the still powered pair) and one pulling down (the killed pair) then the voltage at points A and B will not be as high as the 5 volts we would see when the switches are open.  If all the resistors R were the same value, and the killed supply was at 0 volts, then the highest voltage at A or B would be 2.5 volts. And that is not a good high.
So the additional device, that is not being powered, has disrupted the communitations, preventing true highs. Lows are not affected as the switch will pull the line low.
I don't know the values of all your pull up resistors, and don't know how low the dead supply goes, so I can't say what the new lower highest voltage is. But it seems that it is low enough to make the communications stop working.
And the resistor are not the only thing that can be disgusting the high. The unpowered chip can be providing unexpected current paths. Most port pins have an internal diode to Vcc. And since the chip has no power on Vcc the current on the I2C lines can follow that path to ground.
Also, I think you have drawn the resistors wrong. If they were in series with the SDA and the SCL pins there would be no communications because the 1k resistors doesn't allow the SDA line to be pulled low enough. I think those resistors are pull up resistors. Maybe you can take another look and confirm the connection.

Thanks for the reply!! So the pull up resistors for the I2C line are on the breakout board for the MPU. They are 4.7kohm resistors and are pulled high to 3.3V.

When a device is unpowered any voltage placed on an IO pin is leeched off and fed to the VCC pin through the internal ESD protection diodes.  On a bus like I2C this then cripples the bus. (Note: even if there are no intentional protection diodes the MOSFETs that drive the lines have diodes built into them and these act as protection diodes, but they are very weak and can be easily broken).
You cannot have an unpowered device on an I2C bus and doing so risks damaging the unpowered device (although the limited current provided by the pullup resistors should mitigate this).
If you want to have an unpowered device on the bus you must isolate it from the bus.  I use the PCA9306 as in this answer, but other devices are available.
Did you kill the device by shorting it out? Possibly. It depends what you shorted to where. 3.3V directly onto the SDA or SCL pin while the device is unpowered may well have killed that pin.


text:
Global or local
I'm new to Arduino and embedded, but understand that it is often better to use global instead of local variables (such as here or here).
I have this simple code (from here):
//Libraries
#include <DHT.h>;

//Constants
#define DHTPIN 2     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino

//Variables
float hum;  //Stores humidity value
float temp; //Stores temperature value

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

}

void loop()
{
    //Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Humidity: ");
    Serial.print(hum);
    Serial.print(" %, Temp: ");
    Serial.print(temp);
    Serial.println(" Celsius");
    delay(2000); //Delay 2 sec.
}

My ancient C programmer training (Unix servers) says I must move variables hum and temp to loop(), or is it better on Arduino to leave them as globals?

This depends on how you define "better". For instance, when is "global" necessary? When can a "local" work just as well?

Since the AVR CPU is a register-rich system, putting the variables in loop may well cause the compiler to go "Oh, I have enough registers to store this information. I don't need these variables in memory since they get thrown away straight after using them. I'll delete them and just use internal registers instead.".  Optimizations are great :)

If you are an ancient C programmer, then try functions with parameters "by reference". The compiler can do more optimizations with that. Passing a global variable by reference is almost the same for the compiler as using the global variable in the function, but with the parameter by reference it still does look good because the used variables are nicely declared as parameters. By the way, the dht22 is not accurate, try something better.

@Jot - it's cheap! And my project is not critical. Or is there something better in the same price bracket?

The humidity that the dht22 returns is not accurate, it is only an indication and can be used to check if the humidity goes up or down. When it measures 60%, the relative humidity can be between 40% and 80%. The good sensors with i2c are still 2% or 3% inaccurate. Those sensors are for example the bme280, bme680, htu21d, sht31-d, si7021. Those sensors are 3.3v and the arduino uno is 5. You might need level shifters for the i2c bus. For just the temperature, the ds18b20 is the best choice, good and cheap.

When you look at the hardware itself, there are no memory protections at all.  (at least at the low end - modern desktop machines might have some)  This means that at the hardware level, everything is global no matter how or where you declared it.  That said though, it's still useful to use the scope idea to keep from running over yourself (or your teammate(s)), and to give the compiler an opportunity to optimize, but that's really all it is.

No. If you have the choice, locals are usually better, because they
minimize the risk of name collision, and they help make the program
clearer by keeping the variable definition close to the place where it
is used. In your example, hum and temp should be locals, as there is
no good reason to make them globals.
However, sometimes you don't have the choice. If a variable is used in
both setup() and loop(), then it needs to be global. This is the
case of dht in your example.
Sometimes a variable is used in many functions. Even if you can make it
local, by passing it around through function parameters, doing so
doesn't make the program more readable. In that case you may also prefer
to keep it global.
Sometimes a variable that is used in only one function needs to be
statically allocated in order to preserve its value across calls to the
function. In this case the variable could be a static local. However,
since the static keyword is somewhat obscure for beginner programmers,
Arduino tutorials tend to use globals whenever static storage is needed.
You are not required to follow this practice, although you may want to
if you are writing for an audience of novices.
In any case, the take away of your first two links is not that you
should prefer globals: it's that sometimes there is a good reason for
making a variable global, and that's fine.

Thanks for all your answers, I've changed the code, and it's good to know I don't need to change my practices too much :) (Global variables were banned in all the development environments I worked in in the 1990s) So am I right to conclude that I only NEED to use a global if I refer to it in setup() and loop()? Everything else can be local and passed around?

@minisaurus: Yes, that's right. However, now that he ban is lifted, I suggest you try to avoid thinking of globals as evil. If you find yourself passing a variable around through many functions, consider making it global: does that hurt the program's readability? If the answer is “no”, then a global is probably a good choice.

I'm out of touch, but is the ban really lifted in professional environments with several developers, APIs, libraries and who knows how many files of source code? But I can see how globals maybe aren't a big problem in these single file small Arduino projects.

@minisaurus: I don't know on these environments. My answer is specifically for the kind of programs you write on smallish embedded devices.

The general rule of good practice is to minimize the scope of a variable to necessary minimum. Write the code to be readable and maintainable, don't do premature optimization.
The variables hum and temp should be defined only in loop(). The compiler can optimize it by putting them to global space or using MCU registers only, to avoid repeated creation on stack.

Not an answer, but I thought some of you may be interested in the C coding standards of some projects in the 1990s (based on the EDS standards, if I remember correctly).
A summary of the rules is:

No goto
No global variables
All functions (including main) to return an integer which is either SUCCESS or FAILURE
All variables declared at start of function
All variables declared on a separate line
No "in-line" initialising of variables
All variables initialised, usually to zero, including mallocs
No in-line if's
Probably more things that I can't remember

An example program:
#include <stdio.h>
#include <stdlib.h>

#define SUCCESS 0
#define FAILURE !SUCCESS

int log_error(char *msg) {
  int rv;

  rv = SUCCESS;

  fprintf(stderr, "%s\n", msg);

  return(rv);
}

int function2(void) {
  int rv;

  rv = SUCCESS;

  return(rv);
}

int function1(void) {
  int rv;
  int i;
  char *mem;

  rv = FAILURE;
  i = 0;
  mem = 0;

  if(NULL == (mem = malloc(400))) {
    log_error("Malloc error");
  } else {
    for(i=0; i<400; i++) {
      mem[i] = 0;
    }
    if(SUCCESS != (rv = function2())) {
      log_error("function2");
    } else {
      rv = SUCCESS;
      free(mem);
    }
  }
  return(rv);
}

int main(int argc, char **argv) {
  int rv;

  rv = FAILURE;

  if(SUCCESS != (rv = function1())) {
    log_error("function1 error");
  }

  return(rv);
}

Bit different to the way K&R wrote UNIX, and perhaps not too relevant to embedded? I'm not sure which I prefer, I guess both styles have their place depending on the makeup of a team :)

You very wisely pointed out that not all of these rules are universal. Just to provide an illustration, the Linux kernel coding style contradicts several of the above, including the bans on gotos (sec. 7) and global variables (sec. 4), having to always return a status code (sec. 16), and variable initialization within the declaration (example on sec. 7).


text:
How can we use two devices at the same time with arduino?
I am using fingerprint module r307 and LCD together. In that, I am using 2,3 digital pins of arduino for data transfer to the fingerprint.(I tried other pin configurations for this but it didn't work) But as I am connecting LCD, it also requires same 2,3 digital pins of arduino and it is not possible for me to use 2 and 3 pins of Arduino for both lcd and fingerprint sensor for data transfer. Can you please suggest an alternative to this. Can we use analog pins of arduino as digital ones and if so the how?? PLEASE HELP... Thank you!!

Please add which libraries you are using. You could also add your sketch so far.

When you instantiate an instance of the LCD code, likely you will have a choice of pins to use.  But even with this flexibility (if the library programmer was thoughtful enough & was able to include it), the limits of the particular Arduino and processor you have chosen may make the project difficult or impossible.  As @MikaelPatel has asked, let us know the libraries you are using so we can inspect its possibilities.

Can we use analog pins of arduino as digital ones and if so the how??

Yes. You just treat them the same as any other digital pin.  On an Arduino all pins are digital. It's just that some have additional functionality, like analog input, or PWM, or serial, or SPI, etc.

ADC pin on esp8266?

@Juraj No one said anything about an ESP8266. Which, incidentally, is NOT an Arduino.

I know, but I would not wonder if OP had one and called it Arduino

@Juraj Unlikely, since they talk of analog "pins"", (plural) and the ESP8266 only has one. They'd then talk about "the analog pin".

And they wouldn't have said "use 2 and 3 pins of Arduino". I'm unclear on how anything ESP-related came up here.

@DaveNewton It's Juraj. You're never quite sure what goes through his mind sometimes ;)


text:
MPU6050 Calibration
Why does the MPU6050 IMU sensor not require calibration? I've used other gyro sensors on RC helicopters that required calibration at boot. Also, how does it know what its neutral position is considering that I don't need to calibrate it?

it calibrates itself and as the datasheet says "Enhanced bias and sensitivity temperature stability reduces the need for user calibration".

It's not entirely true that it does not require any calibration at all.
The MPU60X0 family's triple-axis MEMS gyroscope has certain features that reduce the need for calibration. These features are, as mentioned by Juraj, and on the datasheet:

Enhanced bias
Sensitivity temperature stability

This does not mean the sensor is 100% properly calibrated right out of the box, which means if you need it to be extremely accurate, you'd probably have to do some manual calibration on top of the built-in calibration features.
There is a discussion about this on this Github issue. I suggest reading up on that and you might be able to answer your own questions. They are also referring to this datasheet (Direct Download).


text:
Arduino potentiometer (external power) with amplifier
i am trying to make some kind of an amplifier. I got an amp board but want to read out the value from the potentiometer. The problem is that this pot is connected to the amp and has to be connected to the amps power Is there any way i can still read data (with an arduino) so that i can have a volume percentage on a lcd? Or is this imposible?
Amp 24v Potentiometer = 6pin. B50k
also what zould happen if i connect a 10k resistor instead of a 50k ressistor (audio potentiometer) what would the effect be?

Would this work??
btw thanks for helping!
https://www.aliexpress.com/item/2PCS-Precision-097-9mm-potentiometer-switch-biaxial-triple-50K-double-100K-rotary-handle-length-17-5mm/32811342965.html?spm=2114.search0104.3.15.50705d774mtDlF&ws_ab_test=searchweb0_0,searchweb201602_5_10065_10068_10547_319_317_10548_10696_10084_453_454_10083_10618_10304_10307_10820_10821_538_537_10302_536_10059_10884_10887_100031_321_322_10103,searchweb201603_51,ppcSwitch_0&algo_expid=5693c9b0-3022-443b-8f65-c4ca408cc919-2&algo_pvid=5693c9b0-3022-443b-8f65-c4ca408cc919

and does it mater that the last one is 100k (i need (50k) can i use the 100k for the arduino?

or this???
https://www.aliexpress.com/item/2PCS-LOT-09-type-precision-potentiometer-triple-B10K-axis-15MM-power-amplifier-volume-potentiometer-line-three/32830930075.html?spm=2114.search0104.3.9.50705d774mtDlF&ws_ab_test=searchweb0_0,searchweb201602_5_10065_10068_10547_319_317_10548_10696_10084_453_454_10083_10618_10304_10307_10820_10821_538_537_10302_536_10059_10884_10887_100031_321_322_10103,searchweb201603_51,ppcSwitch_0&algo_expid=5693c9b0-3022-443b-8f65-c4ca408cc919-1&algo_pvid=5693c9b0-3022-443b-8f65-c4ca408cc919

can you clarify the meaning of "some kind of amplifier". Do you want a preamplifier (signal voltage amplification), or a power amplifier (high current)?

high current 24 50amps per channel

This little board.
and i just want to be able to read from the potentiometer.
i am guessing i will have to find a triple pot or a quad pot...
https://www.aliexpress.com/item/50Wx2-TPA3116D2-Dual-Channel-DC-4-5-27V-Digital-Power-Amplifier-Board-Two-Channel-Stereo-High/32847729011.html?spm=a2g0s.8937460.0.0.79452e0epIatdy

It's impossible. The pot is most probably acting as a passive variable attenuator. As such the top end will be the incoming audio signal, the lower end will be ground, and the wiper will be the attenuated incoming signal. There's not a lot you can do with that.
You would need to replace the pot with an equivalent triple pot (if such a thing exists) and have one third of it connected to the Arduino.  The pot you have at the moment is a dual pot, and a log taper at that.
Alternatively adding some kind of quadrature (motor) encoder to the shaft of the pot may be a possibility.

A few options come to my mind:

I see you're using a double potentiometer, if you're using only one of it's outputs to control, you can use the other output to measure it's setting. (Or indeed use a "triple potentiometer" or added encoder as Majenko suggested.)
Use the Arduino as an intermediate (have the potentiometer as an input on the Arduino and control the output accordingly on the output of the Arduino).
Measure the output of the potentiometer. I'm not quite sure but the resistance over the potentiometer shouldn't be anything different depending on what is connected as well. Though you could also measure the output voltage on the potentiometer and from there deduce what it's value is (which may be difficult if it's an audio signal on this point in your system).

thanks for the comment i am using a double pot to have stereo i will try to get a triple pot do you think this one will work? even with 100k on the last one the reading should be the same right?

https://www.aliexpress.com/item/2PCS-Precision-097-9mm-potentiometer-switch-biaxial-triple-50K-double-100K-rotary-handle-length-17-5mm/32811342965.html?spm=2114.search0104.3.15.50705d774mtDlF&ws_ab_test=searchweb0_0,searchweb201602_5_10065_10068_10547_319_317_10548_10696_10084_453_454_10083_10618_10304_10307_10820_10821_538_537_10302_536_10059_10884_10887_100031_321_322_10103,searchweb201603_51,ppcSwitch_0&algo_expid=5693c9b0-3022-443b-8f65-c4ca408cc919-2&algo_pvid=5693c9b0-3022-443b-8f65-c4ca408cc919

I don't see why not, and for the price it's worth a shot? Quite interesting part actually, what would've been the odds of finding this locally ;p Though note it may be difficult to find a pinout of this pot, which is worth a check before ordering.


text:
WiFi.setOutputPower();
I'm trying to cut my esp8266 range down to about a meter to save power.  I know that I can adjust output power but I don't know enough to understand what a given setting will actually yield.
I can set zero to kill it or 20.5 to set max range, but what setting is appropriate for a meter or so?  Is there a rule of thumb?

The actual WiFi range is highly dependent on many more factors than just the TX power:

The antenna gain, directionality, and orientation of the receiver
The antenna gain, directionality, and orientation of the transmitter
The proximity of radio-reflective objects nearby (metal)
The proximity of radio absorbing objects nearby (humans)
RF Black Magic

In practice, test your situation by running a series of tests at lower and lower power settings until you get an unreliable connection, then bump it up a couple of notches from there.
Do not rely on transmitter power for security, however. You cannot stop someone from pointing a high-gain antenna at your device and communicating with it from a distance farther than 1 meter. TX power reduction should primarily be for energy conservation.

Thank you.  Am I correct in assuming that .01 would be extremely short range and 20.5 would be max range?

The lowest power output is 0;


text:
Controlling output frequency of 3 Phase SPWM Inverter
I am now on a 3 Phase SPWM inverter project, and i got this code from this article. It works perfectly on simulation. But the problem is, i can't make the output frequency variable. I intend to vary the frequency at range 0 to 100 Hz and use it to control the speed of 3 phase induction motor. Could anyone help me, please? Any advice or maybe you got a code that works perfectly in controlling spwm inverter frequency. Here is the code of 3 phase spwm inverter. Oh, i am using Arduino Mega by the way.
            int i=0;
            int j=0;
            int k=0;
            int x=0;
            int y=0;
            int z=0;
            int OK=0;
            int OK1=0;
            int OK2=0
            int OK3=0;
            int OK4=0;
            int sinPWM[]={1,2,5,7,10,12,15,17,19,22,24,27,30,32,34,37,39,42,
            44,47,49,52,54,57,59,61,64,66,69,71,73,76,78,80,83,85,88,90,92,94,97,99,
            101,103,106,108,110,113,115,117,119,121,124,126,128,130,132,134,136,138,140,142,144,146,
            148,150,152,154,156,158,160,162,164,166,168,169,171,173,175,177,178,180,182,184,185,187,188,190,192,193,
            195,196,198,199,201,202,204,205,207,208,209,211,212,213,215,216,217,219,220,221,222,223,224,225,226,227,
            228,229,230,231,232,233,234,235,236,237,237,238,239,240,240,241,242,242,243,243,244,244,245,245,246,246,
            247,247,247,248,248,248,248,249,249,249,249,249,255,255,255,255,249,249,249,249,249,248,
            248,248,248,247,247,247,246,246,245,245,244,244,243,243,242,242,241,240,240,239,238,237,237,236,235,234,
            233,232,231,230,229,228,227,226,225,224,223,222,221,220,219,217,216,215,213,212,211,209,208,207,205,204,
            202,201,199,198,196,195,193,192,190,188,187,185,184,182,180,178,177,175,173,171,169,168,166,164,162,160,
            158,156,154,152,150,148,146,144,142,140,138,136,134,132,130,128,126,124,121,119,117,115,113,110,108,106,
            103,101,99,97,94,92,90,88,85,83,80,78,76,73,71,69,66,64,61,59,57,54,52,49,47,44,42,39,37,34,32,30,
            27,24,22,19,17,15,12,10,7,5,2,1};

            int potinput = A1;
            int potfreq = A2;
            float potinputval;
            float potfreqval;
            float A;
            float F;

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

            pinMode(4, OUTPUT);
            pinMode(13,OUTPUT);
            pinMode(9,OUTPUT);
            pinMode(10,OUTPUT);
            pinMode(2,OUTPUT);
            pinMode(5,OUTPUT);

            cli();// stop interrupts
            TCCR0A=0;//reset the value
            TCCR0B=0;//reset the value
            TCNT0=0;//reset the value
            //0b allow me to write bits in binary
            TCCR0A=0b10100001;//phase correct pwm mode
            TCCR0B=0b00000001; //no prescaler

            TCCR2A=0;//reset the value
            TCCR2B=0;//reset the value
            TCNT2=0;//reset the value
            //0b allow me to write bits in binary
            TCCR2A=0b10100001;//phase correct pwm mode
            TCCR2B=0b00000001; //no prescaler

            TCCR3A=0;//reset the value
            TCCR3B=0;//reset the value
            TCNT3=0;//reset the value
            //0b allow me to write bits in binary
            TCCR3A=0b10100001;//phase correct pwm mode
            TCCR3B=0b00000001; //no prescaler
            TCCR1A=0;//reset the value
            TCCR1B=0;//reset the value
            TCNT1=0;//reset the value
            OCR1A=509;// compare match value
            TCCR1B=0b00001001; //WGM12 bit is 1 for CTC mode and no prescaler

            TIMSK1 |=(1 << OCIE1A);// enable interrupts

            sei();//stop interrupts
            }
            ISR(TIMER1_COMPA_vect){// interrupt when timer 1 match with OCR1A value
            if(i>313 && OK==0){// final value from vector for pin 13
            i=0;// go to first value of vector
            OK=1;//enable pin 4
            }
            if(i>313 && OK==1){// final value from vector for pin 4
            i=0;//go to firs value of vector
            OK=0;//enable pin 13
            }
            x = round(A*sinPWM[i]); // x take the value from vector corresponding to position i(i is zero indexed)
            i=i+1;// go to the next position
            if(OK==0){
            OCR0B=0;//make pin 4 0
            OCR0A=x;//enable pin 13 to corresponding duty cycle
            }
            if(OK==1){
            OCR0A=0;//make pin 13 0
            OCR0B=x;//enable pin 4 to corresponding duty cycle
            }

            if ((i==209) || OK1==1){//if i equal with 209 enable second signal
            OK1=1;//mantain if function
            if(j>313 && OK2==0){// final value from vector for pin 10
            j=0;// go to first value of vector
            OK2=1;//enable pin 9
            }
            if(j>313 && OK2==1){// final value from vector for pin 9
            j=0;//go to firs value of vector
            OK2=0;//enable pin 10
            }
            y = round(A*sinPWM[j]);// y take the value from vector corresponding to position j(j is zero indexed)
            j=j+1;// go to the next position
            if(OK2==0){
            OCR2B=0;//make pin 9 0
            OCR2A=y;//enable pin 10 to corresponding duty cycle
            }
            if(OK2==1){
            OCR2A=0;//make pin 10 0
            OCR2B=y;//enable pin 9 to corresponding duty cycle
            }
            }
            if ((j==209) || OK3==1){//if j equal with 209 enable third signal
            OK3=1;//mantain if function
            if(k>313 && OK4==0){// final value from vector for pin 5
            k=0;// go to first value of vector
            OK4=1;//enable pin 2
            }
            if(k>313 && OK4==1){// final value from vector for pin 2
            k=0;//go to firs value of vector
            OK4=0;//enable pin 5
            }
            z=round(A*sinPWM[k]);// z take the value from vector corresponding to position k(k is zero indexed)
            k=k+1;// go to the next position
            if(OK4==0){
            OCR3B=0;//make pin 2 0
            OCR3A=z;//enable pin 5 to corresponding duty cycle
            }
            if(OK4==1){
            OCR3A=0;//make pin 5 0
            OCR3B=z;//enable pin 2 to corresponding duty cycle
        }
        }
        }
        void loop() {

          potinputval = analogRead(potinput);
          A = potinputval/1023;

          potfreqval = analogRead(potfreq);
          F = map(potfreqval,1023,0,0,50);}

In this sketch the PWM values, matching a sampled sine curve, are stored in integer array sinPWM[]. The values from sinPWM (1 - 255) are used unmodified (via intermediate variables x, y and z) to set the various timing registers (OCR0A/B, OCR2A/B and OCR3A/B) which control the pulse width modulation. In this way the amplitude(s) of the generated sine wave(s) will be constant.
If you want to control the speed of the motor you have to multiply the values from sinPWM with a factor between 0 and 1. The most logical place is to do that when the values from sinPWM are transferred to the intermediate variables x, y and z. Example: x=round(0.8 * sinPWM[i]). The factor, 0.8 in this example, you can of course replace by a variable which value is derived from an analogRead() of a pin connected to a potmeter or some sensor. But make sure to convert it to a value in the range 0-1 before you use it in the calculation.

Ok.. I will try it. But could you tell me why I should multiply the value with  a factor between 0 and 1, please?

You feed the motor with three sine waves with a mutual phase difference of 120 degrees. The amplitude of the sine wave (= half of the top-top value) determines the speed of the motor. I say this with some reservation because there are many different types of electro motor. I assume you use a three phase motor with a squirrel-cage rotor.

Thanks for your reply. So i've tried the formula you've mentioned above without potmeter first ( i multiplied the sinPWM with value between 0-1), and it takes effect on duty cycle values. But when i connect the potmeter and improve the code, it didn't work. I think something's wrong with my analog converting formula.  Would you mind to take a look to my code above, please?

I will try. But could you first tell me the details about the motor you are using (do you have a datasheet, or manufacturer plus part number)?

I only have these 2 pictures. Please take a look.
Image1
Image2

Thanks for the pictures. What circuit do you have between the Arduino and the motor?

I have 6 gate drivers with 13-14 volt output ( i made my own gate driver with hcpl-3120 IC). Then i have a MOSFET bridge with 6 x Irfp460 MOSFETs. I haven't had a filter yet, because i'm thinking to control the SPWM first. And, it's hard to find references about 3 phase low pass filter.

Thanks for the information. Indeed you made a mistake with the code for processing the potmeter value. First, you don't have to set the pinMode for this pin (this has no further influance). Second the variable A should be a float (not an int, because an int can't hold fractions). To be sure to avoid integer division and to avoid A having an invalid intermediary value (interruption can happen at any point in the calculation) also make a float of potinputval and do the calculation as follows: potinputval = analogRead(potinput); potinputval = potinputval / 1023; A = potinputval;

But my (original) answer is not correct. I was under the impression that you were using a small motor (e.g. a toy motor) in an analog way connected to the Arduino.

I am not a motor expert. But from the plate on the motor it looks like an 3 phase AC asynchronous motor with squirrel cage rotor. If this is correct the motor should have 6 electrical connection points, some of them connected to one of the others (with a metal 'bridge'). The motor can be electrically connected in star or delta configuration (Google on these terms if this is new for you).

The rotation speed of these motors depends on the frequency of the (electrical) phases. So, if you want to change the speed of the motor, you have to change the frequency of the generated sine waves. Most probably this involves other settings for the various timers. It would take me too much time to figure out how to do this. Maybe somebody else from Stack Overlow can help or maybe the guy running the site were you got your co

But when i search for 3 phase induction motor controlling method. I found that vary the supply voltage will effect the motor speed. I think that could be work. And do you know how to invert an array or how to invert pwm? The code above provide 6 spwm output. If i put 2 output together, one of them should be inverted. So i need 3 normal output and 3 inverted output. Do you know how to do that?

I am pretty sure that you can't control the speed of this motor by varying the supply voltage. But you can try that out in a simple way: the supply voltage for the motor is applied via your motor driver (H-bridge), so it is relatively easy to vary it. The article you refer to in the 1st line of your question describes how to generate the positive and the 'negative' halves of the three fases. As the Arduino can't generate negative signals also the 'negative' halves of the fases are positive. Inversion has to be done by a separate circuit (which might be integrated in the motor driver circuit).

Hi PimV, you were right, i have to vary the frequency output of the inverter. The thing is, i haven't find any method to control it. Could you help me once again? Or could you give me some advices or something, please? Thanks in advance.


text:
Arduino Modbus slave error
I am trying to use Arduino as Modbus- RTU slave and Raspberry Pi as a Modbus master I have interfaced Max485 (RS485 to TTL converter) with Arduino and Rs485 to USB converter in Raspberry Pi, Initially, I was able to send data from Arduino to Raspberry Pi, but the data seems to inconsistent and fails to read most times
I am using https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino for Arduino Minimal Modbus for raspberry pi
Connections:

DI(max485)- TX ( Arduino),
DE(max485) -D2 ( Arduino),
RE(max485) - D2( Arduino),
Ro(max485) - RX( Arduino),
Vcc(max485) -5v( Arduino),
Gnd (max485)- GND( Arduino)

code for Arduino
#include <ModbusRtu.h>
uint16_t au16data[6] = {};
Modbus slave(5,0,2);
void setup() {
  slave.begin(19200,SERIAL_8N2 );
 }
void loop() {
  au16data[0]=100;
  au16data[1]=200;
  au16data[2]=300;
  au16data[3]=400;
  au16data[4]=500;
  au16data[5]=600;
  slave.poll( au16data, 6 );
  delay(3000);
}

python code
import minimalmodbus
from datetime import datetime
import time

instrument = minimalmodbus.Instrument('/dev/ttyUSB0', 5)
instrument.serial.baudrate = 19200
instrument.serial.bytesize = 8
instrument.serial.parity = minimalmodbus.serial.PARITY_NONE
instrument.serial.stopbits = 2
instrument.serial.timeout =6
instrument.mode = minimalmodbus.MODE_RTU

while(1):
    try:
        val = instrument.read_registers(0,6)
        # Registernumber, number of decimals
        print val
    except IOError:
        error_msg = "Failed to read from device"
        error_time = datetime.now()
        print "IO Error Time",error_time.isoformat(),error_msg

    except ValueError:
        error_msg = "Failed to read CRC"
        error_time = datetime.now()
        print "Value Error Time",error_time.isoformat(),error_msg
    time.sleep(2)

but now I am getting The exception of failed to read

why the delay in slave? it must run slave.poll to respond to requests from master

the array positions could be replaced by sensor values, some sensor do work slow for instance DHT11

time sensor reading as BlinkWithoutDelay example, but the slave must poll, the loop must run

even without the delay I am getting the exception of failed to read

on fritzing and in code you have DE as pin 2. in the wiring table in Question you have D4?

I made a mistake corrected that

Hint: Common ground missing. http://www.ti.com/lit/an/slla272c/slla272c.pdf


text:
ESP8266 like WiFi modules
I am trying to make a circuit using Nodemcu ESP8266 to control the speed and direction of 3 DC servo motors, however I am short of analog pins.
So are there any ways to increase the number of analog pins?
Or are there other WiFi modules like the ESP8266, but with more number of analog pins?

Short of Analog input pins or output pins? ESP8266 can do PWM on all it's output pins.

I need to control both speed and direction of multiple motors via WiFi, can PWM signals do that?

Your question noted that you don't have enough Analog pins -- what do you need them for? HOW are you controlling motors? There are many different ways, modules, and methods. Please add detail to your question.

ESP32 has much more pins

How many PWMs do you need?
Here you can find a useful description about PWMs on ESP8266 NodeMCU.
According to image, ESP8266 NodeMcu has 9 PWMs pin.


text:
Can't replace SoftwareSerial by Serial1 on Mega board
This sketch runs well with SoftwareSerial define and the monitor displays device modbus values. But now, i want to replace SoftwareSerial by Serial1
and i have no data.
This is the sketch with SoftwareSerial:
#include <SoftwareSerial.h>
#define SSerialRX        10  //Serial Receive pin
#define SSerialTX        11  //Serial Transmit pin
#define SSerialTxControl 40   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;

void setup()
{
  Serial.begin(9600);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  RS485Serial.begin(9600);
}
void loop()
{
  delay(500);
  if (RS485Serial.available())
  { for(int i=0; i<7; i++)
    {
    byteSend = RS485Serial.read();   // Read the byte

    Serial.print(byteSend, HEX);
    Serial.print(" ");
    }
  }
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  byte request[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
  RS485Serial.write(request, sizeof(request));

  digitalWrite(SSerialTxControl, RS485Receive);
  Serial.println(" ");
}

And the sketch i tried with Serial1 (pin 19(Rx) and 18(Tx)):
#define SSerialTxControl 40   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW

byte byteSend;

void setup()
{
  Serial.begin(9600);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  Serial1.begin(9600);
}
void loop()
{
  delay(500);
  if (Serial1.available())
  { for(int i=0; i<7; i++)
    {
    byteSend = Serial1.read();   // Read the byte

    Serial.print(byteSend, HEX);
    Serial.print(" ");
    }
  }
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  byte request[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
  Serial1.write(request, sizeof(request));

  digitalWrite(SSerialTxControl, RS485Receive);
  Serial.println(" ");
}

Can you help me to find my mistake ?

your code expects 7 bytes after asking if at least one is available

https://majenko.co.uk/blog/reading-serial-arduino

Sorry, but i don't understand what you mean ? Is there  a difference with byteSend length using SoftwareSerial or Serial1 ?

The difference is likely due to SoftwareSerial::read() taking a full character time (appx 105uSec at 9600 baud) because individual bits are collected by the software. With a hardware UART, the ::read() call takes only a few microseconds, since the bits are collected by hardware, without holding up the software (much...). So in the hardware case, loop() can execute the ::read() call much more frequently than characters can arrive. Short answer: in the the software version, you just got lucky!

So what is the best way to solve it, using Serial1?

I tried Majenko advices but nothing on monitor...

You need to wait until everything is transmitted before turning low the control signal. Try to add Serial1.flush() https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/HardwareSerial.cpp#L205 When searching on github.com for arduino rs485 libraries, every library that I can find uses serial.flush or a delay to allow the byte to be transmitted before turning low the control signal.

Ok, i will try.

what is the best way to solve it, using Serial1?

With either serial device, you need to collect characters until you have an entire message. If every message will be a fixed number of bytes, you can wait until the return value of the Serial::available() call indicates it has that many characters, then collect them into a buffer and process them. But this assumes you'll never get a badly-formed message. If you do, the incoming bytes will get out of sync with your program.
A better way is to collect bytes into your buffer (but do nothing with them) until you have a complete message (by byte-count, newline character, or however you need to recognize that it is complete) or your buffer is about to overflow, and then either process them, or if your buffer filled and the contents doesn't look like a valid message, discard it and try to re-synchronize with the source. That may mean reading and ignoring bytes until you get a newline, and dealing with the fact you got a garbled message, or telling your source to restart or reset. The exact method (or whether you even want to bother detecting bad messages) depends on the particular situation. Will someone die if you fail? Will something catch fire, burn parts, lose weeks worth of good data, ... ? Or is this an experiment whose consequence of failure are zero or at least not worth any effort to detect it?