text:
MKR1000 not showing up on OSX
I can't appear to get my MKR1000 to list a port on my mac in the arduino ide, am i missing something obvious or does it need additional drivers?
Also
➜  ~  csrutil status
System Integrity Protection status: disabled.
running OSX 10.11.3
Board appears to be working, default led flashing

What does dmesg tell you?

i get a new lines 036284.257826 IOUSBHostDevice@14100000: IOUSBHostDevice::getDescriptorGated: type 0x03 index 2 length 2 completed with 0xe00002e8 and bytesTransferred 0 036284.258099 IOUSBHostDevice@14100000: IOUSBHostDevice::getDescriptorGated: type 0x03 index 1 length 2 completed with 0xe00002e8 and bytesTransferred 0

Is that what you get when you plug the mkr1000 in, or just while it's idle?

when i plug it in

Have you installed the drivers? (If there are any?)

Drivers not required apparently, though I am no expert, if I've missed some please let me know

Double click the reset button on the board. Then it will show in the Port list :-)

Worked for me, thanks! For others: don’t forget to install the board in Arduino board manager as described here: arduino.cc/en/Guide/MKR1000.

I also had to use another (shorter) USB cable.

See if this answers your question:
https://www.hackster.io/charifmahmoudi/arduino-mkr1000-getting-strarted-08bb4a
If not, go to your Board Manager (this happened to me too) and search MKR1000. There should be another install to do. Install that one and you should be good.


text:
Custom built Arduino is not working - double blinks
I've made a home-made Arduino based on this video. The problem is that I can't upload anything, it doesn't react, only the LED double blinks in every second. What does that mean? How to fix it? Thanks.
Update:

This is surely impossible to answer without seeing what you did. Presumably you did something different from what is in the video, what that is, is impossible to say. I suggest posting a very clear photograph, at the very least.

Thanks for the quick reply - I've just provided one. Hope that helps. Thanks :)

Did you bought atmega chip with bootloader already on it?

I guess so - at least according to the Ebay seller.

It's a reasonably clear photo (another couple would help) however I do see at least one major problem. Pin 8 (and pin 22) are Ground, but I don't see any wires running to that. Also the 22 pF (or similar) capacitors connected to the crystal should have their other sides grounded.
I suggest you look at my page Breadboard Arduino which has clear photos and wiring guides. In particular:

Notice the ground wire, and how the capacitors are connected.
I suggest you double-check all wiring, and make sure it is very similar to this:

I've just checked it but the 22s are already grounded to pin 8 as that is a ground. I updated that area anyway according to your photo but having the same issue. I've built this entire stuff for 3 times but getting the same result. :(

Yes, but pin 8 should have a ground wire. You shouldn't rely on it being grounded through the chip. Also the capacitor in series with reset looks a lot larger than 0.1 µF.

Ohh I see, mine is a 100uF one. I mixed up with the 100nF. The smallest I have now is a 1uF. I wish I could just quickly "download" one ...

3D printer? And a bit of aluminium foil? Just remove the wire leading to the capacitor. When the upload starts briefly ground it to reset the processor (a quick tap) and then un-ground it.

I haven't got any 3D printer but an oven and a hair dryer. Am I still good?

source: Stack Exchange

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

sort: votes


text:
Using TTGO TS 1.0 TFT display
I'm trying to use the TTGO TS 1.0 display with a demo app from a different source. The demo app wants the following to be configured:
#define PIN_NUM_MISO 17     // SPI MISO
#define PIN_NUM_MOSI 23     // SPI MOSI
#define PIN_NUM_CLK  5      // SPI CLOCK pin
#define PIN_NUM_CS   26     // Display CS pin
#define PIN_NUM_DC   17     // Display command/data pin
// ** If you want to use them, set them to some valid GPIO number
#define PIN_NUM_RST  0      // GPIO used for RESET control

According to the TTGO readme the following wiring is used:
CS:16
DC:17
SDA:23
SCK:5
RST:9
My guess is:
PIN_NUM_MISO ?
PIN_NUM_MOSI 23
PIN_NUM_CLK  5
PIN_NUM_CS   16
PIN_NUM_DC   17

How to update the demo app to match with this? Reset is optional in the demo and there is 1 additional pin there as well which I can't figure out...

Sounds like your demo code is for an SPI screen, but you have an I2C screen.

Maybe silly question, can this be used somehow say, with a software I2C to SPI adapter?

You can re-write your demo code to use I2C instead of SPI. There's no such thing as a "software I2C to SPI adapter"

Although, looking at the code that's in that repo it may in fact be uni-directional SPI (MOSI and SCK but no MISO, which is quite common).

If it is, as I think it may be now I have dug into the code a little, simply an SPI interface with no MISO (which is quite common for TFT screens) you just map the pins 1:1 and ignore MISO.

PIN_NUM_MISO => Ignore
PIN_NUM_MOSI => SDA
PIN_NUM_CLK => SCL
PIN_NUM_CS => CS
PIN_NUM_DC => DC
PIN_NUM_RST => RST or Ignore

If the demo code insists on there being a MISO pin you can just assign that to any unused GPIO pin. You don't need to connect it to anything.
The majority of TFT and OLED driver code only ever writes to a screen and never reads from it, so MISO is not needed to actually control the screen.

Unfortunately the display doesn't work with this config. Which doesn't necessary mean the answer is wrong, I'll try to confirm it somehow.

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


text:
Overwrite image buffer (inside Adafruit SSD1306)
I'd like to add a method that replaces the entire image buffer into the Adafruit_SSD1306 library. I haven't worked with dynamic memory handling for ages and I'm not sure how to just simply overwrite its pointer to point to a different memory address where my newBuffer is.
static uint8_t buffer[SSD1306_LCDHEIGHT * SSD1306_LCDWIDTH / 8] = {}

void Adafruit_SSD1306::setBuffer(uint8_t * newBuffer) {
  buffer = newBuffer; // not sure which operator to use
}

Update: Passing by reference wouldn't work. The question is: how to overwrite by copying? Would it work well with memcpy?
void Adafruit_SSD1306::setBuffer(uint8_t * newBuffer) {
  memcpy(newBuffer, buffer, (SSD1306_LCDWIDTH * SSD1306_LCDHEIGHT / 8));
}

Update: The code above doesn't seem to making anything. This one neither:
void Adafruit_SSD1306::setBuffer(uint8_t * newBuffer) {
  for(int16_t i = 0; i < SSD1306_LCDWIDTH * SSD1306_LCDHEIGHT / 8; i++) {
    buffer[i] = 255; // experimenting
  }
}

Update: setPixel doesn't work either. - Needed display.display(); :)

Do you want to copy the contents of newBuffer in buffer or rewrite buffer to be uint8_t* which you can change?

(I'm feeding the newBuffer from network and) I wan't a solution that replaces the image buffer the fastest. I don't mind making some changes in the library as long as it's easy. :)

Does copying have big overhead compared to passing the value by reference?

I've just realised that passing by reference might not work as the buffer is in a specific location in the memory, can't be elsewhere.

Even when done properly, changing the code to point to a new buffer location won't free the old buffer.  Arduinos tend to have limited RAM, so you probably want to copy the contents into the existing static allocation, not abandon a big chunk of memory.

How would copying look like?

Something like memcpy() or similar most likely.

Can you check the update please?

void * memcpy ( void * destination, const void * source, size_t num );. You exchanged the argument order in your memcpy call.. Destination must be buffer. You must of course also guarantee that newBuffer has the required length.

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


text:
Camera switch with ov7670 to output standard A/V signal - composite
I've got 3 OV7670 cameras and would like to create a switch that outputs one of the cameras video as standard A/V out (I'm not sure the correct naming).
I found docs explaining how to use the cameras on the Arduino platform but I'm not sure how to output video signal - composite.

I think you mean composite video

Three cameras driven by 1 puny Arduino? Video is what you get when you read frames from the camera very quickly (at least 10 frames per second reasonably) and render those frames very quickly on some screen. You can't do either with an Arduino (Uno?) effectively, even if you'll be switching between them. Take a look at this though: https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno

Thanks for comments, I've updated post and now looking at the link.

An arduino uno is way too slow to output composite video. If you want to generate a PAL video signal you can see here the signal specification.
Most important, one line is output in 52us. If the line is 720px long (720x576 is the common resolution), then you will have to generate one pixel in 72ns. This means that

you will need a very fast DAC (a flash one)
you will need a VERY fast microcontroller. If you have a 160MHz uC you will have to send one output byte every 11 clock cycles, which means that you will barely be able to do any more processing.

Result: it is practically unfeasable. I suggest you, if you want to use it, to look for hardware encoders. But... Probably you will need some faster processing units: maybe a raspberry PI, which already have an hardware encoder...


text:
How to determine the SPIFFS size on an esp8266-01?
I'm confused about my esp8266-01 if they have SPIFFS or not. Is there a way to find it out? If they have, how to get their size?
I've got the following flash id: 0x1440e0.
Example SPIFFS apps keep crashing with wdt reset and lots of dumped hexes.

SPIFFS size is determined by you when you upload the sketch

First you need to know the size of the flash memory attached to esp8266 on your module. Common sizes are 512 kB (4Mbit), 1 MB (8Mbit) and 4 MB. Espressif Flash Download Tool (Windows) or esptool can determine it.
You can choose the size of the SPIFFS in your flash 'layout' by selecting the option in IDE Tools menu. Take one according to for you flash size and size of the files you want to put into SPIFFS.
If you have 1 MB flash on your module and you want to use OTA upload, let flash space for twice a space taken by the sketch.

All the data like WiFi config and binaries go to the flash memory? There is no other dedicated memory for those?

no. esp8266 uses the flash memory like a PC uses a hard-drive

Also, more importantly, I'm getting wdt reset errors with sometimes lots of hex dumps after uploading SPIFFS example apps. I've set the SPIFFS size to 512 (of 1M flash), but not sure if the Flash mode is correct. Any idea? Thanks

did you upload the SPIFFS image with the SPIFFS upload IDE plugin?

I've tried that as well as formatting the SPIFFS using the example code. Not sure what would be a working strategy. I've tried the following among others https://www.pastiebin.com/5ab790f66e9a1

Please have a look that pastebin code I placed. I'm unable to single upload and then run it without getting wdt reset errors. I have erased the esp with esptool prior to uploading it, didn't make any difference.

try some readonly example first. without formating. upload the spiffs from IDE https://github.com/esp8266/arduino-esp8266fs-plugin#arduino-esp8266-filesystem-uploader-

Tried with a different device and it worked. Both have 1M flash but differ in manufacturer. Does this mean the ESP lib doesn't support one?

do you use esp8266 core 2.4.1? the issue is known, but I do not know if it is fixed in the release https://github.com/esp8266/Arduino/issues/4061

I was using 2.4.1, then I removed it and manually installed the latest via git, so that I could apply both patches (not at the same time) from the link you showed. I might retry it as it was really late yesterday, might have done something wrong. Although some guy had no problem with his 001440E0 device which I am having problem with.

erase the flash or upload empty SPIFFS before the next test with the patch

The command with esptool is esptool flash_id and its output will contain something like Detected flash size: 512KB.

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


text:
Why does analog sensor "hum" when plugged into common ground?
I have the ground for an SD card module, LED, and piezo sensor all plugged into the same ground rail. When doing this I get a low "hum" in the piezo readings where instead of reading ground voltage (0) when there's no vibration, it cycles between 4 and 6.
However, when I switch the piezo's ground onto ground rail connected to different ground pin on my Arduino, the hum goes away. If I keep the piezo on original ground and move the SD card module's ground, the hum comes back.
I'm very new to electronics, so I'm wonder what's going on?
EDIT: Here's a diagram of the circuit.

You have a ground loop. Without seeing the actual physical layout it is impossible to determine the cause. This is a common problem in audio circuits. Fixing this is as much an art as a science. The usual solutions involve a single earthing point, earthing at one end only or in extreme cases common mode rejection techniques.

I have added a diagram of the circuit. How could this result in a ground loop?

This is an idealised diagram. These kind of problems are often related to the physical layout e.g. parallel wire runs. I agree that there appears to be nothing amiss.  As I stated this is a black art. I would suggest separating the low level analog circuit from the rest of the wiring - i.e. DO NOT share any earth cabling with any other circuit. This appears to be what you have done when it worked. You should also minimise any other source of interference by using twisted wires to the sensor.


text:
SDS011 Dust Sensor Checksum Error
I'm working with an SDS011 particular sensor through its serial interface. The spec sheet (http://inovafitness.com/upload/file/20150311/14261262164716.pdf) indicates that the second to last byte of a serial packet is a checksum equal to sum of all the data bytes.
I am using pyserial to read and interpret the serial data. Here's a snippet of the code:
import serial

def read_sensor(port):
    while True:
        header = port.read(2)
        if header == b'\xAA\xC0':
            data = port.read(6)
            checksum = port.read()
            tail = port.read()
            if tail == b'\xAB':
                return header + data + checksum + tail

port = serial.Serial(port=MY_PORT)
packet = read_sensor(port)
data_sum = sum(packet[2:8])
checksum = packet[8]

if data_sum == checksum:
  print('Ok')
else:
   print('Error')

However, I haven't got a single packet whose checksum hasn't been an error. Is there anything I could be potentially doing wrong?

Generally, a checksum byte is computed using 8-bit arithmetic, with overflow ignored.
The Python sum function uses arithmetic of indefinite precision (eg, 32- or 64-bit words for small values, with additional words for larger numbers).
Try comparing checksum to data_sum % 256.  If that doesn't fix the problem, print out some of the data packets and checksum values so that you can use a calculator to test different combinations.

data_sum % 256 fixed it. I thought it was strange that data_sum values were greater than a byte. Should've just checked the first byte!

I assume MY_PORT stands for COMxx. Since you set no timeout, it means port.read() will block till it gets the number of bytes requested. I suggest you add a print() to display the bytes returned, if any.
To get the sum, use data_sum = sum(packet[2:8]) & 0xff to ensure you only get a byte. Also add port.reset_input_buffer() right before you call read_sensor(), to flush the input buffer.
It would also be a good idea to take at least 3 consecutive readings from the sensor in case of any errors in the first reading right after opening the port. Dont forget to add a port.close() at the end of your code.


text:
How to read Serial data when multiple functions are Running?
I want to halt the execution of that code, when arduino is receiving serial data for the execution. Right now the Serial data runs when the other code has completed its execution. How can I do it ?
void loop() {
    dmd.setBrightness(brighVal); // set the brightness to led matrix
    scroll();  //function to scroll message

}
void serialEvent() {
  while (Serial.available()) {
    Jsondata = Serial.readString(); //reading json data from APP
    DynamicJsonBuffer jsonBuffer;
    Serial.println(Jsondata);
    JsonObject& root = jsonBuffer.parseObject(Jsondata);
    if (root.containsKey("BiM")) {
      brighVal = root["BiM"];
      switch (brighVal) {   // set's the value of brightness according to brighVal
        case 0:
          brighVal = 2;
          break;
        case 1:
          brighVal = 10;
          break;
        case 2 :
          brighVal = 25;
          break;
        case 3 :
          brighVal = 200;
          break;
      }
    }
  }
}
void scroll() {
  dmd.clearScreen( true );
  dmd.selectFont(Arial_Black_16);
  dmd.drawMarquee("Scrolling Text", 17, (32 * DISPLAYS_ACROSS) - 1, 0);
  long start = millis();
  long timer = start;
  boolean ret = false;
  while (!ret) {
    if ((timer + 30) < millis()) {
      ret = dmd.stepMarquee(-1, 0);
      timer = millis();
    }
  }
}

Then let scroll return immediately
void scroll() {
    static long timer = 0;
    static boolean scroll = true;
    if(scroll){
        dmd.clearScreen( true );
        dmd.selectFont(Arial_Black_16);
        dmd.drawMarquee("Scrolling Text", 17, (32 * DISPLAYS_ACROSS) - 1, 0);
        scroll = false;
        timer = millis()
    }else {
        if ((millis() - timer) > 30)  {
            scroll = dmd.stepMarquee(-1, 0);
            timer = millis();
        }
    }
}

The static keyword means that the value of the variable will be kept across calls.
I used the fact that it will be called in a loop to remove the while loop inside. I split the function up into 2 parts: The reset and the update. We first run the reset to init the marquee. After the reset it will set the boolean so the next time it will enter the update part. Then I used the exit condition of the original loop to make it reenter the update part next time.

it worked .Can you please explain the changes? Thank you so much for helping out.

@RaviParmar I added some explanation.

What if i have multiple functions @ratchetfreak. for example

@RaviParmar Do the same for each function, make sure that no function ever blocks for an extended period of time but instead returns instead. Then using saved state in a global or static local resume the correct actions.

thank you @ratchetfrek. it seems that i have used  lot of delay functions in all the functions because of which arduino got halted.

I am facing some weird issue.The second message is displayed first and  first  text in scroll is splitting into two half.void loop(){ scroll(); Split(); }void Split() { static long Splittimer = 0;static boolean SplitState = true; if (SplitState) {dmd.clearScreen(true); dmd.selectFont(SystemFont5x7);dmd.drawString(0, 0, "World", 5, GRAPHICS_NORMAL); dmd.drawMarquee("Scrolling text", 15, 32, 8);  SplitState = false;Splittimer = millis(); }else {  if ((millis() - Splittimer) > 30)  {SplitState = dmd.stepSplitMarquee(8, 15); scrolled  Splittimer = millis(); } }} @ratchetfreak


text:
Programming Arduino in Pascal?
My question is simple: there is any Pascal or Pascal-class (FPC, Delphi, mikroPascal) programming language for Arduino?
Preferably (I hope I don't ask too much) that language should not be older than 10 years.

Update:
Let's not start a flame war about "why the xxx programming language is so much better Pascal" and keep focus on the core of this question. I know that Pascal has it flaws (nothing its perfect, right?). I accept them and I still want to use it :)
Many thanks.

Because the usual Arduino environment is based on C++ you'd be best searching on "Pascal for AVR" which is the microcontroller used and it looks like there's a few options.

Perhaps Mikroelektronika has some compiler based on Pascal.

Why do you want to? Arguably, C++ is "Pascal-like". I used to program in Pascal heavily, and moved to C/C++ when it became obvious that most serious programming was done in those languages.

One day I will learn C as you recommend. Until then, my question is about Pascal. Many thanks for your recommendation anyway.

Brian W. Kernighan, Why Pascal is Not My Favorite Programming Language, http://www.threedee.com/jcm/psystem/whypascal.html

@MikaelPatel - WOW! I cannot believe people are are still quoting articles wrote at the dawn of programming era. ALL the drawbacks shown in the article are now gone. I think in '81 C had way more problems/drawback. C only got its ANSI standardization in '88. Come on Mikael, bring your knowledge up to date and quote a decent 201x article to clean your embarrassment. Pascal has evolved in billion ways since 1981 (see modern Pascal based languages such as FPC+Lazarus and Delphi)! Don't live in the past!

@Kenny How about you contributing with something? A quote, some code, testing to use what is available in main-stream, etc. So far I think you have not made any friends around here. There are many reasons for why Pascal has left main stream development and why most  embedded development use C/C++. We are a few that are trying to help you change focus. Obviously you can continue to look for an Arduino Pascal but it will be hard to find supporting libraries, drivers, etc.  Please see the bigger picture - live in the now :) :) :)

@MikaelPatel-Contributions related to programming / electronics are not really relevant if they point to some ancient article written back in 81.  I don't think that posting (as you) the first random link found on google is good for the community. So, instead of posting some random garbage I will refrain until I have something relevant for community.

@MikaelPatel-Thanks for the revenge downvote.  Please remember that the question is not "Why Mr. Patel hates Pascal" but "Is it possible to program Arduino in Pascal?". Answer THAT if you want to give something valuable to the community!

@Kenny Yes, we should focus on your original question. Please see my answer. The Pascal debate is very much off-track. Who cares why someone would want to do that. It is not relevant. You should get an answer to the question about using Pascal on Arduino.

Not Pascal, but Ada, which is much less restrictive than Pascal while enjoying the same advantages over low-level programming, and much more actively supported with language revisions as recently as 2012 and the formally provable SPARK language, for when you need your code to work.
Any processor which gcc supports can potentially support Ada, whose Gnat compiler is fully part of gcc.
That's not the whole story because you also need run-time system support for Ada's facilities, but for the Arduino's AVR processor there is a well established environment in the form of the AVR-Ada project.
It generates nice tight little executables, you'll be amazed how much less space simple Gnat executables take compared to Arduino ones - unless you've already made the same comparison between Arduino and C ... which after all uses the same gcc compiler.
For ARM-based Arduinos (Arduino Due at least) the same is possible, though the support is newer and possibly less well established, see the Cortex-GNAT project.
Leaving the Arduino, Ada has also been demonstrated on the MSP430 processor - my own project, sadly neglected at the moment.

Read your own question. You SPECIFICALLY asked about "... or Pascal-like languages". How amazing can Ada can be? the best way to find out is learn. You can use a Pascal-like subset and ignore the advanced features if you like; some of them are inappropriate for MCUs anyway. And re: language revisions,  the latest standard for Pascal seems to be ISO7185:1990, perhaps you are confusing compiler revisions with language standards? Of course Gnat is updated much more often than the language itself.

Clarifications: 1. I am talking about Pascal derivatives (mikroPascal, FPC, Delphi, etc). 2. I am talking about the 'thing' that you install and use in your computer not about ISO. When I will do the program for Arduino I will use a real piece of software (hopefully Pascal) not an ISO.

I'm OK with you not "accept"ing it, btw. One or two of the comments pointed at possible alternative leads : if you follow up and they turn out to be useful, you can always add your own answer. Alternatively there used to be some sort of Pa front end for gcc. So if you feel strongly about Pascal, why not try building that for the AVR back-end, in which case the AVR-Ada project (runtime system) and my MSP430-Ada documentation may provide useful clues about some of the steps on that path. (Working on gcc is not trivial!) Good luck...

Anyway, until somebody will provide a different answer (if ever), Ada is indeed the closest thing to Pascal. I will accept your answer is no better alternative is provided. Thanks anyway. Upvoted.

@Kenny I hear you on obsolete criticisms of Pascal. Ada suffers from the same irrational reluctance to consider it and that affected me for years. I started programming in Wirth's first big language (Algol-W), also used Turbo Pascal (fantastic for its era) then his third (Modula-2 - great but with its limits). Then C and C++ for a decade or so thanks to their commercial inevitability, despite their design insanities. Looking for a saner alternative, tried Ada (not previously available). After C++, felt more like healing than learning. Not a recommendation, just a story of a journey.

@BrianDrummond- Ok, I will try that. I am looking to buy my frist Arduino board.

A Pascal front-end to the Gnu compiler collection (gcc, on which nearly all the of AVR programming is based) already exists. Therefore, a Pascal compiler for AVR exists in principle if not in fact (and I don't know that it doesn't). I'd start by getting in touch with the folks working on the GPC to find out what has already been done.

Is it possible to program Arduino in Pascal?

The answer is yes and no. The answer is yes because it is possible to port the p-code virtual machine to Arduino and compile for that.
The answer is no if extending the question with "is there a supported open-source Arduino/AVR IDE for Pascal available?"
There are a few commercial AVR/Pascal products. You can easily web-search them.
Last, a possible short-cut is to use p2c, a Pascal to C translator, as a pre-processor in the Arduino IDE. There are hooks in the Arduino build for adding additional tools.
Cheers!

Thanks @MikaelPatel. Honestly, I don't mind paying (up to) 100 bucks for a Pascal commercial tool. I pay one order of magnitude more for my Delphi license so, 100 is not that much. P2C seems a decent alternative. I will consider P2C versus Ada (as recommended by Brian). Upvote (but I will keep Brian's post a the answer for the moment). Many thanks again.

There's also pascal p5c at sourceforge --> https://sourceforge.net/projects/pascal-p5c/
It uses gnu c as intermediate code so should work on any platform where gcc is available.


text:
Adding a custom board to the Arduino IDE
I would like to know what is the procedure for adding a custom board to the Arduino IDE?
My custom board is similar to the Arduino Zero. Instead of using the ATSAMD21G18, my board is based around the ATSAMC21G18. I also have the Atmel/Microchip SAMC21 Xplained development board.
I have found some open source code where the author has adapted/forked the Arduino SAMD21 code and made it work for the SAMC21 Xplained board (here). The author has stuck to the Arduino hardware folder structure and has added the SAMC21 Xplained to the board.txt file.
As a test, when I install the Arduino SAMD21 from the Arduino Board Manager, I noticed that it installed the hardware files in the following directory:
 %LOCALAPPDATA%\Arduino15\packages\arduino\hardware\samd\1.6.19\

I have read that to add hardware files to the board manager I need to create a .json file with the appropriate details. More information here. However, as far as I can tell, this requires me to zip the SAMC21 hardware files into a tarball and provide a URL to that tarball. I also need to generate and insert a SHA in the .json file.
Am I on the right path with the .json file?
Or should I just download the SAMC21 hardware files and place them in the %LOCALAPPDATA%\Arduino15\packages\arduino\hardware\samd\ folder next to the 1.6.19 folder?
My last resort would be to just copy the files into the existing SAMD21 hardware folder?

I have looked into the following Arduino SE questions but they do not answer the question satisfactorily.

upload.tool not used in custom boards.txt?
Arduino Due custom platform for school and library installation (I would prefer not to use the Arduino IDE in portable mode.)

I think the .json file is just for publishing so the board manager can find it; you can edit boards.txt to add your own based on zero if its just for you.

do you want to publish it or only for your use? for your use it is simpler to add it into hardware subfolder of your sketches folder

@Juraj This would be just for my own use but I would need to replicate it on a couple of machines. I would appreciate if people could add answers for both scenarios.

@Juraj Thanks. I will look into the link shortly.

The simplest clean way to add your board using an existing core is to add the variant to your sketches folder's hardware subfolder. Only boards.txt and files for the board variant are added.
In your sketches folder create a 'hardware' folder. In this folder create a folder with the name of your boards package and a subfolder with the architecture name and a subfolder for variant and a name of the variant. for example hardware/my_boards/samd/variants/samc21x
In your variant folder (variants/samc21x) put the files for your variant based on variant files of the closet variant in the referenced hardware package. In your case perhaps a mkrzero would be a good example.
In your package's root (hardware/my_boards/samd/) add boards.txt file with entries for your board.
For boards.txt take the options for a similar board in referenced package. Change the names and settings and prefix build.core value with the name of the vendor of the referenced package. For arduino/samd it would be arduino:. For example samc21x.build.core=arduino:arduino
My custom and customized boards definitions https://github.com/jandrassy/my_boards

and samc21x.build.extra_flags=-D__SAMC21G18A__ {build.usb_flags} or similar. the Arduino SAMD core supports compilation for SAMC

success story: https://forum.arduino.cc/index.php?topic=602377.msg4089655#msg4089655


text:
What programmer do I select in Arduino IDE for the ATMEL-ICE ISP?
I have been using an AVRISPmkII for many years but recently gave mine away to another hobbiest. I wnated to buy a replacement and have had to buy an ATMEL-ICE ISP as the AVRISPmkII is now unavailable.
Occasionally, I like to program the Arduino Uno from the Arduino IDE using the ISP.
However when I go to select the programmer (from the tools menu), I don't see the ATMEL-ICE in the list.
How do I get Arduino IDE to recognize the ATMEL-ICE ISP?
Note: I am using Arduino IDE v1.6.8.

Is the AVRISP MKii unreliable because the 6-pin cable is worn out? I made a new one for mine with a new piece of ribbon cable and two header connectors. Might be able to reuse the same cable even, just cut it a little shorter at both ends. I think mine wore out at the plastic case end.  https://www.digikey.com/product-detail/en/amphenol-icc-fci/71600-006LF/609-2841-ND/1302571

@CrossRoads Thanks for the information. I often give my programmers away (in a bundle of other Arduino bits and pieces) in an attempt to inspire more people to take up coding.

Atmel is no longer selling the AVRISP MKii. I'm holding onto mine! Still works great after changing the ribbon cable out.  Not too hard too split the case to unplug and plug a new one on.

@CrossRoads I am glad to hear that yours is working great, however, this is not the problem I am having.

As of V1.8.2, the ATMEL-ICE is now included as a programmer in the Arduino IDE.
The ATMEL-ICE was not available as a in-system programmer (ISP) in version 1.6.8 of the Arduino IDE.

On the 20th of Jan 2017, user facchinm added the ATMEL-ICE to the list of programmers in the IDE, and it was merged into the master on the 8th of Feb. It was released as a version on the 22nd of March 2017.


text:
ESP32 Bluetooth Master does not connect
I want to connect an ESP32 to a SMA Sunny Boy SB5000-TL Solar convertor over Bluetooth, but I cannot establish a connection and I'm kind of stuck.
I use the internal bluetooth module of the ESP32.
What I've done:

I started with this project: https://github.com/delhatch/ESP32_to_SMA but I did not get past the connection. I tried to locate the problem area:

I tried using an Android app (Oxley Solar) to connect to the SB5000-TL Solar convertor, and that works great. The pin code of the convertor is set to 0000.

I tried using two ESP32 modules, one as master, one as slave and that works as well, though I do not need to set a pin. So the bluetooth module of my ESP32 works properly.

So the problem must be in my code, I guess.
This is the code I use to connect to the convertor:
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;
boolean confirmRequestPending = true;

// uint8_t ESP32Slave[6]  = {0x84, 0xCC, 0xA8, 0x2C, 0x70, 0x1E}; // Address of Slave.
uint8_t SMA[6]  = {0x00, 0x40, 0x65, 0x12, 0x4B, 0x3E}; // Address of my SMA inverter.
const char *pin = "0000"; //<- standard pin

void setup() {
  Serial.begin(115200);
  SerialBT.enableSSP();
  SerialBT.onConfirmRequest(BTConfirmRequestCallback);
  SerialBT.onAuthComplete(BTAuthCompleteCallback);
  SerialBT.begin("ESP32master", true); //Bluetooth device name
  SerialBT.register_callback(callback);
  SerialBT.setPin("0000");
  Serial.println("Connecting...");
  bool connected = SerialBT.connect(SMA);
  if (connected) {
    Serial.println("Connected!");
  } else {
    Serial.println("NOT Connected!");
  }
  delay(500);
  SerialBT.end();
  Serial.println("Bye!");
}

void loop() {

}

void callback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
  Serial.print("Got event!");  Serial.println(event);
}

void BTConfirmRequestCallback(uint32_t numVal)
{
  confirmRequestPending = true;
  Serial.println(numVal);
}

void BTAuthCompleteCallback(boolean success)
{
  confirmRequestPending = false;
  if (success)
  {
    Serial.println("Pairing success!!");
  }
  else
  {
    Serial.println("Pairing failed, rejected by user!!");
  }
}

This is the result in the Serial console:
Connecting...
Got event!0
Got event!8
NOT Connected!
Got event!1
Bye!

I tried to replace the Mac Address with the name of the Convertor,
I tried with and without pin.
I'm kind of stuck.
Any idea's of how I can check what is wrong?
Is there any kind of scanner I can use to see what is happening with the app that works and what is (not) happening with my code?
Other ways to get more info/leads?
Could I use a Bluetooth sniffer or so (no experience) to find out what happens?
Any advice would be greatly appreciated!

I have searched the net for a solution for this issue for esp32 trying to connect as a serial master . All i can find is that there is a connection success reporting issue with BluetoothSerial.h while using the correct address or name of the slave .latest version 1.4 i think reports as connection successful, when it is not. version 1.3 reports connection failed. Very frustrating with no updated fix at github. You have probably noticed that all examples of BLE classic use an esp32 as slave and an android phone connecting as a master to switch relays on and off on a BLE board . But there are no


text:
How to enable interrupt again after disabling it?
I am not quite experienced with Arduino and Interrupts. Below I am trying to disable interrupt once it got detected and enable it again when I start loop again. But in below code I am not able to enable it.
int L = 2;
volatile int done0=0;
volatile unsigned long leftT=0;

void recordL()
{
  if(done0 == 0)
  {
      leftT=micros();
  }
  done0 = 1;
  detachInterrupt(0);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(L,INPUT);
  Serial.begin(9600);
  Serial.println("Start..");
}

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

  attachInterrupt(0,recordL,RISING);
  done0 = 0;

  while(!done0)
  {

  }

  Serial.println("Sound..");
  Serial.println(leftT);
  delay(1000);
  Serial.println("After Delay");
}

but I made small change in code. I shifted 'done0=0' above attachInterrupt() then it is working. Why is that happening? One more issue that I am facing here is when I enable it again one more saved value is coming. Does it store value when I have disabled it?
int L = 2;
volatile int done0=0;
volatile unsigned long leftT=0;

void recordL()
{
    if(done0 == 0)
    {
        leftT=micros();
    }
  done0 = 1;
  detachInterrupt(0);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(L,INPUT);
  Serial.begin(9600);
  Serial.println("Start..");
}

void loop() {
  // put your main code here, to run repeatedly:
  done0 = 0;
  attachInterrupt(0,recordL,RISING);

  while(!done0)
  {

  }

  Serial.println("Sound..");
  Serial.println(leftT);
  delay(1000);
  Serial.println("After Delay");
}

Output for 2nd case (Sound is coming only once but I am getting sound after delay also):
   Start..
   Sound..
   2873000
   After Delay
   Sound..
   3873528
   After Delay

You likely need to read the specific processor specifications to understand what may happen when you disable and enable interrupts.  There are many Arduino boards which use different processors.  So a question about interrupts with out specifying which processor you are using is difficult to answer.  I suspect the hardware for the processor you are using keeps track of interrupts while interrupts are disabled.  And will try to service them when you enable interrupts once again.  But this is really up to how the processor's hardware works.

Write down the output you got for the second case.

@MITURAJ I inserted in question.

Are you using a pushbutton to give interrupt ?

No sound from sound sensor.

The code needs modifications. I presume you are using digital pin 2 as your interrupt pin here. But the first argument to your attachinterrupt () is simply 0. That's not a recommended way of passing argument. Check the below link.
Check -https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
I think this is what happened -
In the first case, the code is stuck in the infinite while loop as interrupt routine might have called just after attachinterrupt() and done became 1. After that done becomes 0 and got stuck in while (!done) loop forever as interrupts are now disabled.
In the second case, after making done = 0, the code entered into the interrupt routine and made done = 1, comes out, skips while loop and prints output. Again in loop(), done is made 0 and interrupts are attached back. And again interrupt routine is executed again , possibly because it detected another rising edge. This issue is there with push buttons, due to bouncing. Here, sound sensor may not be outputting clean digital signal.
Note: Disabling interrupt inside interrupt routine is meaningless cz arduino by default disables all interrupts and queues further interrupts during the execution of an interrupt routine. So I really doubt its behavior. You better rectify it by removing that statement from there and put it in the main code after while().

Below I am trying to disable interrupt once it got detected and enable it again when I start loop again.

not sure why you want to do that but interrupts are DISABLED in isr by hardware (unless you explicitly enable it in isr) so what you are trying to do is done for you automagically.

But in below code I am not able to enable it.

mostly it involves enabling the respective interrupt mask, unless you want to enable / disable all interrupts.

Actually I want to take sound once and shut that interrupt for rest of the code in loop and enable that again.

Normally, an Arduino interrupt attachment is made in the setup() method and is never removed.  Consider moving your call to attach the interrupt accordingly and removing your call to detach the interrupt.
Your approach is understandable when considering normal embedded processor programming.  In such cases all aspects of the hardware must be considered.  This may include resetting the interrupt hardware for the next interrupt event.
When programming in the Arduino paradigm, many details are abstracted from the coder to make the coding experience simple and straight forward.  In the example found at the bottom of the interrupt attachment Arduino Reference page, it is evident that no code needs to be added to manage the interrupt within the interrupt method.
To address your question specifically (why does the 2nd code listing work while the 1st does not) consider the actual (possible) sequence of events. The setup() method is 1st run followed by the loop() method.  In the 1st code listing you attached the interrupt then set your "done" flag allowing the code in the interrupt to run. You cause the interrupt by raising the input on interrupt pin 0.  This will likely work and you will then disconnect the interrupt.  If you try to cause the interrupt again before 1 seconds elapses it will appear that the interrupt did not work because the loop() method is still waiting for the 1 second delay you have added and has not re-attached the interrupt.  After the 1 second delay has ended, the loop() method will be called again.  It is likely this time the processor's hardware remembers you tried to cause an interrupt.  So when the interrupt is attached, the interrupt routine is called.  But the "done" flag has not yet been set to zero so the interrupt does not execute code controlled by the "done" flag.  In the 2nd code listing you have remedied this problem by setting the "done" flag before reattaching the interrupt.

Why output is changing if I change position of 'done0 = 0'?

Sorry didn't get it. Whichever value done flag has at the end of loop, loop will execute further from start and re-attach interrupt. Why that won't happen?


text:
I can't manage to upload multiple sketches
I'm doing a gardening project. It involves multiple sensors and even having the sketches for them, I don't know how to make them run together and get a reading on them at the same time. I'm really new with this. It's my first Arduino ever.
I seem to manage getting a read on one of the sensors, but whenever I try to upload a new sketch, it fails to load.
Here are a couple of the codes I want to run together. One is a temperature/humidity sensor and the other one a soil humidity sensor.
Thanks in advance!!!
#include "DHT.h"          // DHT & AM2302 library

// Data pin connected to AM2302
#define DHTPIN 2

#define DHTTYPE DHT22       // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);   // LED pins

//////////////////////////////////////////////////////
//
// SETUP
//
void setup() {
  // Setup serial monitor
  Serial.begin(9600);
  dht.begin();
}

void loop() {

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow     sensor)
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  // check if returns are valid, if they are NaN (not a number) then     something went wrong!
  if (isnan(t) || isnan(h)) {
    Serial.println(F("Failed to read from DHT"));
  }
  else {
Serial.print(F("Humedad: "));
Serial.print(h);
Serial.print(F(" %\t"));
Serial.print(F("Temperatura: "));
Serial.print(t);
Serial.println(F(" C"));
  }

  // Wait 3 seconds
  delay(3000);
}

The other code:
   //////////////////////////////////////////////
  //        ARDUINO SOIL MOISTURE DEMO        //
 //                                          //
//           http://www.educ8s.tv           //
/////////////////////////////////////////////

int sensorPin = A0;
int sensorValue = 0;
int percent = 0;

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

void loop() {

  sensorValue = analogRead(sensorPin);
  percent = convertToPercent(sensorValue);
  printValuesToSerial();
  delay(1000);
}

int convertToPercent(int value)
{
  int percentValue = 0;
  percentValue = map(value, 1023, 465, 0, 100);
  return percentValue;
}

void printValuesToSerial()
{
  Serial.print("\n\nAnalog Value: ");
  Serial.print(sensorValue);
  Serial.print("\nPercent: ");
  Serial.print(percent);
  Serial.print("%");
}

Only one sketch at a time. You will have to merge them (somehow)

@Greenonline, OP did it some hours ago. read the answer and comments

@Juraj -  good point, but then, in that case, the original question has been changed substantially

I can't manage to upload multiple sketches

The arduino can only run one sketch at a time. You can do multiple things in a single sketch, but you can only have one sketch.

... but whenever I try to upload a new sketch, it fails to load.

What exactly fails? You should be able to change sketches, the new sketch should replace the old sketch; If this isn't working you have another problem all together.

Here are a couple of the codes I want to run together ...

You will have to write a new sketch that combines the behavior of the two sketches.
something like:
...
setup()
{
    // common setup code goes here
}
...
loop()
{
    int sensor_reading_1 = analogRead(sensor_pin);
    float sensor_reading_2_h = dht.readHumidity();
    float sensor_reading_2_t = dht.readTemperature();

    ... // do stuff with the readings
}

The error is because I used 2 Voids in 2 separate tabs, apparently.

@guillo umm ... what? that doesn't make any sense at all!

Here's the error that appeared:
"Redefinition of void setup"
Cant manage to paste the entire error code here

A couple of hours in the making I managed to merge them together. Thanks for your replys tho!

@guillo just to be clear, it's not "I used 2 Voids", but "I declared 2 setups". You can have infinite void functions, since void is the return type, but every function should have a unique name


text:
Where to connect shield in USB power supply for Arduino?
I'm making a 5 volt portable regulated power supply (using LM7805 regulator IC) for Arduino UNO. I'm planning to use a USB connector as its output socket, this way I can just plug it into the Arduino to power it.
My problem is where do I connect the USB sockets's shield? (Not an Arduino shield - I am talking about the USB cable's shield).

As far as I know it should be connected to the ground if it is a host device - can we consider the power supply as a host device?

Welcome to Arduino SE.  Please take a moment and take the tour at https://arduino.stackexchange.com/Tour

I don't see how it's too technical to be here. (FYI It's also named Electrical Engineering not Electronics Exchange) The question belonging there is also questionable, they usually push questions like these back here.

@Code Gorilla Thanks for the edit and advice, I'll try Electronic Exchange too.

SDsolar, Avamander Thanks for showing interest in my post.

@CodeGorilla I'm well aware of that. It just won't survive there and if you find it off-topic, use the close flags to indicate that.

In response to the "off topic" close flag; This is a perfectly acceptable question and falls within the "power" and "USB" Arduino Stack Exchange tags.

A similar question has been asked in the Electrical Engineering Stack Exchange: EMI/ESD protection for USB interface?

As for the SHIELD connection, you are correct - it is the metal casing of the connector and the braided shield of the USB cable that connects so it, which is likely referenced to protective Earth somewhere on the PC side of things. For EMI reasons it should not be directly tied to the GND signal connection, but should be connected through some impedance. I've seen both parallel resistor / capacitor (as you've shown) and ferrite bead connections between them. --Adam Lawrence

A good technical explanation was written by Ali Chen in his answer to this question:

Ali Chen's Answer to Structure of a USB 2.0 connector

In the answer, Ali recommends using a 330 ohm resistor in parallel to a 0.1uF capacitor between the digital ground and the protective earth (shield).

simulate this circuit – Schematic created using CircuitLab

If the supply for the Shield is 5V, then you can use one of the 5V lines on the Arduino to power the Shield, plus a common ground of course.

This isn't about Arduino shields, please read my question again. But thanks for trying to be helpful.

No probs, but upon reading your question again, to me it doesn't make sense. I am not clear on what you're asking, John!

Thanks for the comment. The shield I'm talking about here is the shield of the USB socket (a metallic cover surrounds the female USB connector) which I'm going to use at the 5v power supply side (as its output socket).

Aha, I think what caused the confusion is the use of the word 'shield'.  You're probably aware that 'shields', in the Arduino sense, are accompanying boards that sometimes fit atop the Arduino and provide additional functionality.

Read My First Comment!

I did. It was confusing. No need to be rude!


text:
basic_insert with WAMP server doesn't connect with MySQL database
I'm trying to establish a connection with a MySQL database on a local server wirelessly using the following script:
The wireless connection with my router is successful but then connection with database results in
I'm using a WeMos D1 mini ESP8266, Windows 10, WAMP64, MySQL 5.7.14.
I get ping responses from MySQL at 127.0.0.1, and my host computer and also the ESP8266.  I've disabled my Windows Firewall to test it temporarily.  After the wifi connects with the ESP8266 and confirms the correct WiFi.localIP, 'Connection failed' error with additional text below.
I can manually enter data into the test_arduino table so I think it's a connection issue with the database server. Maybe something to do with my router's handling of of Port 80.
I am able to send sensor data to remote sites such as ThingSpeak.
Any help would be appreciated.
// Created by: Dr. Charles A. Bell

#include "ESP8266WiFi.h"
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

IPAddress server_addr(192,168,0,10);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password[] = "PASSWORD";        // MySQL user login password

const char* SSID = "MYSSID";         // Your network SSID
const char* PASS = "MYPASSWORD";

// Sample query
char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";

WiFiClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect

  Serial.print("Connecting to "+*SSID);
  WiFi.begin(SSID, PASS);
  Serial.println("going into wl connect");

  while (WiFi.status() != WL_CONNECTED) //not connected,  ...waiting to connect
    {
      delay(1000);
      Serial.print(".");
    }

  Serial.println("wl connected");
  Serial.println("");
  Serial.println("Credentials accepted! Connected to wifi\n ");
  Serial.println(WiFi.localIP());
  Serial.println("");

  if (conn.connect(server_addr, 3306, user, password)) {
    delay(1000);
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
  delay(2000);

  Serial.println("Recording data.");

  // Initiate the query class instance
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
  // Execute the query
  cur_mem->execute(INSERT_SQL);
  // Note: since there are no results, we do not need to read any data
  // Deleting the cursor also frees up memory used
  delete cur_mem;
}

The following is the Serial COM4 readout:
Connected to wifi
 going into wl connect
.......wl connected

Credentials accepted! Connected to wifi

192.168.1.XX (intentionally deleted)

Connection failed.
Recording data.

Exception (3):
epc1=0x402050ea epc2=0x00000000 epc3=0x00000000 excvaddr=0x402315cc depc=0x00000000

ctx: cont
sp: 3ffef5a0 end: 3ffef7d0 offset: 01a0

>>>stack>>>
3ffef740:  0a00a8c0 00000001 3ffe8785 402050f4
3ffef750:  3ffee524 0000000e 3ffe850e 3ffee79c
3ffef760:  3fffdad0 00000000 3ffee770 402048fd
3ffef770:  402315cc 00000000 3ffee770 3ffee79c
3ffef780:  3fffdad0 00000000 3ffee770 40204945
3ffef790:  402010ae 00000000 3fff061c 4020292e
3ffef7a0:  3ffe8780 00000000 3fff061c 40201d3e
3ffef7b0:  3fffdad0 00000000 3ffee794 40204c34
3ffef7c0:  feefeffe feefeffe 3ffee7b0 40100718
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld

It looks like you haven't finished part of your question: "The wireless connection with my router is successful but then connection with database results in...."

I figured it out.  I needed to set up a User (IP  server) in the database.
In phpMyAdmin I created a new user (esp) and set the Host name to the IP address of the ESP8266.  In the sketch I changed the user from "root" to "esp".

Please expand upon your answer. Your answer may prove to be useful to someone else, who has the same issue, but with less understanding of how to solve it.

Please accept your answer once you have edited/expanded on it.


text:
Move a servo slowly between 2 positions based on input
I am trying to move model railroad crossing gates from a vertical position to a horizontal position when a train is detected. I have the electronics in for the sensing of train position but want the gates to go down and stay down while the train passed.
To do this, I am looking to be able to use an Arduino to slowly move a servo between two different positions based on a digital input (HIGH or LOW) to one of the digital input pins.
When this digital input goes HIGH, the servo needs to slowly move to the other end of travel and then stop. It must stay there until the digital input goes LOW, at which time it needs to slowly move back to the starting position and again await for a HIGH input.
I cannot figure out how to move the servo slowly to each position and keep it there.

You may want something like this: https://www.coolcomponents.co.uk/en/sparkfun-servo-trigger.html . Notice that their firmware is licensed CC-BY-SA.

Welcome to Arduino SE.  Be sure to take the tour at https://arduino.stackexchange.com/Tour

Lacking information about the context of the servo action (ie, what needs to happen at the same time), I'll assume your paradigm uses a loop() function that executes fairly rapidly, and from time to time invokes any necessary actions.
Servo angles can be measured in degrees (typically 0 to 180) or microseconds (typically 1000 to 2000, corresponding to 0° to 180°).  The servo library will accept numbers in either range, and act according to which range the numbers are in.  Note that representing servo angles in microseconds instead of degrees gives about 5.55 times better resolution.  The method outlined below doesn't care which you use.
Also assume the two servo angles mentioned in the question are A and B, with the servo at A if the input pin is low for a long time; and that the desired rate of swing is ±U units of angle every S milliseconds.  Let P = current servo position; T = millis() value at most recent step, initially 0; and V = previous value of input pin.
In each pass through loop():
• Test the input pin.  If it isn't equal to V, toggle V and take a step.  (See below.).
• If  millis()-T > S, take a step.  (See below.)
• Do any other brief per-loop actions
To take a step:
• Add (2*(V>0)-1) * U to P.  The expression (V>0) equals 1 or 0, so (2*(V>0)-1) is 1 if V is true, and -1 if V is false.
• If (V) and P > B, set P = B
• If (!V) and P < A, set P = A
• Servo to position P
• Set T = millis()
Edit: You should create meaningful variable or constant names to represent the quantities A, B, P, S, T, U, V.  Note that S and T should be declared as constants; and if A, B won't change, make them constants also.  State-maintaining quantities P and T should be declared via file-scope variables or globals (outside loop()) or with static allocation (inside loop()), so that their values are maintained as main() repeatedly calls loop().

Thank you for your help.  It should get me going on the project.  I am trying to move model railroad crossing gates from a vertical position to a horizontal position when a train is detected.  I have the electronics in for the sensing of train position but wanted the gates to go down and stay down while the train passed.

I see how you are incrementally increasing or decreasing the servo position without going beyond the boundaries of the preset servo positions.  I am not sure, however, how to get the servo to stay in the assigned positions since the variables are reinitialized each time it goes through the loop.  Are some of these static variables?  Sorry if stupid questions.  New to Arduino programming.

@BobPerry, see edit.  Note, please upvote or accept answer if useful.

Thanks.  Setting up the variables as static didi the trick!


text:
If an I2C connection is lost for a short period of time will it work if the connection is live again?
I'm using an ESP8266 with the Arduino library to read from a sensor(MPU9250 specifically). The readings are done via I2C but I'm using a library that abstracts these methods.
The wires are not soldered together so temporary disconnections are possible and after these disconnects the sensor readings freeze. I'm new to the world of I2C so my questions are:

Do I have to re-init the connection after it disconnects or is there a way to continue on re-connection immediately?
Is there a way to prevent this to happen (for example to stop reading when there's no connection) or should I just solder together the pins?

When an I2C master starts a transmission or a request from a slave, it sends the slaves address and then check for an acknowledgement (ACK) from the slave (SDA LOW, when the clock has a HIGH pulse). When no slave is connected, or there is no slave with this address, then there isn't any circuit to pull SDA to LOW on the clock pulse, that is generated by the master. This is interpreted as No acknowledgement (NACK) and the transmission/request fails and should exit. So a disconnection between the transmission should not freeze your code (though I don't know what your library is doing exactly).
A quick google search gives me, that the esp8266 does not have hardware I2C, so your library does a pure software I2C. There are many pitfalls, which can block the I2C bus (especially, if one the lines is hold LOW by one of the involving circuits). Your library may or may not implement the correct I2C protocoll.
So to clearly answer your questions:

You don't have to reinit connection. Your master transmission fails, if there is no slave, and should give you an error as return value. But be sure, that there isn't happening anything on the SDA or SCL lines, when it starts up again after reconnection. Master or slave can interpret voltage spikes as signal.
If the library is implemented correctly, it will exit, when there is no ACK from the slave.

Look into the documentation of your library how it handles these events. And check the state of SDA and SCL, when a block occures. You can refer to this site for further information about I2C. It also gives some advice if your bus is blocked.


text:
Arduino nano 33 ble vs ble sense. Power consumption, etc
After working with an Arduino Uno at work, I am looking to buy myself a board for some projects/experiments at home. The nano size seems like a great option, especially the one without soldered headers, as it is very flexible and easy to fit in projects with limited space. More specifically, I am interested in nano 33 ble and nano 33 ble sense.
My question is, apart from price does anyone know of any other disadvantages the sense board might have on comparison to the 33 ble?
Does it consume more power if the sensors are not used in a projects (just from being integrated in the board’s circuit)?
Also, does the light intensity sensor work like an LDR (photoresistor)? E.g. will I be able to do things like turn on LEDs automatically when it is dark, based on the sensor’s readings?

The official page for the Nano 33 BLE Sense mentions various things including the datasheet for the light sensor. That appears to be much more sophisticated than an LDR.
According to the sensor documentation (above):

Upon  power-up,  POR,  the  device  initializes  and  immedi-ately enters the low power SLEEP state. In this operational state  the  internal  oscillator  and  other  circuitry  are  not  active,  resulting  in  ultra-low  power  consumption.

You would have to read the documentation for the other devices to check these things. Personally I haven't used one, and Arduino claim it "is a completely new board". So, you may not find a lot of people that can answer those questions.
Keeping power consumption low is quite a complex field. You need to look at clock speeds, sleep states, peripheral power consumption and so on.


text:
Using Arduino to allow continuous servo to go in the opposite direction
For my project I am using 6 continuous servos connected to an Adafruit Servo Shield. To run them I use
pwm.setPWM(0, 0, 1000)
and then set a delay to run them for how long i’d like to, then run
pwm.setPWM(0, 0, 0)
to stop it.
I would like to run the servo in the opposite direction. How would I do this?

You probably already know that continuous servos are different to other hobbyist servos in that they rotate freely, and the PWM signal is used to control speed and direction of rotation.
The specific model of servo you're using is important and you'll need to refer to the datasheet to find out its details. Particulalry the servo's minimum (typically clockwise rotation); mid-point (neutral / no rotation); maximim (usually counter clockwise rotation) PWM pulsewidths. The mid-point is often set by a PWM pulsewidth of 1500 microseconds, but this can vary and it pays to check.
The library you referenced does implement a setPWM() function as you mentioned, however you'll note that it works in a range of ticks from 0 to 4095. The two parameter values set when to turn the PWM pulse on and off expressed as values from 0 to 4095. To use this function you'll need to map these parameters to produce the PWM signal the servo is expecting.
I recommend an alternative, using the writeMicroseconds() function of the same library, which accepts a value in microseconds for which the PWM signal will be high. You'll be able to obtain these directly from the datasheet.
In your question you mention using a PWM of approximately 25% duty cycle (1000/4095) for ON. This is likely much longer than the desired maximum for your servo which if it is 2000 microseconds, might need a value something like 430 (/4095). Similarly you mentioned a zero pulse to achieve a stop. I think this library uses zero as a special case for no PWM pulse. You said this generates a stop condition for your servos, but finding the neutral value may be better.
Rather than figuring out the maths for setPWM() to turn on and off the PWM pulse, the writeMicroseconds() function may be easier.
You'll need to check datasheets for your servos but a value of 1500 microseconds should be near neutral / no rotation. Decreasing values less than this should generate increasing speed clockwise. Increasing values greater than neutral should generate increasing speed counter clockwise.


text:
Problem displaying data sent from Arduino Mega to Arduino Mrk1000 using serial communications
I've been doing a personal project.
The idea of the bigger project is to feed my fish using a robot.
My specific problem is that I would like to see some data from the various sensors that I will be adding. But at the moment I am wanting to be able to use serial communication between my 2 boards to transfer an integer from  my Mega board to my MKR1000 board, and then for my MKR1000 to connect to the WIFI where I can see the information on my phone from the IP address.
Below is the 2 pieces of code, first being for the Mega board, where intergers are turned into strings and then sent the Mrk1000.
The sencond piece of code is for the MKR1000. Main goal is to recieve the data from the Mega board and then diaplayed on the client (over WIFI).
FOR MEGA BAORD ------------------------------------------------------------------------------------------
            char str[4];
            char str1[4];
            char str2[4];
            char str3[4];
            char str4[4];

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

            void loop() {
              int value= 500; //this would be much more exciting if it was a sensor value
              int value1= 400;
              int value2= 300;
              int value3= 200;
              int value4= 100;

              itoa(value, str, 10); //Turn value into a character array
              itoa(value1, str1, 10);
              itoa(value2, str2, 10);
              itoa(value3, str3, 10);
              itoa(value4, str4, 10);
              Serial.write(str, 4);
              delay(10);
                Serial.write(str1, 4);
                delay(10);
                  Serial.write(str2, 4);
                  delay(10);
                    Serial.write(str3, 4);
                    delay(10);
                      Serial.write(str4, 4);
                      delay(10);

            }

FOR MRK1000 -----------------------------------------------------------------------------------------
            #include <SPI.h>
            #include <WiFi101.h>
            #include <stdio.h>
            #include <math.h>

            //#include "arduino_secrets.h"
            ///////please enter your sensitive data in the Secret tab/arduino_secrets.h
            char ssid[] = "";//SECRET_SSID;        // your network SSID (name)
            char pass[] ="";// SECRET_PASS;    // your network password (use for WPA,
            or use as key for WEP)
            int keyIndex = 0;                 // your network key Index number (needed only for WEP)

            char str[4];
            char str1[4];

            int status = WL_IDLE_STATUS;
            WiFiServer server(80);

            void setup() {
              Serial.begin(9600);      // initialize serial communication
              pinMode(6, OUTPUT);      // set the LED pin mode
              Serial1.begin(9600);

              // check for the presence of the shield:
              if (WiFi.status() == WL_NO_SHIELD) {
                Serial.println("WiFi shield not present");
                while (true);       // don't continue
              }

              // attempt to connect to WiFi network:
              while ( status != WL_CONNECTED) {
                Serial.print("Attempting to connect to Network named: ");
                Serial.println(ssid);                   // print the network name (SSID);

                // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
                status = WiFi.begin(ssid, pass);
                // wait 10 seconds for connection:
                delay(10000);
              }
              server.begin();                           // start the web server on port 80
            printWiFiStatus();                        // you're connected now, so print out the status
            }

            int x = 0;       int i = 0;
            void loop() {
              WiFiClient client = server.available();   // listen for incoming clients

              if (client) {                             // if you get a client,
                Serial.println("new client");           // print a message out the serial port
                String currentLine = "";                // make a String to hold incoming data from the client
                while (client.connected()) {            // loop while the client's connected
                  if (client.available()) {             // if there's bytes to read from the client,
                    char c = client.read();             // read a byte, then
                    Serial.write(c);                    // print it out the serial monitor
                    if (c == '\n') {                    // if the byte is a newline character

                        if (Serial1.available()) {
                            delay(100); //allows all serial sent to be received together
                            while(Serial1.available() && i<4) {
                              str[i++] = Serial1.read();
                            }
                          str[i++]='\0';
                        }

                      // if the current line is blank, you got two newline characters in a row.
                      // that's the end of the client HTTP request, so send a response:
                      if (currentLine.length() == 0) {
                        // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
                        // and a content-type so the client knows what's coming, then a blank line:
                        client.println("HTTP/1.1 200 OK");
                        client.println("Content-type:text/html");

                              //strcpy(str, "98993489");
                          int val = atoi(str);
                            //Serial.println(str,4);
                            client.print("str = ");
                            client.print(x);

                        client.println();
                        client.print(x);
                         client.println("
");

                        // the content of the HTTP response follows the header:
                        client.print("Click here turn the LED on pin 9 on
");
                        client.print("Click here turn the LED on pin 9 off
");

                        // The HTTP response ends with another blank line:
                        client.println();
                        // break out of the while loop:
                        break;
                      }
                      else {      // if you got a newline, then clear currentLine:
                        currentLine = "";
                      }
                    }
                    else if (c != '\r') {    // if you got anything else but a carriage return character,
                      currentLine += c;      // add it to the end of the currentLine
                    }

                    // Check to see if the client request was "GET /H" or "GET /L":
                    if (currentLine.endsWith("GET /H")) {
                      Serial.println("high");
                      digitalWrite(9, HIGH);               // GET /H turns the LED on

                      }
                    if (currentLine.endsWith("GET /L")) {
                      Serial.println("low");
                      digitalWrite(9, LOW);                // GET /L turns the LED off

                    }
                  }
                }
                // close the connection:
                client.stop();
                Serial.println("client disonnected");
                x++;
              }
            }

            void printWiFiStatus() {
              // print the SSID of the network you're attached to:
              Serial.print("SSID: ");
              Serial.println(WiFi.SSID());

              // print your WiFi shield's IP address:
              IPAddress ip = WiFi.localIP();
              Serial.print("IP Address: ");
              Serial.println(ip);

              // print the received signal strength:
              long rssi = WiFi.RSSI();
              Serial.print("signal strength (RSSI):");
              Serial.print(rssi);
              Serial.println(" dBm");
              // print where to go in a browser:
              Serial.print("To see this page in action, open a browser to http://");
              Serial.println(ip);
            }

And where exactly is your problem? With displaying over Wifi (on a Website hosted on the MRK?)? Or with the Serial communication?

with trying to display over wifi.

You're going about your sending all wrong. You don't need to convert anything. Just use Serial.println(val1); etc,  then read your serial up until the terminating \n.

3 MCU for this? ATmega2560, SAMD21 and ESP32?


text:
i am not able to figure out the problem due to which i can't upload my sketch to nano
this is the error code (it is new from the previous time i posted)
i am using the hourly build for this and not the Beta
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x6e

this is the info of the loader and board i am using

the code has no problems but idk what is avrdude

Looks like your installation is incomplete. Make sure your core is up to date in the boards manager. Try reinstalling the core.

it is up to date i even checked it even the conf file it there but it shows can't open config file and then path name then shows no such directory or file

Them maybe you have a permissions problem. Are you using the app store version on Windows 10 s?

yes i am using the store version

Don't. It's broken. Download the version form the Arduino website.

k thx for the solution

Uninstall the IDE. Delete all the support files. Download the IDE. Update the core.

Another idea - try using Windows Filemanager to navigate down through the folder path shown in the error message and see if the avrdude.conf file exists in the specified place. this probably will not solve your problem but it might help to understand what is happening. Good luck - Bob

I am just taking a guess as I operate on Linux. I would suggest go to tools menu and see if the correct board is selected. I would venture to guess it is not set for nano. Mine gives me two choices new and old. Try one and if it does not work try the other. Be sure your Baud is set correctly.