text:
powering Nodemcu using Vin
Forgive me for this really dumb question. I am an amateur in electronics, and im trying to wrap up my head around this question and im not able to do so. Need your help.
Im trying to power up a nodemcu using a 5v 1A power supply- I connected +ve to Vin and ground to ground. But i see that 5v is not enough to power up the nodemcu. So i removed the 5V and connected to a 9V battery, and again I find the same issue- the power is not enough. Knowing that i did something wrong - i measured the voltage across Vin and ground and find it to be around 2.5V when using the 5v source and around 2.5V when using the 9 V battery too.
Confused and thinking that my nodemcu is corrupted, i ordered a new one, and did the same. But i find that when i try to supply power using Vin, the voltage across the device- Vin and ground is around 2.5V for the newer device also. Obviously Im missing something.
Can anyone tell me what is it that Im doing wrong. Please tell me how to power a nodemcu without using a usb and only using a 5v source.

9V -> Arduino -> VIN -> NodeMCU 5V = dead NodeMCU.

No. the NodeMCU works on USB power still. Its not dead.

Then you're lucky that a 9V battery is one of the weakest batteries around, otherwise it would have killed the NodeMCU.  It's the current you need to consider. The voltage is 5V and must always be 5V. If it seems "too weak", increasing the voltage is a very very bad idea.

The 5v power supply is 1A. So with that too, the NodeMCU doesnt work. Am I missing something here? Please help me.

Did you connect the 5v to the Arduino barrel jack or the USB?

I took a USB charger - 5v 1A and connected its positive to Vin of NodeMCU. I am not using any arduino here.

Which NodeMCU version?

second generation.

What does that mean? NodeMCUs have a version number, not a "generation". What version number is printed on your NodeMCU?

Im sorry. Its V2. I did a google search and found that V2 was called second generation at this blog https://frightanic.com/iot/comparison-of-esp8266-nodemcu-development-boards/.

Ok, that makes more sense - since the earlier boards don't have a VIN pin, they have a 5V pin.

So... you connected the 5V power supply's positive to VIN. Did you connect the power supply's ground to GND?

Yeah, i made the connection as you said sir. 5v to Vin and ground to GND.

why you simple do not google it http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/

I referred it long ago. And followed instructions from there only.

there are different manufacturers

Yeah sir. However, if i follow the connections as outlined in the blog, i think it must work right? But it doesnt work for me? Is there something that i am missing here?

fwiw, i have no trouble doing this with CP2102-based nodeMCUs (amica), but I've never gotten it to work with the larger CH340G lolin boards, which also don't give you 5v out when plugged into USB; useless. Your best bet for those is to get a cheap LDO module (or smps) and power it from any of the 3.3v pins.

Im struggling with the same problem, did you finally manage to fix it? Thanks, Pablo

I have a NodeMCU Esp8266 v3 (Lolin) and it works fine conecting Vin and G to my cell phone power supply rated 5.1V, 1000mA. This develop board has a aprotective diode (the closest to Vin), if you have a Multimeter o multitester you can check it measurement continuity. If your diode is damaged the power applied to Vin never be enough to power up the nodemcu.


text:
for loop running infinitely
void writereg() {
  digitalWrite(latchPin, LOW);
  for (int i = 7; i >= 0; i--) {
    digitalWrite(clockPin, LOW);
    Serial.print("wswitch&&&&&&");
    Serial.print(i);
    Serial.print("----------------------");
    digitalWrite(dataPin, switches[i].stat);
    Serial.println(switches[i].stat);
    digitalWrite(clockPin, HIGH);
  }
  digitalWrite(latchPin, HIGH);
  touched = false;
}

I don't understand what's wrong with what I'm doing here, but this for loop runs into an almost infinite loop and prints crazily. I'm a newbie to electronics and Arduino and I don't understand what's wrong here. Please help.
This is my switch class:
struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

From the output, it looks like i is not an int but a byte (or unsigned char  or uint8_t). In this case, what you observe is normal because an unsigned is always positive, hence the loop never ends. Are you sure the output posted here matches the code in your question?

Yes. Its the same code that produces this output. i is an int only and not a byte.

Could you show how switches was declared (and details of the underlying type)?

i have edited the question. Please see and let me know if it can solve the issue im facing.

Thanks, unfortunately, that did not show any potential issue of memory overwriting (which is what I thought of when I asked you to add this code). Sorry to insist, but I am really surprised that i is an int. Just in case, do you have special compilation options?

As a test, could you replace your loop with for (int i = 0; i <= 7; i++) and inside the loop body, replace i everywhere with 7 - i ? That would not explain the behavior you get, but that should fix your problem.

Im not sure about this. I was not facing this issue when I was working with Arduino Uno. I have compiled this code to a Atmega328p now and this causes the issue. The code was working properly in Uno.

Let us continue this discussion in chat.

After a chat with OP, it turned out this was a more complex issue, probably a memory overrun.
This cannot be seen in this small snippet, but the whole program is using memory extensively (global variables and dynamic memory heap allocation).
Heavy use of String variables is a likely explanation for the observed behavior.
Also a lot of string literals are putting more pressure on memory in the OP program.
Here are my suggestions:

Replace all "..." string literals with flash-stored strings with F("..."). That will reduce the initial SRAM size used.
Replace all String variables with pure C-string (char* and char arrays) and use standard C string functions such as strcpy, strcat, strlen, strcmp, strchr... This forces to pre-allocate string to their maximum size, but this can be controlled at compile-time (for string variables defined as global). For this point, I also suggest to read a good tutorial on strings in C language.
Use const whenever possible (instead of variables that waste memory)
Use the smallest type needed for each variable, e.g. avoid int (2 bytes) when you need to store a boolean value, prefer bool type (only one byte) or even use 1 byte to store 8 boolean values and use boolean logic to manipulate each value.

Thanks and i would make all the changes that you suggested. Thanks a lot!

Like jfpoilpret said, it looks like i is being treated as an unsigned char or uint8_t causing it to never go below zero. Instead it wraps around to 255, the max value of an 8-bit unsigned integer, as you can see in line 9 of your output. The condition to remain in the loop is i >= 0 which means the loop will never exit. A solution is to add a case for if i is above the starting value:
for (int i = 7; i >= 0 && i <= 7; i--) {

I would recommend finding out why int is being treated as uint8_t for any future projects

I tried this too. But it didnt work.

I have noticed that you have incorrectly declared the switches array.
Your code:
struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

It should be:
struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

struct Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

Alternatively, you could make a typedef struct:
typedef struct
{
  int num;
  bool stat;
  bool touched;
}Swtch;

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

References:
https://stackoverflow.com/a/32185804/6075112
https://overiq.com/c-programming/101/array-of-structures-in-c/#initializing-array-of-structures
https://stackoverflow.com/a/3275389/6075112

This would be true for C,  not for C++, and I do not know in what language the code in the question is.

The Arduino development tools by default use C++.

Isn't the typedef the best practice?

@sa_leinad: No. In C++, it's generally considered quite ugly, as there's no good reason for it. (C++ lets you treat user-defined type names like built-in type names in nearly all cases.)

Thanks all for your comments. I have learnt something today!

source: Stack Exchange

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

sort: votes


text:
Two HC05 Bluetooth Bind problem
I succeeded in giving an AT command. My two BL MAC addresses are 21, 13, A03B and 21, 13, A3E2.
When I want to connect one to the other I use AT+BIND=21,13,A3E2. But then I see Error(7). If I use another BL address from the Internet, it works.
So, why won't my 2 HC05 bind?

The solution is
AT+BIND=0021,13,00A03B

NB: Here I just added 00 left side and right side digits

I think that this is an error caused by a difference of firmware versions. Now BT is on version 3.0-20170601 and I think that this version does not accept these link or bind commands.

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


text:
CC3000 gets wrong address when connecting to wireless AP
I tried using both the SparkFun and Adafruit CC3000 libraries first with what I actually wanted as a program, but when that didn't work, the examples for those libraries, and I always seem to get the same problem.
The CC3000 will connect to my AP, which uses a private address in the range 172.24.1.1/24, and somehow it will end up with the address 192.168.1.64.
I know that it is connecting, since iw event lists the device MAC address as it connects.
The only changes I have made to the source code at this point are the ssid and password, and changing the interrupt and vbat pins to match the configuration of the tinyduino cc3000 board.
The device has firmware 1.34. Here is the code.
The specific output I get from the arduino is as follows (Note I commented out the disconnect at the bottom):
Connected at 115200

---------------------------------
SparkFun CC3000 - Connection Test
---------------------------------
CC3000 initialization complete
Connecting to: my_wifi_ap
Connected!

CC3000 MAC Address: 70:FF:76:04:B9:5B
IP Address: 192.168.1.62
Subnet Mask: 255.255.255.0
Default Gateway: 192.168.1.254
DHCP Server: 0.0.0.0
DNS Server: 192.168.1.254
SSID: my_wifi_ap

Finished connection test

running iw event -f on my AP before running a connection test gives me the following output:
wlan0: new station 70:ff:76:04:b9:5b

When another device, like my phone, connects to this AP, we get 172.24.1.xx, where xx is whatever number between 50 and 150 that DHCP assigns us.
Edit:
Also, if I comment out the disconnect at the end of the test, I can see the device is sending keepalives every three or four seconds using:
iw dev wlan0 station get 70:ff:76:04:b9:5b  //(inactive time never exceeds 4000ms).

I can't ping 192.168.1.64 because that network is obviously unreachable, but trying to ping 172.24.1.64 gives me a exception:
icmp open socket: Operation not permitted

Output from Adafruit Example:
RX Buffer : 131 bytes
TX Buffer : 131 bytes
Free RAM: 1221

Initialising the CC3000 ...
Firmware V. : 1.32
MAC Address : 0x70 0xFF 0x76 0x04 0xB9 0x5B
Started AP/SSID scan

Networks found: 20
================================================

...

SSID Name    : my_wifi_ap
RSSI         : 83
Security Mode: 3

SSID Name    : my_other_wifi_ap
RSSI         : 67
Security Mode: 3

...

================================================

Deleting old connection profiles

Attempting to connect to my_wifi_ap
Started AP/SSID scan

Connecting to my_wifi_ap...Waiting to connect...Connected!
Request DHCP

IP Addr: 192.168.1.62
Netmask: 255.255.255.0
Gateway: 192.168.1.254

The actual device being connected to is a Raspberry Pi AP, which was set up with DNSMASQ and hostapd. The configuration works, and has been proven to work with other embedded networking devices.

What device is your AP? Can you query it for the IP address of the new station? Can you post the output from the Adafruit example?

I'm voting to close this question as off-topic because it is about CC3000 firmware versions and not about Arduino.  Additionally the poster has long abandoned the question without accepting even their own apparent solution and and has not logged in for over a year, meaning that this off-topic question is likely to remain permanently derelict.

I realized that I was using firmware v 1.34 on the board, which is what it was configured with when I got it, and decided I would try to downgrade it to one of the fir;ware sets supplied by adafruit to see if that would work.
The firmware modifying program didn't actually compile on the desktop version of the arduino ide, so I decided to use codebender instead.
I'm not sure whether or not I should be disappointed or relieved, but downgrading the firmware actually made it work. I used the file titled driverpath_1_11, which I believe the libraries refer to as firmware version 0x113 or 0x118, which identifies itself as firmware version 1.24, which somehow actually worked.
The solution is here: https://codebender.cc/sketch:318229
The pins have been changed to correspond with the fixed pings used by the tinyduino.

Please accept either your answer or the other so that the question shows as resolved and does not keep getting churned up for attention.

Welcome to the wonderful world of Adafruit software. Some genius decided that the CC3000 should save the first address it is ever given to nonvolatile storage, and use that ever since no matter what DHCP may subsequently tell it. Check the library source.

I solved it by downgrading the firmware to one that was suggested for use with the adafruit library, but that actually seems like an equally plausible reason as to why it wasn't working. Not sure why the Sparkfun library also failed to work, too, but that one is pretty clearly a WIP.

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

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


text:
Raspberry Pi with Arduino, Serial connection stops working
This is the hardware set-up at home,
Raspberry Pi GPIO -> Logic Level Converter -> Arduino -> Multiple Relays

I am running Raspbian and NodeJS on the Pi while the Arduino is loaded with StandardFirmata.
I connect NodeJS to the Arduino with the johnny-five package and it works well after it's started. But after extended periods, a few hours? The Arduino stops responding. Whatever command that I send to the Arduino won't be acted on. It's as though as the Arduino hung.
Both the Raspberry Pi and Arduino are being powered indenpendently with a 1A Nokia USB Adapter.
Does anyone know why this is happening?

johnny-five
StandardFirmata
NodeJS Server Code

Also, please add links to all the products you are using. I don't know what "Johnny-Five" is aside from a robot from an 80s movie. Same with "StandardFirmata".

Also, the details on the RPi code, as well as (ideally) pictures of how you have everything hooked up.

You might want to consider posting your code, otherwise every answer here will be a guess at best

Very often, if Arduino hangs, this is a memory problem (typically collision between the heap and the stack). It's gonna be hard to diagnose the actual issue without the source code of the program you downloaded to Arduino!

Hav you check that your Arduino still works properly with usual programs (blink in particular). You first need to find out if it is a hardware issue (pin or MCU fried due to too much current switched through the relays) or software.

Added links to all the software I am using and my NodeJS Server code. Will take pictures of the set-up in a bit.

@jfpoilpret added in connection. I'm sure the Uno is fine as I can just restart the uno and it starts working again. It's just that I'm trying to use it as a 24/7 solution

You have drawn a relay coild directly connected to pin 13, which is a very bad idea.  Use an NPN transistor to drive the relay, and give it a catch diode.

I've had a lot of serial hanging issues with my Arduino and Pi3. There seems to be a lot of issues with USB serial interfaces on the Pi. I've also noticed that my Pi seems to connect to the Arduino just fine after a reboot, but if I disconnect and then reconnect the Arduino (which should be fine), then it's able to connect initially, but the connect hangs after a few minutes.

A "1A" means 1 amp? I know the RPi 3 doesn't run reliably with less than 2.5 amps supplied by itself. Is it possible your power supply is overheating and dropping voltage?

@wilsotc Probably shouldn't be replying to a 4 year old thread. The Pi 3 didn't exist back in 2014. I was referring to a Original Raspberry Pi. Unless you're replying to Cerin.
Just so anyone finds this issue, I don't think I ever found a fix for it. It might be better now though.

If none of the code is yours, and all code from the Firmata library, then the most possible cause that comes to mind after reviewing the library code is memory leak, which makes the next allocation to fail and by thus breaking the code.
The Firmata library does perform dynamic memory allocation, checkout Firmata.c, so it is realistic - I would suggest to take it with the Library's author.

Yeah. None of the code on the Arduino is mine. It's all Firmata's. So it's probably Firmata?

logically, it must be. Perhaps they didn't take into account running indefinitely.


text:
Arduino Nano 33 BLE - use of flash to store data; how to expand a piece of sample code
I've been looking into how to store data in between restarts.  With an Arduino UNO, there are plenty of EEPROM libraries, but I'm not finding something 'off the rack' for the Arduino Nano 33 BLE.
I did manage to find a well documented example by Pete Warden, who recently put on github (https://github.com/petewarden/arduino_nano_ble_write_flash), and it can be compiled and downloaded, but I'm unclear as to how one would expand on it, to write a simple function that can store and read multiple values (integer, float, string, arrays).
The code is below, I'm a bit rusty on things, but I am thinking that the key is in the part:
  // Treat the first four bytes of the copy of our flash array as a 32-bit
  // integer.
  int32_t* counter_address = reinterpret_cast<int32_t*>(ram_buffer);

How would one add additional variables (and of different lengths) to this code, so you could write and read more than one variable?   Somehow, it would seem a command like:
int32_t* another_variable = [modified version of:] reinterpret_cast<int32_t*>(ram_buffer);

... would do the trick, but I'm not quite sure about how this is done.
   * Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

// This sketch demonstrates how to initialize, read, and update flash memory
// on an Arduino Nano BLE Sense 33. It contains a counter that starts at zero
// when the sketch is first uploaded, and is incremented by one every time that
// the board is reset without a re-flash. You can test this by uploading the
// sketch, opening the serial monitor, and seeing "Counter=0" output initially.
// If you then press the reset button, you should see "Counter=1", and so on as
// the board is restarted.

// This Mbed API lets us access flash memory, so we include the header. See
// https://os.mbed.com/docs/mbed-os/v6.9/apis/flashiapblockdevice.html
#include "FlashIAPBlockDevice.h"

// One of the challenges I had with the existing examples I found of using flash
// was that they didn't demonstrate how to set an initial value for the memory
// when the sketch was first uploaded. This was essential for most use cases,
// for example we want the counter to start at zero so the initial contents need
// to be set when the program is flashed. I would typically try to use linker
// scripts to set aside an area of memory and mark it so it's initialized during
// flashing, but that's not very easy with the Arduino IDE. Instead I use a bit of
// a hack, by:
//  - Declaring an array of bytes as const, so I know it will end up in
//    flash.
//  - Forcing it to align with the block size of the flash, so it can be
//    accessed by the API that works with whole pages of flash.
//  - Adding an empty initializer list ({}) tells the compiler to zero out the
//    contents in the binary that's flashed to the device.
// The last point is a bit subtle, because you might think that doing it in a
// constructor or setup() would work, but that would be called every time the
// program is reset. What I needed was a way to create a binary with that area
// already initialized before upload, which this approach offers.
// Some other examples use hard-coded addresses for the flash, usually towards
// the top of the address space so that they won't clash with the loaded program,
// but this approach does have the advantage that your writable area is dealt with
// in the same way as other variables, so you shouldn't have to worry about
// overwriting anything.

// From experimentation I know that the "page size" or "block size" of the flash
// on the board is 4KB, and should match the reported get_erase_size() from the
// block device object. In theory we should be able to use the
// MBED_CONF_FLASHIAP_BLOCK_DEVICE_SIZE macro, but this seems to be set to zero.

    #include "FlashIAPBlockDevice.h"

    constexpr int kFlashBlockSize = 4096;

        // Your flash area needs to be a multiple of the block size. In this case I want
        // 64KB (even though I'm only using the first four bytes). You should make this
        // the smallest multiple of the block size that will hold your data.
        #define ROUND_UP(val, block_size) ((((val) + ((block_size) - 1)) / (block_size)) * (block_size))
        constexpr int kFlashBufferSize = ROUND_UP(64 * 1024, kFlashBlockSize);

        // As mentioned above, alignas ensures we get a valid block-aligned address,
        // const should make sure it's in flash, and the empty brackets mean the array
        // is filled with zeroes when the program is first uploaded.
        alignas(kFlashBlockSize) const uint8_t flash_buffer[kFlashBufferSize] = {};

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

              // Beware! If you copy and paste this code into your own example, and try
              // running it without the serial monitor attached, this line will hang forever.
              // You'll need to remove this in production (and yes I have been caught by this
              // myself far too often).
              while (!Serial);

              // The address of the array will be determined by the compiler, and we need to
              // grab it as a 32-bit integer to use with the Mbed API.
              const uint32_t flash_buffer_address = reinterpret_cast<uint32_t>(flash_buffer);
              Serial.println(String("flash_buffer_address=0x") + String(flash_buffer_address, 16));

              // Create the flash object we'll be using to access the flash memory.
              static FlashIAPBlockDevice bd(flash_buffer_address, kFlashBufferSize);
              bd.init();

              // We'll need to copy the area of flash to RAM to modify it, so allocate an
              // array of the right size.
              uint8_t* ram_buffer = (uint8_t*)(malloc(kFlashBufferSize));

              // Copy the existing flash contents into our ram buffer.
              bd.read(ram_buffer, 0, kFlashBufferSize);

              // We need to erase the flash area before we can write into it again.
              bd.erase(0, kFlashBufferSize);

              // Treat the first four bytes of the copy of our flash array as a 32-bit
              // integer.
              int32_t* counter_address = reinterpret_cast<int32_t*>(ram_buffer);

              // Print out the value before any changes.
              Serial.println(String("Counter=") + String(*counter_address, 16));

              // Update our RAM copy of the counter integer.
              *counter_address += 1;

              // Write the whole copy of our RAM buffer back into flash.
              bd.program(ram_buffer, 0, kFlashBufferSize);

              // Shut down our flash access object.
              bd.deinit();
            }

put them in the buffer, read them from buffer

OK... but how does one exactly put them in the buffer?   The syntax is what is not understood.  It is understood that if you have a buffer, you can put at certain locations in the buffer - but how is that done?

The flash will be erased everytime you upload a new sketch. Is that what you want?

No; the request is that you be able to add N variables.  In doing this with EEPROM, it involved offsets from a memory location.  What I'm curious about is how you can do this with a bunch of variables of different types.

I can't really help with the source code you found, but here is a simpler solution for your original problem: I wrote a library called NanoBLEFlashPrefs. It allows you to store parameters and preferences persistently between program restarts and even reprogramming.
The Arduino boards mentioned above use a nRF52840 microcontroller from Nordic Semiconductor. This chip features a very simple file system for flash storage. This is used in the library to store and retrieve an arbitrary struct of data of your program.
Please take a look at the GitHub repository of NanoBLEFlashPrefs.

In the new Arduino board setup, I get the message "WARNING: library NanoBLEFlashPrefs claims to run on mbed_nano architecture(s) and may be incompatible with your current board which runs on mbed architecture(s).
"

@asylumax You can safely ignore this if you really use an Arduino Nano 33 BLE. I have seen this as well, but now it is gone. Which version of the IDE and which version of the board support "Arduino Mbed OS Nano Boards" do you use? With version 2.6.1 of that board support and version 1.8.15 of the IDE I don't see this warning any more.

I guess a simple solution would be to stick with the original
pattern and use only one variable... but have this variable be a
container for all the stuff you need:
struct StoredData {
    int32_t some_integer_variable;
    float some_float;
    // etc...
};

Then you can use the same pattern as the original code:
StoredData* my_data = reinterpret_cast<StoredData*>(ram_buffer);

and access the individual variables as my_data->some_integer_variable,
my_data->some_float, etc.

You can also try my FS_Nano33BLE Library with simple-to-use LittleFS / FATFS.
The filesystem access uses normal POSIX APIs or mbed FileSystem APIs

Great library; there doesn't seem to be a 'directory' function to figure out what files exist.  Right now, I'm writing a few wrappers so you can use strings, which some folks might use.

I was able to build the 'directory' command, based on the link you provided, (https://os.mbed.com/docs/mbed-os/v6.10/apis/file-system-apis.html).  Thanks.


text:
How can you turn off the LEDs on a SparkFun AS7265x Spectral Triad (Spectroscopy Sensor)?
I'm a newbie to program an Arduino but I need to turn off a LED from a external Spectroscopy Sensor.
This is the Sensor:

There are three LEDs on this sensor and they're turned on automatically when the Arduino is plugged in. Can someone perhaps explain in general how to address a LED mounted on something like that ?

it communicates over I2C (a.k.a. Wire or TwoWire). find a library, read the doc

@Juraj the leds communicate over i2c? I don't think they can be disabled, at least not via the bus because the IC on the top dorsn't look like a (suitable) uC to me.

void enableBulb(uint8_t device); void setBulbCurrent(uint8_t current, uint8_t device);

https://learn.sparkfun.com/tutorials/spectral-triad-as7265x-hookup-guide/all

Example 2 - Controlling the onboard LEDs

@SimSon, find a library, read the doc. why to guess?

@Juraj you're right. Now after you added a link to the datasheet, I see there are actually 5 leds on that board...

Thanks it worked :)


text:
Thermistor returns correct value on Arduino Nano, completely fails on Arduino Uno Wifi Rev 2?
I am completely baffled. When I wire the thermistor into my Nano, everything reads completely fine. Then when I switch to the Uno Wifi Rev 2, I get negative numbers -40 to -80 when I was reading 24 on the Nano.
Wiring Diagram is:
           Thermistor
           |       |
Gnd---Resistor     Vcc
           |
       A6/A0 (6 for nano, 0 for Uno)

Code is:
#include <thermistor.h>
#define pin A6 //I change this to A0 on the WIfi. This is the only change
float temp;
uint32_t timeout = millis();
THERMISTOR thermistor(pin, //Analog pin
                  9800,    //Nominal res at 25 ºC
                  3559,    //Thermistor's B value
                  10000);  //Value of the resistor
void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(1000);
  temp = thermistor.read();
  Serial.println(temp);
}

@timemage I just linked each boards store page, if thats what you wanted

It was.  There are significant differences between different boards carrying "Nano" and "UNO" in their names.

The Arduino UNO WiFi Rev2 defaults to an internal analog reference of 0.55V where the classic (non-"Every") Nano defaults to the external VCC voltage as a reference, which is usually around 5V, often a little lower because of the diode it uses between USB and "5V".
Either you need to be using the same voltage reference by selecting a common one with analogReference, or you need to use different references and calculate differently (or provide different values to the thermistor library) according to each reference.
If you've been using the VCC on the normal Nano board, you could try analogReference(VDD); on the UNO Wifi Rev 2.  This isn't necessary a great way to do it (probably using internal references would be better), but it is a simple way to get similar results on a UNO Wifi Rev2 without changing more than a single line to set the reference.


text:
Programming ATTiny1614; Unexpected Signature
Trying to program an ATTTYIN1614 with jtag2updi.
https://github.com/ElTangas/jtag2updi

I was able to use this tool to program an ATTINY1626-XFR and ATTINY807-MNR, but I'm getting an error with ATTINY1614-SSFR.
avrdude: Expected signature for ATtiny1614 is 1E 94 22
         Double check chip, or use -F to override this check.

If you want to make the answer follow more from the question, the part of the avrdude output listing that shows the signature that was actual read would be helpful.

@EdHayes3 if you do not indent the URL, then it becomes clickable ... indented lines are formatted as code

I had the wrong ATTiny1614 selected. Needed to select the non-optiboot option.


text:
How can I stop my servo looping when my sensor doesn't detect movement?
I have this project with my Arduino UNO where I want my servo motor SG90 to go full speed to 180 degrees when the PIR sensor sends HIGH value and go slowly back to zero when the value is LOW.
I have this code working where the servo goes full speed back to zero:
#include <Servo.h>

Servo myservo; //creates a servo object
int pos = 0; //variable to store servo position
//amount of time we give the sensor to calibrate(10-60 secs according to the datasheet)
int calibrationTime = 30;
//the time when the sensor outputs a low impulse
long unsigned int lowIn;
//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pir = 12; //digital pin connected to the PIR's output
int pirPos = 13; //connects to the PIR's 5V pin

void setup() {
  myservo.attach(4); //attaches servo to pin 4
  Serial.begin(9600); //begins serial communication
  pinMode(pir, INPUT);
  pinMode(pirPos, OUTPUT);
  digitalWrite(pirPos, HIGH);
  //time for calibration

  Serial.println("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
  }
  Serial.println();
  Serial.println("done");

  //this waits until the PIR's output is low before ending setup
  while (digitalRead(pir) == HIGH) {
    delay(500);
  }

  Serial.print("SENSOR ACTIVE");
}

void loop() {
  if (digitalRead(pir) == HIGH)
    myservo.write(180);              // tell servo to go to position in variable 'pos'
  Serial.print("Motion detected!");

  if (digitalRead(pir) == LOW)
    myservo.write(0);              // tell servo to go to position in variable 'pos'
  Serial.print("Motion ended!");
}

I'd like the servo to go slowly back to zero, so I tried this :
#include <Servo.h>

Servo myservo; //creates a servo object
int pos = 0; //variable to store servo position
//amount of time we give the sensor to calibrate(10-60 secs according to the datasheet)
int calibrationTime = 30;
//the time when the sensor outputs a low impulse
long unsigned int lowIn;
//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pir = 12; //digital pin connected to the PIR's output
int pirPos = 13; //connects to the PIR's 5V pin

void setup() {
  myservo.attach(4); //attaches servo to pin 4
  Serial.begin(9600); //begins serial communication
  pinMode(pir, INPUT);
  pinMode(pirPos, OUTPUT);
  digitalWrite(pirPos, HIGH);

  //time for calibration
  Serial.println("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
  }
  Serial.println();
  Serial.println("done");

  //this waits until the PIR's output is low before ending setup
  while (digitalRead(pir) == HIGH) {
    delay(500);
  }

  Serial.print("SENSOR ACTIVE");
}

void loop() {
  if (digitalRead(pir) == HIGH)
    myservo.write(180);              // tell servo to go to position in variable 'pos'

  Serial.print("Motion detected!");

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

  Serial.print("Motion ended!");
}

The problem is with this code the servo does go slowly back to zero but then goes full speed back to 180 and again and again ....
Any idea? I'm a beginner in Arduino, so I assume it must not be that hard to figure out.
Thanks.

If (digitalRead(pir) == LOW) then you tell the servo to jump to 180 with this line: for (pos = 180; pos >= 0; pos -= 1)

I'd run your code through Tools/Auto Format in the IDE, which is something you should do before posting in the future, for the sanity of your readers, if not for your own.

Okay thanks for the tip guys !!

Don't set the pos to 180 in the (digitalRead(pir) == LOW) branch if you do not want it to repeatedly jump up to 180 for as long as the condition is true.
void loop() {
  if (digitalRead(pir) == HIGH)
     pos = 180;
  myservo.write(pos);              // tell servo to go to position in variable 'pos'

  Serial.print("Motion detected!");

  if (digitalRead(pir) == LOW)
    for (; pos > 0; pos -= 1) { // decay to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }

  Serial.print("Motion ended!");
}

Alternately, you could use pos as a state variable and simplify things:
void loop() {
  if (digitalRead(pir) == HIGH)
     pos = 180;
  elif (pos > 0 ){
     pos--;
     delay(15);
  }
  myservo.write(pos);
}

If pir is LOW, the OP's speed-controlled code will keep cycling between 180 and zero again and again.

"long as the condition is true" or maybe "as long as the input remains LOW".  I'm going to delete my previous comments above (and this one later), because with your good clarifications they're going to look more out of sync.

I pasted the code, works like a charm, thanks a lot to you two guys !!

It sounds like you should "accept" this answer.


text:
I have a problem combining two different sketches into one sketch
Below are two attached the two codes, the second code is for using a microphone to detect for cough and sneezes where the first code is used for humidity and temp.
// For Scanning Insitu Exhale Parameters via nRFConnect or any BLE Service App
// Carbon-dioxide & Volatile OCs have been pseudo-mapped under Pressure & Rainfall respectively(ppm & ppb);)
#include <ArduinoBLE.h>
#include <Wire.h>
#include <SparkFunBME280.h>
#include <SparkFunCCS811.h>
#define CCS811_ADDR 0x5B
#define PIN_NOT_WAKE 5
CCS811 myCCS811(CCS811_ADDR);
BME280 myBME280;

BLEService sensorService("181A");  // Environmental_Sensor-Service
// 180D HeartRate
// 181B BodyComposi.
BLEShortCharacteristic sensorLevelChar1("2A6E", BLERead | BLENotify);   // Temperature-Characteristic
BLEShortCharacteristic sensorLevelChar2("2A6F", BLERead | BLENotify);   // Humidity-Characteristic
BLELongCharacteristic sensorLevelChar3("2A6D", BLERead | BLENotify);    // PCo2-Characteristic
BLELongCharacteristic sensorLevelChar4("2A78", BLERead | BLENotify);    // PTVoC-Characteristic
// 2A37 HRmeasurement
// 2A2C Magdeclination
// 2A98 weight
// 2A6D Pressure
// 2A9D Recom.HRMax.
// 2A8E Height
// 2A8D Max.HR
// 2A8C Gender
// 2A00 DeviceName
// 2A38 bodysensorlocation
int oldSensorLevel1 = 0;
int oldSensorLevel2 = 0;
int oldSensorLevel3 = 0;
int oldSensorLevel4 = 0;
long previousMillis = 0;

void setup() {
  Serial.begin(9600);
  while (!Serial);
  pinMode(23, OUTPUT);

  if (!BLE.begin()) {
    Serial.println("Bluetooth init. failed!");
    while (1);
  }
  Wire.begin();
  CCS811Core::status returnCode = myCCS811.begin();
  Serial.print("CCS811 begin exited with: ");
  printDriverError( returnCode );
  Serial.println();
  myBME280.settings.commInterface = I2C_MODE;
  myBME280.settings.I2CAddress = 0x77;
  myBME280.settings.commInterface = I2C_MODE;
  myBME280.settings.I2CAddress = 0x77;
  myBME280.settings.runMode = 3; //Normal mode
  myBME280.settings.tStandby = 0;
  myBME280.settings.filter = 4;
  myBME280.settings.tempOverSample = 5;
  myBME280.settings.pressOverSample = 5;
  myBME280.settings.humidOverSample = 5;
  delay(10);
  myBME280.begin();

  BLE.setLocalName("Mask.xME");
  BLE.setAdvertisedService(sensorService);
  sensorService.addCharacteristic(sensorLevelChar1);
  BLE.addService(sensorService);
  sensorLevelChar1.writeValue(oldSensorLevel1);

  sensorService.addCharacteristic(sensorLevelChar2);
  BLE.addService(sensorService);
  sensorLevelChar2.writeValue(oldSensorLevel2);

  sensorService.addCharacteristic(sensorLevelChar3);
  BLE.addService(sensorService);
  sensorLevelChar3.writeValue(oldSensorLevel3);

  sensorService.addCharacteristic(sensorLevelChar4);
  BLE.addService(sensorService);
  sensorLevelChar4.writeValue(oldSensorLevel4);

  // start advertising
  BLE.advertise();
  Serial.println("Bluetooth active, waiting to be connected.....");
}

void loop() {
  // waiting for a BLE central device.
  BLEDevice central = BLE.central();
  if (central) {
    Serial.print("Connected to central: ");
    Serial.println(central.address());
    digitalWrite(23, HIGH);  // indicate connection
    while (central.connected()) {
  if (myCCS811.dataAvailable())
  {
    myCCS811.readAlgorithmResults();
    printInfoSerial();
    float BMEtempC = myBME280.readTempC();
    float BMEhumid = myBME280.readFloatHumidity();
    myCCS811.setEnvironmentalData(BMEhumid, BMEtempC);
  }
  else if (myCCS811.checkForStatusError())
  {
    printSensorError();
  }
      long currentMillis = millis();
      if (currentMillis - previousMillis >= 200) {
        previousMillis = currentMillis;
        updateSensorLevel1();
        updateSensorLevel2();
        updateSensorLevel3();
        updateSensorLevel4();
      }
    }
    digitalWrite(23, LOW);
    Serial.print("Disconnected from central: ");
    Serial.println(central.address());
  }
}

void updateSensorLevel1() {
  float temperature = myBME280.readTempC();
  Serial.print("Temperature = ");
  Serial.print(temperature, 0);
  //float T = myBME280.readTempC();
  Serial.println(" °C");
  float sensorLevel1 = map(temperature, 0, 100, 0, 10000);
  sensorLevelChar1.writeValue(sensorLevel1);
  oldSensorLevel1 = sensorLevel1;
}

void updateSensorLevel2() {
  float humidity = myBME280.readFloatHumidity();
  Serial.print("Humidity = ");
  Serial.print(humidity, 0);
  Serial.println(" %");
  float sensorLevel2 = map(humidity, 0, 100, 0, 10000);
  sensorLevelChar2.writeValue(sensorLevel2);
  oldSensorLevel2 = sensorLevel2;
}

void updateSensorLevel3() {
  float CO2 = myCCS811.getCO2();
  Serial.print("Co2 = ");
  Serial.print(CO2);
  Serial.println(" ppm");
  float sensorLevel3 = map(CO2, 0, 100, 0, 1000);
  sensorLevelChar3.writeValue(sensorLevel3);
  oldSensorLevel3 = sensorLevel3;
}

void updateSensorLevel4() {
  float VoC = myCCS811.getTVOC();
  Serial.print("TVoC = ");
  Serial.print(VoC);
  Serial.println(" ppb");
  float sensorLevel4 = map(VoC, 0, 100, 0, 100);
  sensorLevelChar4.writeValue(sensorLevel4);
  oldSensorLevel4 = sensorLevel4;
}

void printInfoSerial()
{
  Serial.println("CCS811 data:");
  Serial.print(" CO2 concentration : ");
  Serial.print(myCCS811.getCO2());
  Serial.println(" ppm");
  Serial.print(" TVOC concentration : ");
  Serial.print(myCCS811.getTVOC());
  Serial.println(" ppb");

  Serial.println("BME280 data:");
  Serial.print(" Temperature: ");
  Serial.print(myBME280.readTempC(), 2);
  Serial.println(" degrees C");
  Serial.print(" %RH: ");
  Serial.print(myBME280.readFloatHumidity(), 2);
  Serial.println(" %");
  Serial.println();
}

void printDriverError( CCS811Core::status errorCode )
{
  switch ( errorCode )
  {
    case CCS811Core::SENSOR_SUCCESS:
      Serial.print("SUCCESS");
      break;
    case CCS811Core::SENSOR_ID_ERROR:
      Serial.print("ID_ERROR");
      break;
    case CCS811Core::SENSOR_I2C_ERROR:
      Serial.print("I2C_ERROR");
      break;
    case CCS811Core::SENSOR_INTERNAL_ERROR:
      Serial.print("INTERNAL_ERROR");
      break;
    case CCS811Core::SENSOR_GENERIC_ERROR:
      Serial.print("GENERIC_ERROR");
      break;
    default:
      Serial.print("Unspecified error.");
  }
}
void printSensorError()
{
  uint8_t error = myCCS811.getErrorRegister();
  if ( error == 0xFF ) //comm error
  {
    Serial.println("Failed to get ERROR_ID register.");
  }
  else
  {
    Serial.print("Error: ");
    if (error & 1 << 5) Serial.print("HeaterSupply");
    if (error & 1 << 4) Serial.print("HeaterFault");
    if (error & 1 << 3) Serial.print("MaxResistance");
    if (error & 1 << 2) Serial.print("MeasModeInvalid");
    if (error & 1 << 1) Serial.print("ReadRegInvalid");
    if (error & 1 << 0) Serial.print("MsgInvalid");
    Serial.println();
  }
}

Code 2
// Cough & Sneeze Classifier built through Edge Impulse Studio.
// If your target is limited in memory remove this macro to save 10K RAM
#define EIDSP_QUANTIZE_FILTERBANK   0
#include <PDM.h>
#include <cscan2_inference.h>

typedef struct {
    int16_t *buffer;
    uint8_t buf_ready;
    uint32_t buf_count;
    uint32_t n_samples;
} inference_t;

static inference_t inference;
static bool record_ready = false;
static signed short sampleBuffer[2048];
static bool debug_nn = false; // Set this to true to see e.g. features generated from the raw signal

/**
 * @brief      Arduino setup function
 */
void setup()
{
    // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.println("SpecVital Inference...");
    // summary of inferencing settings (from model_metadata.h)
    ei_printf("Inferencing settings:\n");
    ei_printf("\tInterval: %.2f ms.\n", (float)EI_CLASSIFIER_INTERVAL_MS);
    ei_printf("\tFrame size: %d\n", EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE);
    ei_printf("\tSample length: %d ms.\n", EI_CLASSIFIER_RAW_SAMPLE_COUNT / 16);
    ei_printf("\tNo. of classes: %d\n", sizeof(ei_classifier_inferencing_categories) / sizeof(ei_classifier_inferencing_categories[0]));
    if (microphone_inference_start(EI_CLASSIFIER_RAW_SAMPLE_COUNT) == false) {
        ei_printf("ERR: Failed to setup audio sampling\r\n");
        return;
    }
}

/**
 * @brief      Arduino main function. Runs the inferencing loop.
 */
void loop()
{
    ei_printf("Starting inferencing in 2 seconds...\n");
    delay(5000);
    ei_printf("Recording...\n");
    bool m = microphone_inference_record();
    if (!m) {
        ei_printf("ERR: Failed to record audio...\n");
        return;
    }
    ei_printf("Recording done\n");

    signal_t signal;
    signal.total_length = EI_CLASSIFIER_RAW_SAMPLE_COUNT;
    signal.get_data = &microphone_audio_signal_get_data;
    ei_impulse_result_t result = { 0 };

    EI_IMPULSE_ERROR r = run_classifier(&signal, &result, debug_nn);
    if (r != EI_IMPULSE_OK) {
        ei_printf("ERR: Failed to run classifier (%d)\n", r);
        return;
    }

    // print the predictions
    ei_printf("Predictions (DSP: %d ms., Classification: %d ms., Anomaly: %d ms.): \n",
        result.timing.dsp, result.timing.classification, result.timing.anomaly);
    for (size_t ix = 0; ix < EI_CLASSIFIER_LABEL_COUNT; ix++) {
        ei_printf("    %s: %.5f\n", result.classification[ix].label, result.classification[ix].value);
    }
#if EI_CLASSIFIER_HAS_ANOMALY == 1
    ei_printf("    anomaly score: %.3f\n", result.anomaly);
#endif
}
/**
 * @brief      Printf function uses vsnprintf and output using Arduino Serial
 *
 * @param[in]  format     Variable argument list
 */
void ei_printf(const char *format, ...) {
    static char print_buf[1024] = { 0 };
    va_list args;
    va_start(args, format);
    int r = vsnprintf(print_buf, sizeof(print_buf), format, args);
    va_end(args);
    if (r > 0) {
        Serial.write(print_buf);
    }
}
/**
 * @brief      PDM buffer full callback
 *             Get data and call audio thread callback
 */
static void pdm_data_ready_inference_callback(void)
{
    int bytesAvailable = PDM.available();
    // read into the sample buffer
    int bytesRead = PDM.read((char *)&sampleBuffer[0], bytesAvailable);
    if (record_ready == true || inference.buf_ready == 1) {
        for(int i = 0; i < bytesRead>>1; i++) {
            inference.buffer[inference.buf_count++] = sampleBuffer[i];
            if(inference.buf_count >= inference.n_samples) {
                inference.buf_count = 0;
                inference.buf_ready = 1;
            }
        }
    }
}
/**
 * @brief      Init inferencing struct and setup/start PDM
 *
 * @param[in]  n_samples  The n samples
 *
 * @return     { description_of_the_return_value }
 */
static bool microphone_inference_start(uint32_t n_samples)
{
    inference.buffer = (int16_t *)malloc(n_samples * sizeof(int16_t));
    if(inference.buffer == NULL) {
        return false;
    }
    inference.buf_count  = 0;
    inference.n_samples  = n_samples;
    inference.buf_ready  = 0;
    // configure the data receive callback
    PDM.onReceive(&pdm_data_ready_inference_callback);
    // optionally set the gain, defaults to 20
    PDM.setGain(80);
    //ei_printf("Sector size: %d nblocks: %d\r\n", ei_nano_fs_get_block_size(), n_sample_blocks);
    PDM.setBufferSize(4096);
    // initialize PDM with:
    // - one channel (mono mode)
    // - a 16 kHz sample rate
    if (!PDM.begin(1, EI_CLASSIFIER_FREQUENCY)) {
        ei_printf("Failed to start PDM!");
    }
    record_ready = true;
    return true;
}
/**
 * @brief      Wait on new data
 *
 * @return     True when finished
 */
static bool microphone_inference_record(void)
{
    inference.buf_ready = 0;
    inference.buf_count = 0;
    while(inference.buf_ready == 0) {
        delay(10);
    }
    return true;
}
/**
 * Get raw audio signal data
 */
static int microphone_audio_signal_get_data(size_t offset, size_t length, float *out_ptr)
{
    arm_q15_to_float(&inference.buffer[offset], out_ptr, length);
    return 0;
}

/**
 * @brief      Stop PDM and release buffers
 */
static void microphone_inference_end(void)
{
    PDM.end();
    free(inference.buffer);
}

#if !defined(EI_CLASSIFIER_SENSOR) || EI_CLASSIFIER_SENSOR != EI_CLASSIFIER_SENSOR_MICROPHONE
#error "Invalid model for current sensor."
#endif

And... what is the "problem" you have with it?

You have 2 different problems you need to solve before you can merge these sketches.
The first sketch has a loop within a loop. in psuedocode it is:
void loop(){
   Connection con = connect();
   while(con.connected()){
       doStuff();
   }
   notify_disconnected();
}

This is a problem because the loop never exits in normal operation.
you can rewrite this into
Connection con;
void loop(){
    if(con.connected()){
        was_connected = true;
        doStuff();
    } else{
        if(was_connected){
            notify_disconnected();
            was_connected = false;
        }
        con = connect();
    }
}

The other sketch has the classic delay problem which the first sketch gives an example of handling.
void loop(){
    delay(5000);
    doStuff();
}

this can be changed into
void loop(){
    long currentMillis = millis();
    if (currentMillis - previousMillis >= 5000) {
        previousMillis = currentMillis;
        doStuff();
    }
}

After you do these fixes and make sure the names of the globals and functions don't collide and no unneeded wires cross you can put both in the same sketch:
void setup(){
    setup_sketch1();
    setup_sketch2();
}

void loop(){
    loop_sketch1();
    loop_sketch2();
}


text:
How to run multiple DC motors in different patterns?
I am a complete novice in programming and I hope someone could guide me here. I am doing a haptic research project, where 8 DC coin vibrating motors would be fitted on the fingers of subjects (excluding thumbs), and the subject has to respond the number of fingers they feel the vibrations on.
Every trial has to have a different pattern of outputs, say: in first trial, 4 motors are activated-motor 1, motor5, motor8 and motor 3. In a single trial, the motors have to have a common delay of 150 ms and 4 seconds break after next one starts.
My question is, that in 8 motors, there are 255 different activation patterns possible. How do I define all these 255 patterns and randomise their sequence?
I am using the mega board and connecting each motor to a PWM pin and all having a common ground.
Here is a sample code with 3 such combinations (only seven motors are connected here):
#define viboutpin 2
#define viboutpin1 3
#define viboutpin2 4
#define viboutpin3 5
#define viboutpin4 6
#define viboutpin5 7
#define viboutpin6 8

void setup() {
     pinMode(viboutpin,OUTPUT);// define a pin as output
     pinMode(viboutpin1,OUTPUT);
     pinMode(viboutpin2,OUTPUT);
     pinMode(viboutpin3,OUTPUT);
     pinMode(viboutpin4,OUTPUT);// define a pin as output
     pinMode(viboutpin5,OUTPUT);
     pinMode(viboutpin6,OUTPUT);
}

void loop() {
    digitalWrite(viboutpin,HIGH);
    digitalWrite(viboutpin1,HIGH);
    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin3,HIGH);
    digitalWrite(viboutpin4,HIGH);
    digitalWrite(viboutpin5,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin, LOW);
    digitalWrite(viboutpin1,LOW);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin3,LOW);
    digitalWrite(viboutpin4,LOW);
    digitalWrite(viboutpin5,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin4,HIGH);
    delay(150);
    digitalWrite(viboutpin4,LOW);
    delay(2000);
}

Why not generate a psuedo random number from 0 to 255 and use it as a code for which motors are to be activated - bit 0 == viboutputpin0, etc.? Then one function can look at each bit in turn and activate that motor if the bit is set, delay, and stop the motors.
You'll probably want to test your code with a few pre-defined test patterns instead of the random ones, and once you're satisfied that it works, randomly seed the random number generator so your project will generate a different pattern each time. One way to do that is to ask via terminal for the operator to click the 'Send' button (or tap the space bar if you're using a separate terminal emulator that sends key by key). Measure the time from the request to the response in microseconds, discard the 2 or 3 least significant bits of the result and keep the next 8. The micros() function's resolution is 4 usec at 16 MHz, is the reason for discarding those 2 lower bits.


text:
Tasks in ESP32: guidelines rather than blink example
I'm using an ESP8266 for IOT devices.
I wish to work with an ESP32 and harvest its benefits - for my uses managing WiFi and MQTT connectivity.
Most tasks examples are very basic and quite the same (blinking LEDs). But for a real time application, more data is needed for which I can't find a guide.
For example:

when to use core0 or core1?
How to evaluate stack size needed for a task?
Are there any limitation for a task? Is a mqtt.loop()  for example, ligit, memory wise?

I'd be happy to read about real life-implementations for tasks (especially "dos" and "don'ts")
Example usage from ESP32 DOCS
 // Dimensions the buffer that the task being created will use as its stack.
 // NOTE:  This is the number of bytes the stack will hold, not the number of
 // words as found in vanilla FreeRTOS.
#define STACK_SIZE 200

 // Structure that will hold the TCB of the task being created.
 StaticTask_t xTaskBuffer;

 // Buffer that the task being created will use as its stack.  Note this is
 // an array of StackType_t variables.  The size of StackType_t is dependent on
 // the RTOS port.
 StackType_t xStack[ STACK_SIZE ];

 // Function that implements the task being created.
 void vTaskCode( void * pvParameters )
 {
     // The parameter value is expected to be 1 as 1 is passed in the
     // pvParameters value in the call to xTaskCreateStatic().
     configASSERT( ( uint32_t ) pvParameters == 1UL );

     for( ;; )
     {
         // Task code goes here.
     }
 }

 // Function that creates a task.
 void vOtherFunction( void )
 {
     TaskHandle_t xHandle = NULL;

     // Create the task without using any dynamic memory allocation.
     xHandle = xTaskCreateStatic(
                   vTaskCode,       // Function that implements the task.
                   "NAME",          // Text name for the task.
                   STACK_SIZE,      // Stack size in bytes, not words.
                   ( void * ) 1,    // Parameter passed into the task.
                   tskIDLE_PRIORITY,// Priority at which the task is created.
                   xStack,          // Array to use as the task's stack.
                   &xTaskBuffer );  // Variable to hold the task's data structure.

     // puxStackBuffer and pxTaskBuffer were not NULL, so the task will have
     // been created, and xHandle will be the task's handle.  Use the handle
     // to suspend the task.
     vTaskSuspend( xHandle );
 }

in a real time application, more data is needed which I can't find a guide for it

That is because there isn't one. The amount of memory needed is completely defined by the application and the task you want to run, so no "guide" can tell you what that will be.
You will have to analyze the actual software you want to run to see what it does and how it works to estimate the likely size of stack needed (note: stack is used for local (non-static) variables as well as storage for registers when calling functions). It's entirely up to you to work it out. The basic assumption (since the SDK is aimed at professional users not hobbyists like typical Arduino users) is that you know what your software is doing since it's you writing that software.

when to use core0 or core1?

When you need to balance your processing load. Again that's entirely down to your software and how you need it to work. Maybe you have one task that has to have almost exclusive use of a core - in which case you bind everything except that task to the same core, and place that task on its own core. Or maybe you just want to spread the tasks out evenly. It's your choice.

Are there any limitation for task?

Yes. The chip only has finite memory. You can't give a task more memory than there is. Also be aware that there may be a watchdog monitoring your tasks so you have to be sure to "kick" it regularly and not block too long.


text:
Converting c string to integer to unsigned char
I'm grappling with types between two different libraries.
The gist is that I'm using the ArduinoWebsockets library to receive information coming from my API that I then want to render out to an LED matrix. An example message would look like this:
1
2
4
8
16
32
64
128

It's important to point out that the data here is a list of string version of numbers, not integers.
I.e. if you look at the binary version of 1 from the list, it's actually 110001 which is the ASCII code for the character 1.
This is because the message coming back from the websocket server is pulled out as a const char *.
The LED matrix function I'm calling has a signature of:
void Write_Max7219(unsigned char address, unsigned char dat)

So I need to send in the values as unsigned chars.
I want to:

parse this information line by line
convert the ASCII character for the number into its integer equivalent
pass the value to a different function to write the data to an LED matrix

I'm not sure how exactly to do this. I've been grappling with the type const char pointer vs regular char pointer and how to properly parse the return delimited string.
Any help would be greatly appreciated!!
Clarification
Based on some of the comments I don't think I explained the reason I'm trying to do this conversion very well. Here's (hopefully) a better explanation:
The reason I want to convert it is because I'm not displaying the number character as a string, I want to use the binary representation to control the lights in a row of the matrix.
The number 1 or 0b00000001 would light up only the rightmost led on the 8 led row of the matrix.
The idea is that I could send over rows of numbers where each row corresponds to the row on the LED matrix.
e.g.
1   -> 0b00000001
2   -> 0b00000010
4   -> 0b00000100
8   -> 0b00001000
16  -> 0b00010000
32  -> 0b00100000
64  -> 0b01000000
128 -> 0b10000000

But the messages I get from the websocket server are coming through as the string representations of the numbers (ASCII or UTF) vs the numbers themselves, so I can't just pass the numbers into the function for the LED matrix because the underlying binary is different.
The conversion is so that I can use the binary representation of 1 (0b00000001) vs the binary representation of '1' ( 00110001).
UPDATE AND RESOLUTION
So I've been on a big troubleshooting journey. When @ocrdu said:

BTW I would try to get the websocket to send the correct single bytes instead of string representations of numbers, if at all possible.

I thought "yeah, that's the real way of fixing it and understanding what's going on", so I started tracing the issue back. Without going into all of the detail it turns out that the problem I was having was actually starting at the test client.
I use firecamp and websocat as websocket client testing tools. I was trying to send the binary data via both tools, but when I dug in via Wireshark I found that the data in flight coming from the client itself was made up of the hex values for the encoded characters of the 1s and 0s.

After researching and asking a separate stackoverflow question I figured out a way of sending the actual binary data from the client, specifically printf.
e.g.:
 printf "\x01\x02\x03\x04\x05\x06\x07\x08" | websocat -b ws://localhost:3002

Now that this works I can start going back through the rest of my Arduino code and have it parse the binary data directly instead of converting the encoded values to their binary counterpoints.
All of that said, I do appreciate all of the help. I may not have needed to do the conversions for this particular instance, but I want to get better with my C types, conversions, and general understanding so the knowledge gained here is still beneficial. Thanks everyone :bows:

ASCII code is represented by one byte, which is 8 bits, not 6 bits

it is unclear why you need to convert the ascii character to a number before displaying it

point 3 is 'void' unsigned char is one byte and your bit mask values fit into one byte.

(char) strtoul(strData)  http://www.cplusplus.com/reference/cstdlib/strtoul/

Awesome, thanks @dandavis I'll give that a try.

@jsotola re: ascii byte length: I know it's 8 bits, I typed out the ascii without leading zeros. The reason I want to convert it is because I'm not displaying the number character as a string, I want to use the binary representation to control the lights in a row of the matrix, so 1 or 0b00000001 would light up only the rightmost led on the 8 led row of the matrix. The conversion is so that I can use the binary representation of 1 (0b00000001) vs the binary representation of '1' ( 00110001)

Not sure if or why you want to convert char* to int, but if you need to, there are atoi(), atol(), strtol(), strtoul() to consider, or rolling your own function.
Pros and cons are discussed here. Main thing to note is that atoi() and atol() have no error handling, but if the char* you feed them is completely under control and predictable, that need not be a problem.
BTW I would try to get the websocket to send the correct single bytes instead of string representations of numbers, if at all possible.

a nice thing about atoi() is that it stops at non-digits, so your input can be "dirty" as long as starting with numbers, which makes it nice for using with existing string pointers instead of a small chopped-out char arrays.

I think this may be the solution. I have more detail but I have to wait till after work to update the question.


text:
Variable declared inside void setup() is forgotten in void loop()
If I declare a variable in void setup() and try to do something with it in void loop(), it just says that the variable is undeclared. Here is the code:
#include "Servo.h"

void setup() {
  Servo servo1;
  int x_key = A0;
  servo1.attach(2);
  pinMode(A0, INPUT);
  pinMode(2, OUTPUT);

  int x_position = 90;
}

void loop() {
  if (analogRead(A0) < 512) {
    x_position++;
    servo1.write(x_position);
  }
}

You need to select your code and tap the {} (code formatting) button. I did it for you.

Of course it's undeclared. The variable is in setup. It's not in loop.

Because the variable is only valid, where it is declared, to use the official term: it's scope. When the program moves out of the scope of this variable, it will get thrown away and be no longer available. You can declare it in global scope, meaning outside of any function

This is more a question about C/C++, not about Arduino

@chrisl true, but the OP doesn't know enough to know where to ask the question. We all have to start somewhere. I just wish people would do some self-study before running to the internet looking for somebody else to answer their questions for them.

what is your question? ... you did not ask anything

Yes, that is how C and C++ (and most other C-like languages) work. Variables have "scope". Any variable define inside a pair of curly braces (between a { and a }) is only visible inside those braces.
If you want to reference a variable in both setup() and loop(), you have to make it a global variable, defined at the top of your code.
#include "Servo.h"
Servo servo1;
int x_position = 90;  //Define your global var(s) here

void setup() {
    int x_key = A0;  //This var only exists inside the setup function
    servo1.attach(2);
    pinMode(A0, INPUT);
    pinMode(2, OUTPUT);

}

void loop() {
    if (analogRead(A0) < 512) {
        x_position++;
        servo1.write(x_position);
    }
}

Surely servo1 should be global as well?

Yup, that too. I was in  a bit of a hurry when I made that post.


text:
Watchdog on Arduino Nano does not recover
I'm trying to add a watchdog on an Arduino Nano, for my code, and I'm following the code in this manual exactly, but after the amount of time for not resetting the watchdog, it resets but does not reboot.
In the last paragraph it says that:

However, I could not find something similar in Optiboot bootloader (If
I'm wrong, correct me please!), used by Arduino UNO and other new
boards. It seems that they sacrificed this check for size. So, it is
possible that watchdog timer will be enabled after reset, so -  if you
set it's value too low, your board may never come out of bootloader
stage. So, to be always on the safe side, set watchdog to longer
periods (2S and more).

So I've tried for 8 s, but still same result.
What is wrong?
#include <avr/wdt.h>
int k=1;

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

void loop() {
  //do stuff here
  k++;
  wdt_reset();
  Serial.println(1000 * k);
  delay(1000 * k);
}

Please describe "resets but does not reboot". What happens? What does not? Try section 11.8 of the Atmega328p datasheet which describes the operation modes of the watchdog timer. You may need some additional setup to get the result you want.

Please post the actual test code you are using. The linked page only shows code which should not reset unless "do stuff here" takes too long. (Edit your question to do this).

@NickGammon added

As @JRobert said, what do you mean by "it resets but does not reboot"? Do you mean the watchdog timer resets, or the processor resets? If the processor resets then it would reboot.

the "old" Nano bootloader doesn't clear the Watchdog flag and while the bootloader waits for the upload, the board resets.
flash the "new" bootloader to Nano
In IDE 1.8.6 you can select version of Nano in Tools menu. It is the 'new' bootloader if you select "Atmega328p" and 'old' if you select "Atmega328p (Old bootloader)". If you invoke "Burn bootloader" it will use the bootloader for the selected option.

Can you please refer ?

how to burn bootloader? you need a programmer or other Arduino. https://www.arduino.cc/en/Tutorial/ArduinoISP

where to get this "NEW" bootloader ?

I enhanced the answer

The complete process of burning a bootloader is described here: https://docs.arduino.cc/built-in-examples/arduino-isp/ArduinoISP . The answer above is a summary and assumes that a programmer is a,ready connected to the target "Nano".

This works on an Uno R3.
The sketch restarts every 4 seconds when wdt_reset() is commented out.
Please copy the code and try it.
  #include <avr/wdt.h>

  void setup() {
    pinMode(13,OUTPUT);
    digitalWrite(13,LOW);

    delay(50);
    digitalWrite(13,HIGH);    // flicker the LED to identify when setup() is running
    delay(50);
    digitalWrite(13,LOW);
    delay(50);
    digitalWrite(13,HIGH);
    delay(50);
    digitalWrite(13,LOW);
    delay(50);
    digitalWrite(13,HIGH);
    delay(50);
    digitalWrite(13,LOW);
    delay(50);

    wdt_enable(WDTO_4S);

  }
  void loop() {
    digitalWrite(13,HIGH);
    delay(500);
    digitalWrite(13,LOW);
    delay(500);
    //wdt_reset();
   }

hi- same affect... perhaps Uno and Nano behave not the same ?

@Guy.D: We still need to know what you see happening and what you expected would happen instead.

@JRobert I’ll describe what I see: code run ok until time that wdt does not get its reset ( which I do on purpose). After that leds on board start to flicker non stop, and data stop posting on serial monitor ( this part I call- reset ). Only after a power off - board is booting back up. If I wouldn’t power off- that flickering state would keep forever.

this makes no sense .... the code that i posted flickers the LEDs during setup(), but there is no serial I/O code ..... it appears that you are not loading the new sketch into the Arduino, just rerunning the old sketch

I got the WDT working in my Nano with the old bootloader using this code from an old post on Arduino Forum.
The code is added after the wdt_reset();
  //reset watchdog
  wdt_reset();
  //set up WDT interrupt
  WDTCSR = (1 << WDCE) | (1 << WDE);
  //Start watchdog timer with 4s prescaller
  WDTCSR = (1 << WDIE) | (1 << WDE) | (1 << WDP3) | (1 << WDP0);

the true problem are wdt intervals shorter than the time bootloader waits for upload

The problem may be that the 328 defaults to a Watchdog time of 16mS after a reset-
WDP3 = 0, WDP2 = 0, WDP1 = 0, WDP0 = 0 so when it resets and starts your program from the beginning of your code, the program never gets very far.  I made a very short recovery program that just invokes noInterrupts(); and load it straight after a power off / on. Then you can load a new program that doesn't use the watchdog.

After that leds on board start to flicker non stop, and data stop
  posting on serial monitor

Definitely have a read of the datasheet for the '328p, section 11.8. There are several modes of operation - it can interrupt; reset; or both. Even if it resets, it doesn't reload your initial RAM data, so, for instance, line 2 int k=1; looks like an executable statement but is an initializer and has no effect at reset, and k retains its current value. There are probably other, similar, anomalies that happen when the WDT fires.
You probably don't need to understand the WDT down to its last control-bit but definitely make sure you're using it in the mode you want to be in. It will probably be handy during your testing to have a tiny sketch that just disables the watchdog so you can quickly get your Arduino back for the next test.


text:
Broken serial connection corrupting Arduino values
I have a problem with my homemade fan speed controller powered by an Arduino Nano, which reads a value from Serial (Arduino serial monitor, or Processing sketch) and uses the 0~255 value to set a variable fanspeed1 to set a PWM pin to control the fan speed.
The problem is when I close the Processing sketch, or the Arduino serial monitor, fanspeed1 is changed to max value (the fan speeds up to full speed).
I would like to send serial to set the value and then close the serial monitor, or Processing sketch and the value of fanspeed1 should not change.
If I need to post some code I can simplify my sketch down to a send serial, receive serial, make pin pwm = serial(0~255), but I am guessing there is a simple solution to this unfindable with my googling.
Help please, these fans need controlling...

Showing us your simplified sketch code would be useful here. For now, try to protect 'fanspeed1' from changing when serial communication is not active.

Disable the auto-reset functionality of the board?

It's 0~255, not 256.

You could consider writing/reading the value to/from the EEPROM.
http://arduino.cc/en/Reference/EEPROM
This allows the board to be reset, or even turned off, and retain the value previously set.  What you would be doing is saving the value to the internal memory of the Arduino.  This is resettable and persistent over a "reboot".
Granted, there is a limited number of writes you can do, but that number is high enough (~100k) that you will probably wear out the fan before the EEPROM sector dies.

Syntax
EEPROM.write(address, value)
EEPROM.read(address)
EEPROM.update(address, value)

For objects:

EEPROM.put(address, data)
EEPROM.get(address, data)


text:
Display values from a function on GLCD
I am new to Arduino and I'm trying my first Pro Mini. I was able to find DS1302 code from github that runs perfectly. My problem is trying to add some LM35 code to also display temperature data as well as the time data.
The code doesn't seem to run the Celsius and Fahrenheit functions. I have attached my code. Any help will be appreciated.
//Required library - http://www.rinkydinkelectronics.com/library.php?id=5
//Blog Post - http://overskill.alexshu.com/ds1302-real-time-clock-w-arduino/

#include "U8glib.h"
#include <DS1302.h>
#include <PreciseLM35.h>
//int float pinLM35 = A0;
const int pinLM35 = A0;
PreciseLM35 lm35(pinLM35, DEFAULT);

DS1302 rtc(2, 3, 4);
U8GLIB_ST7920_128X64 u8g(13, 11, 12, U8G_PIN_NONE);

void setup(void) {
  rtc.halt(false);
  rtc.writeProtect(false);

  // The following lines can be commented out to use the values already stored in the DS1302
  // Once you flash the Arduino with the correct time.

  //rtc.setDOW(FRIDAY); // Set Day-of-Week to FRIDAY
  //rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(6, 8, 2010); // Set the date to August 6th, 2010

  // assign default color value
  if (u8g.getMode() == U8G_MODE_R3G3B2)
    u8g.setColorIndex(255); // white
  else if (u8g.getMode() == U8G_MODE_GRAY2BIT)
    u8g.setColorIndex(3); // max intensity
  else if (u8g.getMode() == U8G_MODE_BW)
    u8g.setColorIndex(1); // pixel on
}

void draw(void) {
  u8g.setFont(u8g_font_04b_03);
  u8g.drawStr( 2,5, "******************************");
  u8g.drawStr( 13,10, "Arduino Pro Mini Control ");
  u8g.drawStr( 24,20, (rtc.getTimeStr()));
  u8g.drawStr( 1,20, "TIME: ");
  u8g.drawStr(70,20,  "Temp (C): ");
  u8g.drawStr (80,20, (lm35.readCelsius()));
  u8g.drawStr( 25,30, rtc.getDOWStr());
  u8g.drawStr(70,30, "Temp (F): ");
  u8g.drawStr(3,30, "DAY: ");
  u8g.drawStr(80,30, (lm35.readFahrenheit()));
  u8g.drawStr( 24,40, rtc.getDateStr());
  u8g.drawStr(1,40, "DATE: ");
  u8g.drawStr(70,40, "AREF : ");
  u8g.drawStr(80,40, (lm35.readPreciseAref()));
  u8g.drawStr( 15,55, "DS1302 Real Time Clock");
  u8g.drawStr( 2,65, "********************************");
}

void loop(void) {
  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while(u8g.nextPage()); //u8g.nextPage()
  // rebuild the picture after some delay
  delay(500);
}

Have you tried sending the output of the functions to the serial monitor and seeing if its a problem with the display library or the functions?

I used this code:  u8g.setPrintPos(110,20);


text:
Displaying 3 hex bytes sent to serial port on an OLED display
I am new to Arduino and I'm trying my first Pro Mini. I was able to find OLED display code from github that runs perfectly. My problem is trying to show 3 hex bytes sent by a remote control decoder module on the display.
The code will run under serial monitor with serial.print("I Received"); and serial.println(incomingByte, HEX);.
I want to receive this code on the serial port and display it on the OLED screen.
Any help is welcome.
I attached my code any help will be appreciated.
int incomingByte = 0
void setup() (
  Serial.begin(9600)
)

void loop() (
  if (serial.available() > 0) (
    incomingByte = Serial.read();
    u8g.drawStr(10, 37" I Received"); //glcd text position
    u8g.setPrintPos(10,42);
    u8g.print(incomingByte, HEX);
  )
)

This code can't work. You're missing semi-colons, a comma, and replaced {} with (). Good luck with that... You need to fix your code first.

I fixed all the errors and the code runs fine, thanks for suggestions and ideas. The u8g draw functions would not run in the loop function.

I'm going to assume you know the difference and significance between {} and () and the fact that the code you pasted in had a few syntax issues.
Below is a copy which should compile (I haven't tried it) I added a check to see if Serial.read() returned data, but otherwise its what you had.
int incomingByte = 0;
void setup()
{
    Serial.begin(9600);
}

void loop()
{
    if (Serial.available() > 0)
    {
        incomingByte = Serial.read();
        if (incommingByte != -1)
        {
            u8g.drawStr(10, 37, " I Received"); //glcd text position
            u8g.setPrintPos(10, 42);
            u8g.print(incomingByte, HEX);
        }
    }
}

You've not actually said if the code works or not.  Please can you try this version and report the results.


text:
Multiple Wire.write() not working for Arduino Nano I2C
Code for Master
#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
}

void loop()
{
    Wire.beginTransmission(9);

    Wire.write('c');
    Serial.println('c');
    Wire.write('a');
    Serial.println('a');
    Wire.endTransmission();
}

In my case Wire.write('c') is performing the task which is assigned to 'c' in slave board.
Then its printing 'c' in serial monitor as intended.
But, Wire.write('a') line is being neglected and nothing happens on slave board.  But again, it's printing 'a' in serial monitor as per code.
Why is that Wire.write('a'); is neglected? Both boards are Arduino Nano.
Code for Slave
#include <Wire.h>
#define RED 8
#define GREEN 10
int x = 0;

void setup() {
  pinMode (RED, OUTPUT);
  pinMode (GREEN, OUTPUT);
  Wire.begin(9);
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
}

void loop() {
    if (x == 'a') {
        digitalWrite(RED, HIGH);
        digitalWrite(GREEN, LOW);
    }
    if (x == 'b') {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, HIGH);
    }
    if (x == 'c') {
        digitalWrite(RED, HIGH);
        digitalWrite(GREEN, HIGH);
    }
    if (x == 'd') {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
    }
}

What is your slave board? Is it another Arduino? If yes, you need to show us the code for that too. Maybe you are misunderstanding how the Wire library works. Wire.write() does not send anything over the I2C lines. It only puts the data into the libraries internal buffer. Transmission is then done by Wire.endTransmission(), which sends out the content of the internal buffer as one I2C transmission. My guess is, that your slave is only reading the first byte of every transmission, thus ignoring the second byte ('a')

Thnak you for you reply i have added slave code also... please do see it.. thanks again

"transmission is then done by Wire.endTransmission()" this line gave me a hit, I modified my master code and now it working perfectlu.. thanks man

Make sure you mark the answer accepted and vote it up since it contains what you found useful.

Important information: Wire.write() does NOT send anything over the I2C lines. It just puts the data into the libraries internal buffer. The actual transmission is then done by Wire.endTransmission().
I2C is packaged transmission protocol. That means, that the transmission is done in confined data packages. In your master code you are calling Wire.write() two times before Wire.endTransmission(). That means you are sending 1 package with 2 data bytes in it.
Now for your slave code: You are using a callback function for the onReceive event. This callback function is called once per transmission. In there you can read all the data of that transmission. After that the data is thrown away (I think actually it gets deleted, when a new transmission is received). You are only reading once with Wire.read(). So you only ever read the first byte of every transmission, which is always the letter 'c'.
What to do know? This depends on how you want the code to behave. Since you are setting 2 LEDs based on the received byte it would be better to only send 1 byte transmissions. For that, you can change your master code. For example like this:
#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
}

void loop()
{
    // Send the command c
    Wire.beginTransmission(9);
    Wire.write('c');
    Wire.endTransmission();

    // Wait 1s, so that we can see the LEDs state accordingly
    delay(1000);

    // Send command a
    Wire.beginTransmission(9);
    Wire.write('a');
    Wire.endTransmission();

    // Wait 1s, so that we can see the LEDs state accordingly
    delay(1000);
}

This code will change between 'c' and 'a' every second. You need a delay there to actually see the LEDs light up. Otherwise they would change too fast for you to see it.
Note: Actually you need to declare the variable x as volatile, because the onReceive callback is called from an ISR. With that keyword you are telling the compiler, that x can change at any time (by the ISR of the corresponding I2C interrupt). It might be, that your current code works, because the compiler was smart enough to see that, but in general you should always use volatile with every variable, that can change in an ISR. Declaration then looks like this:
volatile int x = 0;

And to handle the ISR data really correct, you would need to make the usage atomic, because the ISR can happen in the middle of the comparison for the if statements. An int is two bytes, so the first byte might be updated and the second byte not. That would corrupt your data. There are two ways to handle that in your case:

Make the reading of x atomic: Normally one would turn of the interrupts, read the volatile variables into local variables (as a copy) and then turn the interrupts on again. That way the interrupt cannot corrupt the data in the variable during reading. The further calculation/comparison would then be done with the local variable.

Use a single byte as volatile data: The described problem does not apply to variables, which only use 1 byte (since on the 8bit Arduinos like the Nano the reading of a single byte cannot be interrupted). So just make x of type char (or uint8_t or byte).

You should use the second option.

The OP does use two LEDs to show the state, so he should be able to see which was the last received letter.

@PMF Yes, he/she uses 2 LEDs. But there are 4 states, each with a different pattern for those 2 LEDs. For each of the valid commands both LED states are written. So he/she can only see the last received command. If he/she sends two command without any delay between them, the first command is shown only a very short time (most likely too short to actually see it). Thus the delay


text:
Joy-IT RS232 Shield and RS232 voltage levels
First of all, sorry if this is a dumb question, but I'm pretty new to the whole Serial RS232 concepts.
I do have an Arduino Board that, from what I read about, is not able to communicate via RS232 because of different levels.
My question now is: If the Joy-IT RS232 Shield will make up for that. So is this shield handling the RS232 level shift? I don't really know what to look for so I am asking here.
Thanks!

Yes, that shield will handle the level shifting for you. If you look closely at the images of the shield, you see the MAX232 chip, which is a commonly used chip for getting UART (which is the Serial interface of the Arduino) to speak over RS232.
And yes, RS232 uses different voltage levels. The UART on a microcontroller usually uses the voltages 0V and 5V (or 3.3V depending on  it's supply voltage), which is also called TTL levels (Transistor-Transistor Logic), while RS232 mostly works with +-10V (though different voltages are also inside the standard). You see, that this is a symmetrical voltage around ground (0V).

Wow thanks for the detailed answer! Then this shield is exactly what I need for my project.


text:
Vernier to Arduino not working
I want to connect this analog Vernier temperature probe to my Arduino with this British Telecom Connector (BTA).
According to datasheet, when sensor is in the connector, the PIN 6 of the connector should give us the value from 0-5V. I think it should work with this connector because it is supposed to work with this adapter, which is approved by Vernier. It's hard to get any real details about this official Vernier adapter, but I think it doesn't do anything different than just the BTA (linked above).
Of course, I also connected 5V and GND to connector, but when I want to read that 0-5V from Arduino, it says 0. Every single time. The sensor is not broken, because it works with Vernier sensor interface shield which I put on the Arduino (yes, I could use it, but I want to make my project smaller).
That's how the PINS work:

Sensor Pin
Arduino Pin

1 (+/-10 V output line)
A1

2 (Ground)
Ground

3 (Vres/resistance reference)
A4 (also for I2C autoID)

4 (AutoID)
A5 (also for I2C autoID)

5 (+5 Volt power)
5V

6 (0-5 V output line)
A0

I don't know if that's important, but the sensor is based on a thermistor. Also, if I connect A0 to PIN number 1 (+/- 10V output line), it gives me a value.  But, I really can't find anywhere how is that value connected with temperature. I hope I presented my problem well enough so you will understand it.
Thanks :)

This is probably going to sound mean, but I'm sincere in this. Break that up into coherent paragraphs and make sure you're focusing on one thing.

data is a number that's not 0 ... very normal

Sorry, i just didn't know what kind of information do you need :/. That's the link to the probe: https://www.vernier.com/product/stainless-steel-temperature-probe/ . I though it would work with Arduino like this because it works if you use this protoboard adapter approved by Vernier: https://www.vernier.com/product/analog-protoboard-adapter/ .

Take some time to edit your question.  You can put those links into it while you're in there.

Well, I've made an edit to get you started.  I'm trying to be conservative with it.  You should refine it.


text:
Detect current in car handbrake circuit

Using Arduino, how can I detect that the switch is on? I have access to the wire within the red rectangle only. That's because the switch is closely connected to the car body (ground). When the handbrake is up, the switch is pushed by a coil to touch car body and close the circuit. And when the handbrake is down, the switch go away from the car body and the circuit is open.

Can you insert a voltage monitor? Or other parts?

If you literally only have access to that wire, you cannot. You will need access either to the ground or 12v, or the bulb to see if it is lit.

Actually that's not quite true. You could do it by cutting the wire and putting a resistor in series, then measuring the voltage across the resistor.

this seems like a school assignment. ... did i guess correctly?

@CodeGorilla what will voltage monitor do?

@jsotola Nope, It's an idea I'm making in my car

@MegamindSaiko it will monitor the voltage.

If you are doing this in your car, as you say, then you can easily get a ground somewhere else (the whole body is ground) and just use a voltage divider (two resistors) to measure the voltage.

It's the handbrake switch button, the switch is directly connected to the ground, there's no wires or space to place anything. while the handbrake is up, a coil push the switch to touch car body, and while down the switch get away from the car body and open the circuit.

A friend of mine said that I can just check for the voltage (without shunts or any other tools). He said that if the switch is closed, the voltage would be zero as the ground, and if the switch is open, it will read 12 V. Is that true?? I will try it using a multimeter.

After examining the answers provided by "Jose can u c", "Alberto Perro" and "VE7JRO", and the comments by "Mark Smith", It was clear to me that there are a lot of methods to use, but I found out that the simplest way is to just measure the voltage at any point within the red rectangle. While the circuit is close, it will read 0V, and while the circuit is open, it will read about 12V.
And of course we will use voltage divider to reduce the voltage to  about 4V, and 4.7 zener diode to protect Arduino's pin.

If you truly only have access to the red rectangle content, and not the Ground or +12V supply, you could use an opto-isolator, assuming you can use enough of the wire in the red rectangle to be able to form a voltage divider to get at least 1-2 mA through the input side of the opto.

It gets easier if you have access to the Ground point, too...

Based on your comments:
"It's the handbrake switch button..." and "..if the switch is closed, the voltage would be zero as the ground, and if the switch is open, it will read 12 V.",
you could splice into the wire and use it as an input for the Arduino. You can NOT connect it directly to an Arduino because 5V is the maximum voltage permitted on a digital input (assuming your Arduino is running at 5V).
There are several ways to connect it to the Arduino safely, such as an opto-isolator, a level-shifter or using passive components.
This circuit using 2 resistors and a zener diode may work for you:

Be sure to connect the vehicle ground to the Arduino GND.

Wrap the wire around a ferrite or some iron core and detect magnetic field.

This may not be the most practical answer, but here's an upvote for creative thinking!

If you can modify the cabling, you can add a shunt resistor in series and measure the voltage drop between the terminals. This way you can measure the current draw that would be 0 if the switch is open and something if the switch is closed.
Other way you can use an ACS712 Current Sensor.


text:
Weird serial behavior on atmega2560
EDIT
This seems to be something to do with the oscillators. Switching to the internal oscillator and writing straight avr-c allows me to run a basic blink program. Writing the same basic blink in arduino and flashing with the IDE (through serial or usbasp) results in a non functional program. I'd like to be able to use the oscillator because it doesn't look like I can get everything done in time at 8MHZ
I have an arduino mega 2560 which a few weeks ago was working fine. Now, I'm trying to output some data from it, and 've broken it down to a very, very basic proof of concept:
void setup() {
// put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
   // put your main code here, to run repeatedly:
   Serial.println("hello");
}

This prints:
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

indefinitely on the screen. If I change the baud to 115200, I get the "hello" and the newline, and slowly start getting garbage afterwards. If I switch to 234500, I get a few prints, and then nothing.
Adding a delay after the print does not change the frequency of the serial prints:
void loop() {
// put your main code here, to run repeatedly:
    Serial.println("hello");
    delay(100000);
}

They still come in immediately.
I have a feeling this has something to do with timing of an interrupt, but I'm not setting anything up. I plan to reflash and fix the fuses, but my usbASP cable is broken right now. Any other input on what might be going on here?
Edit:
This occurs on two different boards. I originally had some i2c devices (mag/gryo/barometer) on board, but those have since been removed. I have tried two different usb cables in two different USB ports. This might be on the host side?
Edit:
Both the TX and Rx lights are solid this whole time. Almost as if there's a loopback. My other laptop won't even boot right now. I'm concerned a surge from a storm last night might have taken out both of these machines
More testing:
Looking at the output on a scope, the board is actually only outputting an "h" character. If I do:
Serial.println('U');
delay(1000);

I get a square wave, so the delay doesn't run at all.
If I do:
Serial.println('U');
Serial.println('U'); //or any other character
delay(1000);
I get a U character over the scope, and then an empty serial frame. The delay still doesn't run, but it looks like the second println is exiting.
Even burning a new bootloader fails on these boards

This does look like some kind of hardware problem. I have seen Uart chips causing strange output and act as if having a loopback, but only on real Uarts, not on USB devices.

Was either of the Atmega boards connected to anything during the surge? Was the host computer plugged in to power? It does sound like the common element is your computer's USB. Can you try using a different physical USB port on the laptop? A different laptop?

I've brushed both boards to eliminate shorts. I'd accept hardware failure but two previously working boards on the same day?

@jrobert boards were not powered, laptop was charging. My other laptop (also charging) will not boot today, which contributes to my suspicion

add Serial.println("world"); delay(5000); to your code

@jstola the issue here is it's never exiting the original serial print. I need to read the Arduino core code (and/or just code this in straight avr-c) to see what error handling is going on and why serial print is never exiting

It would help to print something distinct in setup() to know whether or not the boards are resetting.

Consider doing a loop-back test.  Connect RESET to GND and D0 to D1.    This will hold the ATMega2560 in reset so it doesn't interfere.  IdeallyD0 and D1 would be connected by low value resistor, say 330 ohms to protect against accidentally letting the 2560 out of reset. With D0 and D1 connected, what you send you should receive at any of the standard baud rates.  This will tell you something about whether are before or after the serial transceiver.

Answering my own question - a bit of a walk of shame here.
I had disabled the internal TIMER0_OVF_vect in the arduino core code, so that I could write my own (for another project). I wrapped in in an #if 0 so I could go and bring it back when I needed it.
Today, I learned that the atmega interrupts aren't filled with an IRET by default, but instead hit the reset vector, resetting the board. Anything I compiled on this library would reset whenever TIMER0 overflowed, because my ifdefs didn't cover the TIMSK setting in the arduino core either
The "Serial.println isn't exiting" was actually "the board is resetting before it can complete" and explains why faster bauds could print more data.
Not much smarter than hairless apes, sometimes.


text:
Will adding Ethernet shield reduce the IO count of Arduino?
I have searched this question but could not find an answer on this site.
There was a related question - Latest Ethernet shield - used pins, how to bypass restrictions on arduino forums, but, I was unable to understand what the answer meant.
The background of my project:
My project requires

| S.No. | IO Type | IO Qty |
|-------+---------+--------|
| 1     | AI      |     11 |
| 2     | DI      |      9 |
| 3     | DO      |     11 |

I intend to connect this arduino board via ethernet shield to a network. I want to receive data over the network for display and storage purposes on a PC.
Questions:

What Arduino board should I select?
Will ESP8266 be compatiable with the suggested model?
Are there any pitfalls that should be considered when making the
selection for this design.

P.S: I have raised the same question on the arduino forum. If I get an answer- I will share my answer here as well

@Juraj. I understand that [Mega2560] has the most number of IO's. 16-AI and 54 DI/DO. Should that be ok?

click the link to the "related question" and you will find that it invalid.

@jsotola Its funny, that the link broke. Fixed it

instead of posting the same thing on two websites, post a description here of what you do not understand. ... someone here may be able to give you an explanation. ... the way things are, you may get an answer, but your understanding will still be unclear.

You should use a Mega if you really need so many gpio pins.
Arduino Ethernet and WiFi shields and their clones use 3 GPIO pins with SPI function with connection on ICSP header. Next they use the Slave Select signaling pin 10 and the SD card Slave Select signaling pin 4. The shields are compatible with Mega. So you should still have enough pins.
esp8266 can be connected to SPI. then it uses the same pins like the Ethernet shield except of the SD card slave select pin.
if you connect esp8266 to Serial port, then all the pins are free. Mega has 4 Serials.
esp8266 is cheaper but you need to connect it with level shifters and have a good power supply. there is no good esp8266 shield for now. The Mega + WiFi board from Robotdyn has the esp8266 on board with Serial connection.

SPI function is on pins 11, 12, 13 on Uno and 50, 51, 52 on Mega. the Slave Select (SS) pin is SPI function if Atmega is SPI slave. 10 on Uno and 53 on Mega. If Atmega is master, then the SS pin must be set as output. So it is good to use it for signaling to SS pin of one of the slaves.