text:
Changing ESP-12E NodeMCU to ESP-01S - how to trigger sketch?
I had my sketch up and running with a NodeMCU and a Leonardo Pro Micro and decided I wanted to minimize the footprint of the project and use the smaller ESP-01S board instead.
The ESP-01S is programmed to send a push notification to Pushover and my old code works - the only problem is that I don't know how to trigger it from the Pro Micro.
With the NodeMCU I just setup it up to listen on Pin 2 and I triggered a high/low from my Pro Micro and it sent the push notification - at the moment as soon as I power the ESP-01S up it just sends the push notification over and over and doesn't see the connection from the Pro Micro to stop it doing this.
Here is my current code on the ESP-01S

#include <ESP8266WiFi.h>

// Wifi Settings
const char* ssid = "Redacted";
const char* password = "Redacted";
// Pushover settings
char pushoversite[] = "api.pushover.net";
char apitoken[] = "Redacted";
char userkey [] = "Redacted";
int length;
WiFiClient client;
void setup() {
  pinMode(0, OUTPUT);
  digitalWrite(0, LOW);
  pinMode(2, INPUT);
  Serial.begin(9600);
  delay(10);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Print the IP address
  Serial.print(WiFi.localIP());

}

void loop()
{
if(digitalRead(5) == 1) pushover("Deployment Completed");
}

byte pushover(char *pushovermessage)
{
 String message = pushovermessage;

 length = 81 + message.length();

if(client.connect(pushoversite,80))
 {
   client.println("POST /1/messages.json HTTP/1.1");
   client.println("Host: api.pushover.net");
   client.println("Connection: close\r\nContent-Type: application/x-www-form-urlencoded");
   client.print("Content-Length: ");
   client.print(length);
   client.println("\r\n");;
   client.print("token=");
   client.print(apitoken);
   client.print("&user=");
   client.print(userkey);
   client.print("&message=");
   client.print(message);
   while(client.connected())
   {
     while(client.available())
     {
       char ch = client.read();
       Serial.write(ch);
     }
   }
   client.stop();
 }
}

and my Leonardo Pro Micro code is as follows
#include <HID-Project.h>
#include <HID-Settings.h>
int buttonPin;
int buttonPin2;
char chr;   // for incoming serial data, type char is signed 8-bit, -128 to 127, ASCII is char codes. Save 1 byte over type int.

void setup() {
  pinMode(5, OUTPUT);
  pinMode(7, OUTPUT);
  BootKeyboard.begin();
  Keyboard.begin();
  Mouse.begin();
  Serial.begin(115200);
  buttonPin = 4; //White Button
  buttonPin2 = 6; //Black Button
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
}

void loop() {
  delay(5000);
  digitalWrite(5, HIGH);
  delay(100);   //short wait time
  digitalWrite(5, LOW);
  }

Obviously I want the digital pin 5 of the Pro Micro to trigger the ESP-01 to send a push notification when it's trigger.
Just for the record I'm using a 3.3v Pro Micro btw so there's no issue with the voltage here, before I was using a Logic Converter with a 5v board.
I have the ESP-O1S setup with the 3V3 and EN are connected to the 3v VCC on the Pro Micro, the GND to GND and I tried IO0 and IO2 to Digital Pin 5 on the Pro Micro.
Could someone point me in the right direction?

why do you read pin 5 in esp8266?

Use io 0 as the esp-01S pin wired to Micro, but change the logic for pull-up, because esp-01S has a pull-up resistor on io 0 of the esp8266. Use LOW to trigger the action and HIGH as normal state.
On Arduino Micro side set the output pin HIGH before you set it as OUTPUT. This will avoid the LOW state. While the Micro pin is in INPUT state after power-up, the pull-up resistor on esp-01S will pull io 0 HIGH.

Gotcha, so do I need to change any of this code on the ESP-01S?
void setup() {
pinMode(0, OUTPUT);
digitalWrite(0, LOW);
pinMode(2, INPUT);
Serial.begin(9600);
delay(10);

in esp8266 pinMode(0, INPUT); and if (digitalRead(0) == LOW) pushover("Deployment Completed");

Got it, cracked it, thanks Jaraj!

Just to double check, the correct way on the Leonardo to change the logic is to just set the pin write as HIGH in setup right? There's no way to flip it when you set it out as a Output (that I can see)

yes set it HIGH before setting it as output, to avoid the LOW state which would trigger the action


text:
Reading data by port manipulation (Arduino Due)
I have shorted the 23rd pin of port A with 3.3v output pin (i.e. tieing 23rd pin of port A to logic high). Now I am trying to read the 23rd pin of port A by using following code-
void setup() {
  Serial.begin(9600); // put your setup code here, to run once:
  char print_str[40];
  REG_PIOA_PER = 0x00800000;   //Write 1's to A register pins to override other peripherals and allow GPIO use for pins
  REG_PIOA_ODR = 0x00800000;   //Set A register pins to INPUT
  sprintf(print_str, "\n%08X", REG_PIOA_PDSR);
  Serial.println(print_str);
}

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

According to the code, the serial output should be 0x00800000. But I am always getting 0. Could you please tell me, what is going wrong?

23rd pin is PA22 ... did you connect the correct pin?

Check the value of REG_PIOA_WPMR.

Hint: Take a look at the GPIO library for SAM. There is an initialization missing. https://github.com/mikaelpatel/Arduino-GPIO/blob/master/src/Hardware/SAM/GPIO.h

source: Stack Exchange

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

sort: votes


text:
How can I measure the point of contact between two wires?
I'm not sure the best way to ask this question, so I'll try to explain what I'm looking for, and roughly what I think is involved.
I want to measure the point of contact between two wires. This seems like it could be a resistance measurement, but I wasn't sure if that was the best way to go as it seems like the amount of change would be too small to measure.
Specifically I have two wires (more likely some sort of conductive ribbon) on a glove. One wire runs along the index finger, and the other is at the tip of the thumb. When someone touches their thumb to their finger, I want a value that indicates approximately where they touched.
For example, if they touch the tip of their finger to their thumb the value would be 1. If they touched their thumb to their first knuckle, then the value would be 0.75. And so forth. With a touch between two "points" producing a value in between.
Ideally someone could slide their thumb down their finger and produce a slowly changing value from 1 to 0.
Is resistance the way to go for this? It seems like there could a lot of other variables (surface area of contract, humidity, etc) that could dramatically change the resistance. Is there a better method?
Update: Because of some overzealous votes to close and confusion, this will be using the Arduino platform (maybe an ESP32, if that matters) once I figure out what sort of sensors and systems to work with.

Will you be using an Arduino in your project?

the index finger resistive strip and a contact on the tip of the thumb could act as a potentiometer .... one end of strip connected to Vcc ... other end connected to ground ... read the voltage on the thumb contact

voting to close because the question is not about Arduino

@VE7JRO Yes, this will be using Arduino platform, that is why I am posting it here. I can go add the words Arduino to the post if that makes you feel better.

@Jstola A restive strip sounds like exactly what I need. I'm assuming that works with Arduino (since we are on an Arduino site) but I guess I need to ask since you didn't say so explicitly.

You don't want wire, or wire braid. The resistance is too low and is very hard to determine accurately. Instead you want nichrome wire. Then just use it with a resistor of similar resistance to the maximum resistance of a touch as if it were a potentiometer.

@Majenko I figured the resistance would be too low. Looking into Nichrome wire and other resistive wire now. Thanks!

@VE7JRO Thanks for shutting down my first post here. Really makes me feel welcome to the community. I can just delete it and take my attention elsewhere. Clearly this isn't a site welcoming to new users. Thanks for making that clear before I waste more or my time participating in the community.

@Jim McKeeth - I'm sorry you feel that way. Unfortunately, your question is off-topic for the Arduino SE network. Please have a look at this page about General Electronics: arduino.stackexchange.com/help/on-topic "If your question is about making electronics or other electricity questions not related to Arduino, try Electrical Engineering". "If knowledge of Arduino would improve a question, it's on topic."

@Jim McKeeth - Your question only has a peripheral relationship to Arduino (if you decide to use one), is mainly about general electronics, and if you substitute a different type of micro controller (Rasberry Pi for example), the question is essentially the same.

@ve7jro I clarified my question immediately after I was asked if it was Arduino related. I see now sensor recommendations for use with Arduino are off topic. Seems very narrow-minded. I used to participate a lot in Stack Overflow before the culture got toxic. I see the toxic culture is all over the network. No thanks.

you could try 4 terminal sensing.
I have not used it myself, but the basic idea is to try to normalise for some of the external factors you mention.
As for the Arduino, the analog to digital converters have 10 bits of precision. This means you will get 1023 distinct values as the input voltage varies betwee 0 and Vmax (+5 or +3.3 depending upon the actual device). So that is fairly precise, usually you just use the value from the analog read - but you can convert to a value between 0 and 1 by dividing:
    int analogInt = analogRead(<your port here- e.g. A0>);
    double analogFloat = analogInt / 1023.0

Which begs the question, did you try using a 2 wire system? Assuming just 1000 data points, and a finger being, say, 5cm in length; that's roughly 1 point per .05 mm. I know it won't work out exactly like that, but that is my point - it is likely to be a rough estimate anyway due to the size of a finger at the touch point.

I didn't try the 2 wire system yet. I wasn't sure if it would work, and wanted to do a little research first. The 4 terminal sensing sounds interesting too.

Thanks for taking the time to answer my question. Because it has been put on hold, it is most likely going to just end up in a black hole on here and eventually be deleted.

:-( hopefully my reply helped you even if this topic is unwelcome here

It is helpful. Thanks!

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


text:
How can I connect multiple MCP23017's to an arduino?
I am working on a project and I am trying to figure out how to connect multiple MCP23017 IO Expanders to one arduino. All of the guides that I have found in my quest for information only explain how to connect one MCP chip or how to address multiple MCP chips. None seem to explain how to connect them physically. BTW, I am talking about the I2C version of the chip.

If you know how to connect one chip you know how to connect many chips.  One or eight it's the same.
All the SCL pins connect to the SCL pin of the Arduino. All the SDA pins connect to SDA on the Arduino.
Just make sure that each chip is given a unique address using the A0-A2 pins as detailed in the datasheet.

One to eight is the same, ten is too much with three address bits.

You can also address them all with the same address, and use the A0-A2 pins as a chip select.  For example, have discrete pins connected to A0s, and have A1, A2 connected to Gnd. Have A0 held high in the code.  When you want to talk to a device, bring A0 for that device low, use the I2C address for A0-A1-A2 =0, then bring A0 for that device back high.  Next device, use the next A0 line, and so on.  You could expand even further, with A1/A2 = 0,0,  and 0,1, and 1,0, and 1,1, with 32 slave select lines (fed by 4 shift registers even, with just 3 control lines needed to load the shift registers).


text:
strtoul behavior between C and Arduino
I have this code C code that compiles OK on my laptop
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

unsigned int crc32(const void *m, size_t len) {
  const unsigned char *message = m;
  size_t i;
  int j;
  unsigned int byte, crc, mask;

  i = 0;
  crc = 0xFFFFFFFF;
  while (i < len) {
    byte = message[i];
    crc = crc ^ byte;
    for (j = 7; j >= 0; j--) {
      mask = -(crc & 1);
      crc = (crc >> 1) ^ (0xEDB88320 & mask);
    }
    i = i + 1;
  }
  return ~crc;
}

int main() {
  char str[] =
      "620004";
  size_t len = strlen(str);
  unsigned int crc = crc32(str, len);

  size_t len2 = (len + 1) / 2;
  unsigned char arr2[len2];
  for (size_t i = 0; i < len; i += 2) {
    arr2[i / 2] = strtoul((char[3]) {str[i], str[i + 1], '\0'}, 0, 16);
  }
  crc = crc32(arr2, len2);
  printf("CRC: 0x%X\n", crc);

  return 0;
}

And I'm trying to port it to Arduino
#include <CRC32.h>

void setup() {
  Serial.begin(115200);
  uint8_t byteBuffer[] = "620004";
  size_t numBytes = sizeof(byteBuffer) - 1;
  size_t len2 = (numBytes + 1) / 2;
  unsigned char arr2[len2];
  CRC32 crc;
  for (size_t i = 0; i < numBytes; i += 2) {
    arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
  }
  for (size_t i = 0; i < numBytes; i++){
    crc.update(byteBuffer[i]);
  }

  uint32_t checksum = crc.finalize();
  Serial.print("CRC: ");
  Serial

But I'm getting a
Arduino: 1.8.9 (Linux), Board: "Arduino/Genuino Uno"

/home/nico/Arduino/crc32/crc32.ino: In function 'void setup()':
/home/nico/Arduino/crc32/crc32.ino:11:50: warning: narrowing conversion of 'byteBuffer[i]' from 'uint8_t {aka unsigned char}' to 'char' inside { } [-Wnarrowing]
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                  ^
/home/nico/Arduino/crc32/crc32.ino:11:69: warning: narrowing conversion of 'byteBuffer[(i + 1u)]' from 'uint8_t {aka unsigned char}' to 'char' inside { } [-Wnarrowing]
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                                     ^
crc32:11:84: error: taking address of temporary array
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                                                ^
exit status 1
taking address of temporary array

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

And I'm not really understanding what's the issue here with the strtoul function and its different behavior on Arduino

All those errors are related to (char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, it has nothing to do with strtoul. Who knows how old is the compiler where it works.

Btw first two are caused by difference between:  char str[] = "620004"; and uint8_t byteBuffer[] = "620004";

Please make an answer, don't post an answer as a comment. Comments are for clarifying the question.

In some architectures a "char" is an "unsigned byte". In others it's a "signed byte".  The AVR specification mandates a signed byte for char. Whatever you are compiling on probably mandates an unsigned char.
You cannot assume one or another. If you are working with an array of characters (a "string") you should be assigning it to a char data type. That way the signage of the data type and the "string" content will match.
By using uint8_t you are specifically telling it to use an unsigned byte.
strtoul() expects a char. Since on AVR char is signed, when you try and squeeze an 8-bit value into a 7-bit + sign space it warns you. Which is good. You potentially lose the 8th bit of your data.
The main error, though, is:
error: taking address of temporary array

This is caused by you creating a new temporary array within the parameter list of strtoul.
{byteBuffer[i], byteBuffer[i + 1], '\0'}

Then you take the address of that array and pass it to the function.  That is not good. Imagine the situation where the function returns something that is dependent on that address. For instance a function that returns a pointer to all but the first character of the string.  Once the function returns that returned pointer points to an area of memory that is no longer valid - the temporary array has already been disposed of.
I know that's not the case in your code, but it's a possibility you can conceive.
Yes, temporary arrays like that are perfectly valid in some versions of C++. But those are fairly recent versions, and the Arduino compiler isn't that recent (I don't know which version introduced them as valid off hand, but we're up to GCC version 8 now. Arduino is still down at version 5.something IIRC).
Suffice it to say, don't use temporary arrays like that (which is a shame, because it's damn useful).  Instead you have to assign it to a new array and pass the pointer to that array instead:
char tempArr[3] = {byteBuffer[i], byteBuffer[i + 1], '\0'};
 arr2[i / 2] = strtoul(tempArr, 0, 16);

That way the address you're passing to the function is one that is allocated on the stack and is guaranteed to exist past the lifetime of the function call (right up until the end of the current scope).

Not questioning the language issues that were pointed out, but simple answer to what you asked,

"... what's the issue here with ... its different behavior on Arduino"

is that these are two different compilers, possibly written to two different standards of the language (the standards evolve over time) and likely run with different error- and warning suppression switches.
And not to be pedantic but to clarify, it hasn't actually run on the Arduino yet, not having compiled successfully in that environment. The differences you see are entirely due to the differences between the two compilers and the error-options they were run with.


text:
lcd doesn't show any characters , is the problem in the lcd itself?
That's my wiring besides another part of a project ( ultrasonic sensor) which works correctly on the same breadboard, Rs 12 , En 11 , d4 8 , d5 9 , d6 10 , d7 13 I tried to change power of arduino from 5 to 3.3 volt & I tried to use a power adapter
the lcd sometimes show me dark boxes for seconds when I use the potentiometer often in the first row of the display
i used the simulation of tinker cad & it's working but doesn't work on my project & i used the default arduino code with changing the pins number

code :
#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 8, d5 = 9, d6 = 10, d7 = 13;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // Turn off the display:
  lcd.noDisplay();
  delay(50000);
  // Turn on the display:
  lcd.display();
  delay(50000);
}

[![enter image description here][2]][2]

Your code will print on the LCD and immediately turn it off, then wait for 50 seconds and turn it on again. Have you waited the 50s to check if something is shown?

yes I waited for it I doesn't show me any character

In addition to the 6 signals you described, I see 6 more. Allowing that the LCD needs power & ground, and one is the potentiometer, what are the other 3? Do you have a part number for the display, or can you show a definition of its inputs? What is the 10K pullup resistor for?

Vss gnd , VDD 5v , V0 to the middle terminal of potentiometer used for adjusting contrast , RW gnd  , 10 k resistor connected to anode I used it beacuse of the schematic in this link  https://www.hackster.io/MylesBartlett/ultrasonic-security-system-with-object-distance-display-0d7140?f=1#    I tried to remove it but It made the lcd stop working or having power

If you are using 4-bit structure you must use LSB not the MSB. Try your code by connecting your wires to d0,d1,d2,d3 of LCD.


text:
Can you drive a stepper motor without the L293D
Can you drive a stepper motor without L293D.
Don't awnser without giving explanations or saying it will be cheaper to buy the L293D.
Thanks

yes, you can ... there are other stepper drivers available

Any (dual-) H-bridge will do. You can build your own H-bridge out of transistors. You could even use two relays. Or get some proper stepper drivers, as the L293D isn't really great for that purpose.

Depending on the type of stepper motor the answer can be "Yes" or "No".
There are two types of stepper motor: Unipolar and Bipolar.  Bipolar motors typically have 4 wires and require a H-bridge to drive them.
The L239D is a popular (and cheap), though inefficient, H-bridge that is commonly used. But it is possible to build your own H-bridge from discrete components. There are a lot of caveats and pitfalls when building your own H-bridge though, so people generally don't unless they have a specific requirement that isn't addressed by an integrated one. There are plenty of schematics and descriptions of operation online if you want to learn more about H-bridges.
There are also dedicated bipolar stepper drivers which are easier to work with: you just set the direction and give it a pulse to step in that direction. Much easier to program with, but can be more expensive. However these do tend to be more modern MOSFET based components which are far more efficient and dissipate less heat (or can handle more powerful motors in a similar size package).
Unipolar stepper motors, on the other hand, have more wires (typically 6) and are much simpler to drive. All you need for these is a transistor per coil (typically 4 coils connected as pairs) and you just need to activate them in the right sequence.
The ULN2003 is a popular integrated chip for driving unipolar stepper motors. It's just a bunch of transistors in a single package that is easier to wire up than discrete transistors, though there is no reason why you couldn't do it just with 4 discrete transistors. It's just simpler and tidier to use a single chip.
There are plenty of demonstrations and tutorials online describing driving a unipolar stepper motor with the ULN2003.


text:
NRF24l01 with Atmega 32u4 and internal clock
Will the nrf24l01 work with the Atmega 32u4 if I am using the 32u4's internal clock, or must I have an external clock source?

Knowing the interface between nrf24l01+ and Atmega32U4 is also answer to your question. And even with using asynchronous serial it should be possible (but might be less reliable sometimes)

Connecting to nrf24 via    CE, CSN, SCK, MOSI, MISO   -    I have the nrf24 working fine on my Pro Micro, now trying it on my custom pcb where I do not use an external oscillator.  My custom pcb works fine other wise, including the SPI as I have another device working on the SPI.  Just not working with the nrf24.

And SPI is synchronous interface, so there is a master sending CLK signal to clock data to selected slave

Correction,  My other device is connected via I2C,  not SPI.  But I am programming the 32u4 via SPI.

Without at least schematics, test scenarios and so on (what works or not works and where), it's hard to guess.

Should be just fine. I2C and SPI don't care about at what speed the MCU runs. Only things like UART sometimes require a more stable clock source, like a crystal, instead of the internal RC oscillator.

I found a mistake on my custom pcb,  I wanted CE as pin4 and CSN as pin5, but I mistakenly put them to pins 38 & 39 on the chip which are A4 and A5. Any issue having analog pins as CE and CSN?

You ask a yes/no question, to which the answer is yes, nRF24L01 as a serial peripheral device will work as well as if you had used an Arduino UNO or any other microcontroller, provided the SPI bus is correctly initialized.
Generally you want the following in the setup() part of your sketch/program:
  pinMode(CE_pin, OUTPUT);//chip enable set as output
  pinMode(CSN_pin, OUTPUT);//chip select pin as output
  pinMode(MOSI_pin, OUTPUT);//SPI data out
  pinMode(MISO_pin, INPUT); //SPI data in
  pinMode(SCK_pin, OUTPUT);//SPI clock out

  digitalWrite(CSN_pin, HIGH);//SPI idle
  digitalWrite(CE_pin, LOW);

  SPI.setBitOrder(MSBFIRST);//SPI Most Significant Bit First
  SPI.setDataMode(SPI_MODE0);// Mode 0 Rising edge of data, keep clock low
  SPI.setClockDivider(SPI_CLOCK_DIV2);//Run the data in at 16MHz/2 - 8MHz
  SPI.begin();//start up SPI library


text:
freeRTOS tasks never run on Lightblue Bean
Although Punchthrough no longer supports the Bean and Bean+ they still maintain the online compiler and reference materials:
Bean Github
Bean reference
One of the external libraries they've included in the cloud compiler is FreeRTOS, linked libs Arduino FreeRTOS port, and the cloud compiler/BeanLoader seems to properly link to the lib and download my compiled app to the bean:
// minimal test for freeRTOS

// works on UNO, fails on Bean

#include <Arduino_FreeRTOS.h>

// Logging hackery
// 0 disables, 1 enables
// #define LogConstantly 0
#define LogConstantly 1

#if(LogConstantly)
  #define Dump(x) Serial.print(x)
  #define Dumpln(x) Serial.println(x)
  #define DumpS Serial
#else // ! LogConstantly
  #define Dump(x)
  #define Dumpln(x)
  #define DumpS
#endif // LogConstantly

// LED handling
// Find the Bean files in [apps]Bean\ Loader[vers?].app/Contents/Resources/Arduino/hardware/bean/avr/cores/bean/
// Defined in bean.h:  BEAN_BEAN_BEAN_H
#ifdef BEAN_BEAN_BEAN_H
  #define LED_ON  Bean.setLed(0,0,127)  // light the blue segment at 50%
  #define LED_OFF Bean.setLed(0,0,0)
#else
  #define LED_ON  digitalWrite(LED_BUILTIN, HIGH);
  #define LED_OFF digitalWrite(LED_BUILTIN, LOW);
#endif // BEAN_BEAN_BEAN_H

#define RELAYOUTPUT 2 // pin for relay control.

// tasks for RTOS scheduling

void TaskBlink(void *pvParameters)  // This is a task.
{
  (void) pvParameters;
  while(true) { // A Task never exits.
    LED_ON;
    Dumpln("BlinkenLit");
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
    LED_OFF;
    Dumpln("BlinkenDark");
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
  }
}

void TaskRelay(void *pvParameters)
{
  (void) pvParameters;
  while(true) { // A Task never exits.
    digitalWrite(RELAYOUTPUT, HIGH);   // engage the relay
    Dumpln("relay enabled");
    vTaskDelay( 2500 / portTICK_PERIOD_MS ); // wait for 2.5 seconds
    digitalWrite(RELAYOUTPUT, LOW);    // disengage the relay
    Dumpln("relay disabled");
    vTaskDelay( 900 / portTICK_PERIOD_MS ); // wait for .9 second
  }
}

// setup runs once on reset/power
void setup() {

  Serial.begin(115200);
  while (!Serial) { ; } // wait for USB serial port on 32u4 boards.

  pinMode(RELAYOUTPUT, OUTPUT);
#ifndef BEAN_BEAN_BEAN_H        // Bean's tricolor LED is already initialized.
  pinMode(LED_BUILTIN, OUTPUT); // just in case UNO LED line uninitialized.
#endif

  // test and display hardware connections
  LED_ON;
  digitalWrite(RELAYOUTPUT, HIGH);
  Dumpln("everybody lit?");
  delay(2000); // 2 second nap
  LED_OFF;
  digitalWrite(RELAYOUTPUT, LOW);
  Dumpln("everybody should be unlit, RTOS schedule starts in 5 seconds...");
  delay(5000);

  // set up tasks to run independently.
  xTaskCreate(
    TaskBlink
    ,  (const portCHAR *)"Blink"   // A name just for humans
    ,  128  // This stack size can be checked & adjusted by reading the Stack Highwater
    ,  NULL
    ,  1  // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
    ,  NULL );

  xTaskCreate(
    TaskRelay
    ,  (const portCHAR *) "Relay"
    ,  128  // Stack size
    ,  NULL
    ,  1  // Priority
    ,  NULL );

  // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
}

void loop()
{
  // Empty. Things are done in Tasks.
}

This code works as expected on an UNO, but never seems to execute its tasks on a Bean+. The Bean clearly passes through the setup function, triggering both LED and relay for 2 seconds as expected, but then it never manages to execute a task.
FreeRTOS uses the AVR's Watchdog timer for scheduling. My suspicion is that the Bean may use the AVR's watchdog timer for Bean.sleep() and there's a conflict there. But their docs imply that the Bluetooth chip manages AVR sleep. From Power Management::

What wakes up Bean? What actually happens in Bean sleep is that the
  ATmega (the microcontroller running your Arduino sketch) goes fully to
  sleep. Meanwhile, the Bluetooth chip sleeps in between small periods
  of Bluetooth stack activity. This means the Bluetooth chip can wake up
  the ATmega for a variety of events:
A client connecting to Bean can wake the ATmega if Bean is configured
  for wake-on-connect A received serial message will wake the ATmega Any
  type of interrupt will wake the ATmega A common practice is to have
  Bean sleep for as long as possible using Bean.sleep(0xFFFFFFFF). This
  way, Bean will stay asleep indefinitely, and you can wake up Bean with
  a serial message or interrupt.

OTOH, this subsequent line in the Bean Docs is very suspicious, because FreeRTOS docs note that the AVR watchdog timer's granularity is 15 ms. That's an odd coincidence, I'd expect the BLE chip to have finer grained timers available, and I seem to recall the AVR chips need about 7 ms to wake from deep sleep.

Minimum Sleep Time It’s important to keep in mind that Bean.sleep()
  has a minimum sleep time of 15 ms. If you need delays under 15 ms, you
  will have to use delay or delayMicroseconds instead.

So, finally the questions:
Does the Bean sleep implementation depend upon the watchdog timer?
If so, can FreeRTOS and/or the Bean be persuaded to play nice?
If not, what might be breaking FreeRTOS in the Bean?
(And yes, I know the Beans, unsupported and (slightly) obsolete are now a poor choice for a real-time control task. But I like the Bean and Bean+, still have a few in my parts bin, and have a task that's a perfect match for the Bean. I don't blame Punchthrough for abandoning the Bean, though I do wish they'd left up, or at least archived, the user forum.)

A minor rant: I know the arduino is intended as an inexpensive gentle entry to low-power, connected computing, but it's a crime that the environment provides so little support or guidance for its natural uses: sensing, machine control, environmental reporting, etc. No builtin example I've seen shows proper interrupt management. All the timing examples use power hogging, cycle wasting, busy-wait delays. Where's the scheduler? Maybe a task queue? Libdispatch lite, anyone?
I guess the moral is: if I want it, why aren't I contributing? :( Insert usual lame excuses ):

to your comment: it wouldn't be Arduino then. you can do it all without Arduino or mixed with Arduino

@Juraj Yeah, true ... but the Arduino environment is sooo convenient :) I've done a lot of bare-metal real-time, but the setup time for new hardware, and the often-crummy dev tools, makes it tedious for hobby hackery. I'm planning to explore this as an alternative: https://platformio.org/platformio-ide

I use Eclipse plugin Sloeber. With it I can very fast solve questions like yours by 'drilling' down into source code of the core and libraries. It is like x-ray vision compared to Arduino IDE. But first I would need to install the 'bean' core.


text:
Read write with half duplex SPI
I'm currently struggling interfacing an SPI device using just 3 pins (CLK, DATA, NSS).
Wiring up? Connecting MOSI/MISO together?
How do i read since it's half duplex?
In ESP32 there are flags which can be set (SPI_TRANS_USE_RXDATA, SPI_TRANS_USE_TXDATA). How can i accomplish this in the Arduino environment? i didn't see a such option and the API seems a little bit limited.
Thanks for any advice.

All you need is a single resistor.

simulate this circuit – Schematic created using CircuitLab
When DATA is an input the data from MOSI passes through the resistor to both DATA and MISO.  When DATA is an output the data from DATA goes to MISO and voltage is dropped safely across R1 to the sink or source of MOSI depending on what state it is in.
In other words, when DATA is input it receives from MOSI. When DATA is output MOSI is ignored.
Code wise, it's no different to any other transfer. You just never have any valid data to transfer while receiving. So just transfer anything (0xFF is a common choice).
For example, if you need to send 0x38 first then receive two bytes, you would:
SPI.transfer(0x38);
uint8_t byte1 = SPI.transfer(0xFF);
uint8_t byte2 = SPI.transfer(0xFF);

Thanks, worked great! +1


text:
Problems when attaching a second ultrasound sensor (HC SR04)
I am working on an obstacle avoiding robot. It uses an ultrasound sensor to avoid obstacles, but currently has trouble avoiding objects that are diagonal to it. Thus, i want to add a second ultrasound sensor, and alternate their readings. I am testing the code, which should look right and then leftn and return the distances. The code worked for just one ultrasound.  and it is a follows:
#include <NewPing.h>
#include <Servo.h>

#define trig_pin1 A1 //analog input 1
#define echo_pin1 A2 //analog input 2
#define trig_pin2 A3 //analog input 1
#define echo_pin2 A4 //analog input 2
int distance1 = 100;
int distance2 = 100;

#define maximum_distance 200 //sensor function
Servo servo1; //our servo name
Servo servo2;
NewPing sonar1(trig_pin1, echo_pin1, maximum_distance);
NewPing sonar2(trig_pin2, echo_pin2, maximum_distance);
void setup() {
  // put your setup code here, to run once:
  servo1.attach(11); //our servo pin
  servo1.write(90);
  servo2.attach(6); //our servo pin
  servo2.write(90);

  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
}

void loop() {
    int distanceRight = 0;
  int distanceLeft = 0;

        distanceRight = lookRight();
    delay(300);
    distanceLeft = lookLeft();
    delay(300);
  }
}

int readPing1(){
  delay(10);
  int cm = sonar1.ping_cm();
  if (cm==0){
    cm=250;
  }
  return cm;
}

int lookRight(){
  servo1.write(50);
  delay(500);
  int distance1 = readPing1();
  delay(100);
  servo1.write(115);
  return distance1;
}

int readPing2(){
  delay(10);
  int cm = sonar2.ping_cm();
  if (cm==0){
    cm=250;
  }
  return cm;
  }
int lookLeft(){
  servo2.write(170);
  delay(500);
  int distance2 = readPing2();
  delay(100);
  servo2.write(115);
  return distance2;
  delay(100);
}

I get the following error:
'readPing1' was not declared in this scope

and I get the same error for the readPing2 function. Why could this be?

tip: you can simplify your code by using if (cm==0) cm=250;

It turns out I had an extra "}" after the void loop function. The code worked as expected after removing it


text:
How can i stop DC motor when button on remote is released?
I am trying to control a motor using a remote with Arduino Mega. The motor turns on when I press the button on the remote but when I release the button, it continues to move. Does anyone know how to stop the motor spinning when I release the button on the remote?

IR remote? Those generally don't have the concept of button release.

do you actually have code to turn the motor off?   .... a lot of people assume that if the motor turns on when a button is pressed, that it will magically turn off when the button is released

share you sketch here.

You won't get answer more precise than Majenko's, until you share the code in question. Though it is a good answer.

For an infra-red remote control you generally can't. Those don't normally have the concept of button release.
Normally there are two kinds of buttons on a remote:

Burst code
Repeat code

The first sends a short burst of the same code. This allows for a function to be run once per button press.  The second sends the same code over and over again constantly until you release it.
For the repeat code buttons you can use that to your advantage.  You program your Arduino to run the motor for a short period. That period needs to be slightly longer than the time between each code reception. Then it can appear that it's responding to the release of the button.
For example, if your remote sends codes 5 times per second then whenever you receive a code you start the motor. If you haven't received a code for more than say 300ms then stop the motor.


text:
How to generate musical notes using an uno without using tone() function? Can anyone share the embedded c language code for it?
I also want to know how can we make it without functions like digitalwrite

read this https://www.arduino.cc/en/Reference/PortManipulation

but then it is not Arduino, if you don't use Arduino functions and the question is off-topic

I don't see what is off-topic about it, if he has an Arduino and wants to make it do stuff. Surely he doesn't necessarily have to use the Tone library, or necessarily do digitalWrite? Ultimately every library will eventually use the hardware registers, and you wouldn't say that the libraries are off-topic, would you?

@NickGammon, OP wants an AVR C program with main() (embedded C language code) and it looks like an assignment from school. If I write the low level part of an Arduino library I use the underlying technology which is not Arduino and if it is AVR and I have a question about it, I go to avrfreaks forum

Perhaps you are right about the assignment, but there is nothing inherently bad about helping people to enlightenment. :)

Yes, that's easy enough to do. I wrote a library to do that, as described here.
Basically you could make a class like this:
class TonePlayer
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const timerRegA_;
  volatile byte * const timerRegB_;
  volatile byte * const timerOCRH_;
  volatile byte * const timerOCRL_;
  volatile byte * const timerTCNTH_;
  volatile byte * const timerTCNTL_;

  public:
    // constructor
    TonePlayer (
          // ports
          volatile byte & timerRegA,
          volatile byte & timerRegB,
          volatile byte & timerOCRH,
          volatile byte & timerOCRL,
          volatile byte & timerTCNTH,
          volatile byte & timerTCNTL)
       :
         timerRegA_  (&timerRegA),
         timerRegB_  (&timerRegB),
         timerOCRH_  (&timerOCRH),
         timerOCRL_  (&timerOCRL),
         timerTCNTH_ (&timerTCNTH),
         timerTCNTL_ (&timerTCNTH)
  { }

    void tone (const unsigned int Hz);
    void noTone ();

  };  // end of TonePlayer

Then implement the two functions like this:
void TonePlayer::tone (const unsigned int Hz)
{
  // it takes two toggles for one "cycle"
  unsigned long ocr = F_CPU / Hz / 2;
  byte prescaler = _BV (CS10);  // start with prescaler of 1  (bits are the same for all timers)

  // too large? prescale it
  if (ocr > 0xFFFF)
    {
    prescaler |= _BV (CS11);    // now prescaler of 64
    ocr /= 64;
    }

  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;

  // reset counter
  *timerTCNTH_ = 0;
  *timerTCNTL_ = 0;

  // what to count up to
  *timerOCRH_ = highByte (ocr);
  *timerOCRL_ = lowByte (ocr);

  *timerRegA_ = _BV (COM1A0);             // toggle output pin
  *timerRegB_ = _BV (WGM12) | prescaler;  // CTC
  }  // end of TonePlayer::tone

void TonePlayer::noTone ()
  {
  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;
  } // end of TonePlayer::noTone

And now call it:
TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (220);  // 220 Hz
  delay (500);
  tone1.noTone ();

  tone1.tone (440);
  delay (500);
  tone1.noTone ();

  tone1.tone (880);
  delay (500);
  tone1.noTone ();
  }

void loop() { }

In this example you plug your speaker into D9 (digital pin 9) on your Uno, with the other pin going to ground. Since this plays tones using the hardware timers you can do other things in your loop without affecting the tones.

from Atmega328 datasheet TCNT1 = 0x1FF; " Note that when using “C”, the compiler handles the 16-bit access"

Ah yes, I might have been overly cautious there.

I made a 13 note piano-like (well, more organ-like) tones instrument here
https://forum.arduino.cc/index.php?topic=179761.0
Youtube clip of it in action
https://www.youtube.com/watch?v=4c8idXN4Pg0
Only 8 notes in the clip, that was all the buttons I had at the time.
I used a '1284P processor instead of '328P so it could have 13 inputs & 13 outputs, without jumping up to a 2560.
There is nothing wrong with using Direct Port Manipulation in the Arduino IDE environment. Arduino is just C++ with some things made easier for the user with functions, macros, etc.
Here's the code.
/* Crossroads, 26 July 2013
 test for creating multiple simultaneous notes using micros()
 press a key, get a note. Use external analog mixer (summing op amp) for sound mixdown to single output to a speaker
 need a higher pin count device - this code is for '1284P - with specific pin mappings, not written for uC portability
 play 13 notes for now, C4 up to C5
 note info from http://www.sengpielaudio.com/calculator-notenames.htm
 Input keys: pin2=C4, 3=C#4, 30=D4, 8=D#4, 9=E5, 31=F5, 4=F5#, 5=G5, 6=G5#, 7=A5, 10=A5#, 11=B5, 12=C5
 Output notes: pin 16=C4, 17=C#4, 18=D4, 19=D#4, 20=E5, 21=F5, 22=F5#, 23=G5, 24=G5#, 25=A5, 26=A5#, 27=B5, 28=C5
 Ordering is funny due to Bobuino mapping, and having PortA output bits follow portD input bits, portC output bits follow portB input bits
 0,1 reserved for serial
 13,14,15,29, unused, maybe make 1 of 9 octave select? Piano has 7 full C to B octaves, 2 partials
 */
// array of 1/2 period of the notes in microseconds
// so a C8 note would be 119uS High, 119uS low for example
unsigned long noteArray[] = {
  119, // C8, highest note - note 0
  127,134,142,150,159,169,179,190,201,213,225,239, // B7, A#7,A7, G#7, G7, F#7, F7, E7, D#7, D7, C#7, C7 - notes 1-12
  253,268,284,301,318,338,356,379,402,426,451,478, //  B6 down to C6 - notes 13-24
  506,536,568,602,638,676,716,758,804,851,902,965, // B5 down to C5 - notes 25-36
  1012,1073,1136,1204,1276,1351,1432,1517,1607,1703,1804,1911, // B4 down to C4 - notes 37-48
  2025,2145,2272,2408,2551,2703,2863,3034,3214,3405,3607,3822, // B3 down to C3 - notes 49-60
  4050,4290,4545,4816,5102,5405,5727,6067,6428,6810,7215,7645,  // B2 down to C2 - notes 61-72
  8099,8581,9091,9631,10204,10811,11454,12135,12856,13621,14431,15289,  //  B1 down to C1 - notes -73-84
  16198,17161,18182, // B0, A#0, A0 - 85-86-87
};  // really need to flip this whole thing over so that 0 is lowest note & 87 is  highest
byte keyArray[]={
  2,3,30,8,9,31,4,5,6,7,10,11,12,13,}; //Ports D2,D3,D4,D5,D6,D7,B0,B1,B2,B3,B4,B5,B6, added b7 - notes 48, 47,46,45,44,43,42,41,40,39,38,37,36
byte outputArray[] = {
  14,15,16,17,18,19,22,23,24,25,26,27,28, 21,22,29}; // Ports A0,A1,A2,A3,A4,A5,C0,C1,C2,C3,C4,C5,C6, added a6, a7, c7
// ports selected for consistency for bits used from input to output from D in to A out, and B in to C out
byte keyActive[]= {
  0,0,0,0,0,0,0,0,0,0,0,0,0,}; // 1 indicates key is pressed
//byte octaveSelect[] = {
// 13,21,22,29}; // b7,a6,a7,c7 -  0 to 9 - future use
// ATMEL ATMEGA1284P on Bobuino
//
//                       +---\/---+
//           (D 4) PB0 1 |        | 40 PA0 (D 21) AI 7
//           (D 5) PB1 2 |        | 39 PA1 (D 20) AI 6
//      INT2 (D 6) PB2 3 |        | 38 PA2 (D 19) AI 5
//       PWM (D 7) PB3 4 |        | 37 PA3 (D 18) AI 4
//   PWM/SS (D 10) PB4 5 |        | 36 PA4 (D 17) AI 3
//     MOSI (D 11) PB5 6 |        | 35 PA5 (D 16) AI 2
// PWM/MISO (D 12) PB6 7 |        | 34 PA6 (D 15) AI 1
//  PWM/SCK (D 13) PB7 8 |        | 33 PA7 (D 14) AI 0
//                 RST 9 |        | 32 AREF
//                VCC 10 |        | 31 GND
//                GND 11 |        | 30 AVCC
//              XTAL2 12 |        | 29 PC7 (D 29)
//              XTAL1 13 |        | 28 PC6 (D 28)
//      RX0 (D 0) PD0 14 |        | 27 PC5 (D 27) TDI
//      TX0 (D 1) PD1 15 |        | 26 PC4 (D 26) TDO
// INT0 RX1 (D 2) PD2 16 |        | 25 PC3 (D 25) TMS
// INT1 TX1 (D 3) PD3 17 |        | 24 PC2 (D 24) TCK
//     PWM (D 30) PD4 18 |        | 23 PC1 (D 23) SDA
//      PWM (D 8) PD5 19 |        | 22 PC0 (D 22) SCL
//      PWM (D 9) PD6 20 |        | 21 PD7 (D 31) PWM
//                       +--------+
//
byte x;
byte portDkeys;
byte portBkeys;
byte portAnotes;
byte portCnotes;
unsigned long currentTime;
unsigned long changeTime[]= {
  0,0,0,0,0,0,0,0,0,0,0,0,0,}; // track when to flip output
unsigned long duration;
/* consistency check
 INDEX, NOTE, port In, port Out
 0, C4,       D2, A2           read 04 write 04 FB 1111 1011 Middle C
 1, C#4,      D3, A3           read 08 write 08 F7 1111 0111
 2, D4,       D4, A4           read 10 write 10 EF 1110 1111
 3, D#4,      D5, A5           read 20 write 20 DF 1101 1111
 4, E4,       D6, A6           read 40 write 40 BF 1011 1111
 5, F4,       D7, A7           read 80 write 80 7F 0111 1111
 6, F#4,      B0, C0           read 01 write 01 FE 1111 1110
 7, G4,       B1, C1           read 02 write 02 FD 1111 1101
 8, G#4,      B2, C2           read 04 write 04 FB 1111 1011
 9, A4,       B3, C3           read 08 write 08 F7 1111 0111  Concert A
 10, A#4,     B4, C4           read 10 write 10 EF 1110 1111
 11, B4,      B5, C5           read 20 write 20 DF 1101 1111
 12, C5,      B6, C6           read 40 write 40 BF 1011 1111
 */
/*************/
void setup(){
  //Serial.begin (115200); // for debug testing
  for (x=0; x<14; x=x+1){ // input pins with pullup
    pinMode(keyArray[x], INPUT);
    digitalWrite (keyArray[x], HIGH);
  }
  for (x=0; x<17; x=x+1){
    pinMode(outputArray[x], OUTPUT); // output pins
  }
  //  for (x=0; x<4; x=x+1){ // future use maybe
  //    pinMode(octaveSelect[x], INPUT); // input pins with pullups
  //    digitalWrite (octaveSelect[x], HIGH);
  //  }
} // end setup

/***********/
void loop(){
  //Serial.print (" ");
  // if key is pressed, determine time for next transition
  // if key is not pressed, no transition, use AC coupling into summing op-amp for no output
  // idea is to allow multiple notes to be created simultaneoulsy. Can the reading & if's all be done fast enough?
  portDkeys = PIND; // Read the input keys - using direct port manipulation for speed
  portBkeys = PINB;
  currentTime = micros();

  // Didn't make this part of a larger loop/array lookup because that adds 12-15uS for each pass thru the loop

  /* Check if key for note C4 is pressed, key0  */

  if ((portDkeys & 0x04) == 0){ // key is pressed D2 -> A2
     if (keyActive[0]==0){
       keyActive[0] = 1;
       changeTime[0] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[0])>=noteArray[48]){ // time for a period toggle?
      changeTime[0] = changeTime[0] + noteArray[48];    // setup time for the next toggle
      PINA=0x04;  // write a 1 to PINx toggles an output bit - NickGammon to the rescue again!
    }
  }
  else{keyActive[0] = 0;}

  /* Check if key for note C#4 is pressed, key1  */

  if ((portDkeys & 0x08) == 0){ // key is pressed D3 -> A3
       if (keyActive[1]==0){
       keyActive[1] = 1;
       changeTime[1] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[1])>=noteArray[47]){
      changeTime[1] = changeTime[1] + noteArray[47];
      PINA = 0x08;
    }
  }
  else{keyActive[1] = 0;}

  /* Check if key for note D4 is pressed, key2  */

  if ((portDkeys & 0x10) == 0){ // key is pressed D4 -> A4
       if (keyActive[2]==0){
       keyActive[2] = 1;
       changeTime[2] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[2])>=noteArray[46]){
      changeTime[2] = changeTime[2] + noteArray[46];
      PINA = 0x10;
    }
  }
  else{keyActive[2] = 0;}

  /* Check if key for note D#4 is pressed, key3  */

  if ((portDkeys & 0x20) == 0){ // key is pressed D5 -> A5
       if (keyActive[3]==0){
       keyActive[3] = 1;
       changeTime[3] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[3])>=noteArray[45]){
      changeTime[3] = changeTime[3] + noteArray[45];
      PINA = 0x20;
    }
  }
  else{keyActive[3] = 0;}

  /* Check if key for note E4 is pressed, key4  */

  if ((portDkeys & 0x40) == 0){ // key is pressed D6 -> A6
       if (keyActive[4]==0){
       keyActive[4] = 1;
       changeTime[4] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[4])>=noteArray[44]){
      changeTime[4] = changeTime[4] + noteArray[44];
      PINA = 0x40;
    }
  }
  else{keyActive[4] = 0;}

  /* Check if key for note F4 is pressed, key5  */

  if ((portDkeys & 0x80) == 0){ // key is pressed D7 -> A7
       if (keyActive[5]==0){
       keyActive[5] = 1;
       changeTime[5] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[5])>=noteArray[43]){
      changeTime[5] = changeTime[5] + noteArray[43];
      PINA = 0x80;
    }
  }
  else{keyActive[5] = 0;}

  /*  Now Port B & Port C */
  /* Check if key for note F#4 is pressed, key6  */

  if ((portBkeys & 0x01) == 0){ // key is pressed B0 -> C0
       if (keyActive[6]==0){
       keyActive[6] = 1;
       changeTime[6] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[6])>=noteArray[42]){
      changeTime[6] = changeTime[6] + noteArray[42];
      PINC = 0x01;
    }
  }
  else{keyActive[6] = 0;}

  /* Check if key for note G4 is pressed, key7  */

  if ((portBkeys & 0x02) == 0){ // key is pressed B1 -> C1
       if (keyActive[7]==0){
       keyActive[7] = 1;
       changeTime[7] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[7])>=noteArray[41]){
      changeTime[7] = changeTime[7] + noteArray[41];
      PINC = 0x02;
    }
  }
  else{keyActive[7] = 0;}

  /* Check if key for note G#4 is pressed, key8  */

  if ((portBkeys & 0x04) == 0){ // key is pressed B2 -> C2
       if (keyActive[8]==0){
       keyActive[8] = 1;
       changeTime[8] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[8])>=noteArray[40]){
      changeTime[8] = changeTime[8] + noteArray[40];
      PINC = 0x04;
    }
  }
  else{keyActive[8] = 0;}

  /* Check if key for note A4 is pressed, key9  */

  if ((portBkeys & 0x08) == 0){ // key is pressed B3 -> C3
       if (keyActive[9]==0){
       keyActive[9] = 1;
       changeTime[9] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[9])>=noteArray[39]){
      changeTime[9] = changeTime[9] + noteArray[39];
      PINC = 0x08;
    }
  }
  else{keyActive[9] = 0;}

  /* Check if key for note A#4 is pressed, key10  */

  if ((portBkeys & 0x10) == 0){ // key is pressed B4 -> C4
       if (keyActive[10]==0){
       keyActive[10] = 1;
       changeTime[10] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[10])>=noteArray[38]){
      changeTime[10] = changeTime[10] + noteArray[38];
      PINC = 0x10;
    }
  }
  else{keyActive[10] = 0;}

  /* Check if key for note B4 is pressed, key11  */

  if ((portBkeys & 0x20) == 0){ // key is pressed B5 -> C5
       if (keyActive[11]==0){
       keyActive[11] = 1;
       changeTime[11] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[11])>=noteArray[37]){
      changeTime[11] = changeTime[11] + noteArray[37];
      PINC = 0x20;
    }
  }
  else{keyActive[11] = 0;}

  /* Check if key for note C5 is pressed, key12  */

  if ((portBkeys & 0x40) == 0){ // key is pressed B6 -> C6
       if (keyActive[12]==0){
       keyActive[12] = 1;
       changeTime[12] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[12])>=noteArray[36]){
      changeTime[12] = changeTime[12] + noteArray[36];
      PINC = 0x40;
    }
  }
  else{keyActive[12] = 0;}

} // end loop

Nice video! You could post your rather short code into your answer so that it doesn't totally rely on links. :) This is, after all, a completely alternative way of doing it to the one I showed (which doesn't allow multiple notes at once).

Just select the code, hit Ctrl+K (K for Kode). That indents it 4 spaces and formats it for you. I did it for you. :)

Cool! I didn't realize that could be done.  Thanks Nick!


text:
Can't get MMC3416xPJ to work
I needed a magnetometer with a high Output Data Rate (ODR). This is because I wanted to measure AC magnetic fields of around 20-80 Hz. So I decided to go with the MMC3416xPJ prototyping board which has an ODR of 800 Hz (https://au.mouser.com/new/memsic/memsic-mmc3416xpj-sensors/). I have never written an I2C interface for a sensor myself so I probably messed up. The datasheet for my sensor can be found here. I can get the product ID from the sensor correctly so that means the wiring is correct and some of the code is correct. But when I print out the measurements, they give me overflow values instead of the Earth's magnetic field. BTW I am developing this on Arduino board. Any help would be appreciated.
My code can be seen below -
Magnetometer.h

#ifndef MAGNETOMETER_H
#define MAGNETOMETER_H

#include "General.h"
#include <Wire.h>

#define MAGNETOMETER_I2C_ADDRESS 0x30
#define X_OUT_LOW 0x00
#define X_OUT_HIGH 0x01
#define Y_OUT_LOW 0x02
#define Y_OUT_HIGH 0x03
#define Z_OUT_LOW 0x04
#define Z_OUT_HIGH 0x05
#define STATUS 0x06
#define INTERNAL_CONTROL_0 0x07
#define INTERNAL_CONTROL_1 0x08
#define RO 0x1b
#define R1 0x1c
#define R2 0x1d
#define R3 0x1e
#define R4 0x1f
#define PRODUCT_ID 0x20

class Magnetometer
{
  public:
    Magnetometer();
    void Setup();
    void Test();
  private:
    void TestConnnection();
    void ReadRawData();
};

#endif

Magnetometer.cpp
#include "Magnetometer.h"

Magnetometer::Magnetometer()
{

}

void Magnetometer::Setup()
{
    Wire.begin(SDA, SCL);
    TestConnnection();

    Wire.beginTransmission(MAGNETOMETER_I2C_ADDRESS);
    Wire.write(INTERNAL_CONTROL_1);
    Wire.write(0x00);
    Wire.endTransmission();

    Serial.println("Magnetometer Setup");
}

void Magnetometer::Test()
{
    ReadRawData();
    Serial.println("Magnetometer Test");
    delay(1000);
}

void Magnetometer::ReadRawData()
{
    int16_t RawMx, RawMy, RawMz;
    byte status = -1;

    // 1-3
    Wire.beginTransmission(MAGNETOMETER_I2C_ADDRESS);
    Wire.write(INTERNAL_CONTROL_0);
    Wire.write(0x01);
    Wire.endTransmission();

    // 4-7
    Wire.beginTransmission(MAGNETOMETER_I2C_ADDRESS);
    Wire.write(STATUS);
    Wire.requestFrom(MAGNETOMETER_I2C_ADDRESS, 1);
    status = Wire.read();
    Serial.print("status = "); Serial.println(status);
    while ((status%2) != 1)
    {
        status = Wire.read();
        Serial.println("Data not ready");
    }
    Serial.println("Data ready");
    Wire.endTransmission();

    // 8-17
    Wire.beginTransmission(MAGNETOMETER_I2C_ADDRESS);
    Wire.write(X_OUT_LOW);
    Wire.endTransmission();
    Wire.requestFrom(MAGNETOMETER_I2C_ADDRESS, 6);
    RawMx = Wire.read();
    RawMx |= Wire.read()<<8;
    RawMy = Wire.read();
    RawMy |= Wire.read()<<8;
    RawMz = Wire.read();
    RawMz |= Wire.read()<<8;

    Serial.print("RawMx: "); Serial.print(RawMx);
    Serial.print(" RawMy: "); Serial.print(RawMy);
    Serial.print(" RawMz: "); Serial.println(RawMz);

    float scaleFactor = 2048;
    float convertToMircoTelsa = 100;
    float Mx, My, Mz;

    Mx = (float) RawMx / scaleFactor * convertToMircoTelsa;
    My = (float) RawMy / scaleFactor * convertToMircoTelsa;
    Mz = (float) RawMz / scaleFactor * convertToMircoTelsa;

    Serial.print("Mx: "); Serial.print(Mx);
    Serial.print(" My: "); Serial.print(My);
    Serial.print(" Mz: "); Serial.println(Mz);

    // Serial.print("Wire.ava = "); Serial.println(Wire.available());
}

void Magnetometer::TestConnnection()
{
    byte id = -1;
    while (id != 6)
    {
        Wire.beginTransmission(MAGNETOMETER_I2C_ADDRESS);
        Wire.write(PRODUCT_ID);
        Wire.requestFrom(MAGNETOMETER_I2C_ADDRESS, 1);
        id = Wire.read();
        Wire.endTransmission();

        if (id != -1)
        {
            Serial.println("Cannot connect to Magnetometer");
        }
    }
    Serial.println("Magnetometer TestConnnection Success");
}

If you guys suggest me any other magnetometers that have a high ODR (at least above 300 Hz), it would be really appreciated.

Add print-out when you run the sketch. What are the raw values?

That is not fast, that is slow, because the I2C bus is slow and the Wire.endTransmission and Wire.requestFrom are blocking functions, they wait until everything has finished. You might use Wire.setClock to set the bus to 400kHz, but a magnetometer with SPI interface avoids all these problems. Which arduino board do you use ? I see a few mistakes with the Wire functions, you have to read in the Arduino Wire reference how to use them.

@MikaelPatel I get overflow values

@Jot I am using a Wemos D1 mini which based on the Esp8266. Can you give me pointers on the mistakes I made? Thanks in advance.

@Jot Do you know where I can find a magnetometer which has an odr of above 300 Hz and uses SPI for data transfer?

The wire.endtransmission is used when writing data: https://www.arduino.cc/en/Reference/WireEndTransmission The LIS3MDL is used with arduino and has spi and i2c and 1kHz in fast_odr mode. The LSM9DS1 is also often used with arduino, has also spi and i2c and is 952Hz. I don't know if the internal circuit is also that fast, that speed is just the interface.

Perhaps a set/reset before configuring the device helps:
writeRegister(MMC34160PJ_CTRL0, 0x80);          // refill cap
delay(50);
writeRegister(MMC34160PJ_CTRL0, 0x20);          // set
//delay(10);
writeRegister(MMC34160PJ_CTRL0, 0x80);          // refill cap
delay(50);
writeRegister(MMC34160PJ_CTRL0, 0x40);          // reset
//delay(10);


text:
using two mpu6050 to get more accurate and precise angles
i have been using this gyro for a while, now i am aware of all measures taken, to improve the outcome of this board.
my question is: would using two at the same time improve the results?
if yes how to use them both?
thanks in apporch

Using two IMU on same board might not give you that same result as IMU units data depends upon placement and orientation soldered. They are advised to be soldered at the center of your board, as two IMU  can't soldered at the center of same PCB in same orientation.

@vaibhav, yes got it. it is actually not a problem since the acceleration measured is the same on all the board  (law of physics). the only reason to put the imu in the center is to avoid noise out of vibrations.

Maybe you can account for the displacement from the center by calculation. But using 2 units will only reduce some of the electrical noise in the sensors. Often a big part of noise on the gyros data comes from vibrations in the device. Let's say you are building a robot. The motors will induce vibrations, when running. These can get caught up by the gyros, depending on the positions of gyro and motor and the form of the frame. What kind of device are you building?

would you mind chrisl of you put your comment as an answer so i can accept it.

Using a Kalman filter might help here.


text:
LED brightness control problem
My first question here.
As an example, I'm using https://howtomechatronics.com/tutorials/arduino/how-to-control-ws2812b-individually-addressable-leds-using-arduino/ code to control my lighting, which I'm going to install to my car, just my code was a bit simplified, but I left the line, where brightness is being controlled and here's the fun part. When trying to change the brightness, it changes inconsistently. When increasing, it gets a bit brighter then a bit dimmer and at some spots it just turns off, when it should be bright. I'm also new to Arduino, so don't really know how Arduino reads these values, but maybe there is some other way to control brightness?
#include <SoftwareSerial.h>
#include <FastLED.h>
#define NUM_LEDS 20
#define PIN 5
CRGB leds[NUM_LEDS];
int brightness = 155;
//int fadeAmount = 5;
SoftwareSerial BT(0,1);
String dataIn = "";

void setup() {

  FastLED.addLeds<WS2811, PIN, GRB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness(brightness);
  Serial.begin(9600);
  BT.begin(9600);
  setAll(50, 50, 50);
}

void loop() {

  if (BT.available() > 0) {
    dataIn = BT.readString();
    delay(10);
    FastLED.show();
  }
    if (dataIn.startsWith("0")) {
        setAll(0,0,0);
        delay(10);
    FastLED.show();
    }
    else if (dataIn.startsWith("w")) {
        setAll(255,255,255);
        delay(10);
    FastLED.show();
    }
    else if (dataIn.startsWith("r")) {
        setAll(0,255,0);
        delay(10);
    FastLED.show();
    }
    else if (dataIn.startsWith("g")) {
        setAll(255,0,0);
        delay(10);
    FastLED.show();
    }
    else if (dataIn.startsWith("b")) {
        setAll(0,0,255);
        delay(10);
    FastLED.show();
    }
    else if (dataIn.startsWith("y")) {
        setAll(200,255,0);
    }
    else if (dataIn.startsWith("1")) { //This is the brightness lines
      String stringBrightness = dataIn.substring(dataIn.indexOf("1") + 1);
      brightness = stringBrightness.toInt();
      FastLED.setBrightness(brightness);
      FastLED.show();
    }
  }

void showStrip() {
   FastLED.show();
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
   leds[Pixel].r = red;
   leds[Pixel].g = green;
   leds[Pixel].b = blue;
}

void setAll(byte red, byte green, byte blue) {
  for(int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  showStrip();
}

A couple of comments: 1) why are you using a software serial? If you use pins 0 and 1 use the hardware serial, otherwise if you must use other pins set them correctly. 2) Are you saying that even if you are setting all the leds to the same color some of them have different brightness than the other? It seems to me this is a power supply issue rather than a control one.. Are all the LEDs the same ones, from the same strip?

@frarugi87 I guess it would be best to make a short video to show what I mean, because I dont know how to say that for everyone to understand correctly. I'll put a link later today, because now I have to go to work.

Using BT.readString() is asking for trouble, as the result is dependent on the timing of the serial data stream. Try using linefeed delimited commands instead.

For sure use the hardware serial rather then software serial, but before you even mess with getting the serial figured out, make sure the LED's work as you expect.  In the setup function do something like:    setAll(255,0,0); delay(1000);setAll(128,0,0);delay(1000);setAll(10,0,0); delay(1000);    Does this make them all start out bright red and then go half bright and then very dim or off?  If this is not producing the expected results then you need to work on that.  Once you can make it work as you want by directly coding it that way, then introduce the ability to control it via commands.

Another gotcha: I assume \these LEDs use PWM to get different brightness levels for each color channel. If the cycle rate is slow enough, the pulsing of the LEDs can create strange light trail effects when the light source is moving across the field of view of the observer. You can see this effect if you take an LED calculator and sweep it rapidly across your field of view. Very high frequency PWM usually solves the problem, but since these are LEDs that are controlled using a serial interface (I2C?) you likely don't have any control over the PWM frequency used to drive them.

youtu.be/WcQ11pYzJnc So here's the video. @ChadG Yes, that works and it starts bright, then dimmer and then very dim.

@EdgarBonet maybe that why there's that delay between commands? because if I press some colors faster it chooses just the first one that was pressed.

@frarugi87 to answer your question why I use software serial, because I haven't learn't any coding before and this is my start, so I even didn't knew of hardvare serial


text:
Increasing speed of Vl6180x Sensors
I have 5x vl6180x pololu ToF sensors. I have managed to hook up all of the sensors to the arduino via I2C by making each sensor startup at different times and when they do, changing their addresses, but while I can quite easily read them, they take a very long time, 50ms - 300ms. I'm using the Pololu VL6180x library and when I've investigated the library, I couldn't find any delays in the code. I have also tried to change the clock rate of I2C to 400kHz, but that didn't seem to affect the speed. The datasheet of the sensors says that a sensor might take ~63ms to respond, but is there any way to make it faster? If not, can I read the sensors with the AtTiny13A and send the data from each chip to arduino? Which protocol should i use to communicate with them, if i want to read their measured distance?
Ps. I'm making a robot which needs to move fast and react quickly to each sensor. (11 of sensors in total, none, except ToF are I2C)

You can use startRangeContinuous and readRangeContinuous to have the sensor continuously measuring the distance, negating the need to wait for the sensor to do a measurement.
Using readRangeSingle will start a single measurement, and this function will just sit there waiting for the measurement to be done, after which it will return the result.

Well, i have just tried it out, it seems that the sensors speed barely changes(remains ~60ms when it doesn't see anything and ~20ms when it does) and it keeps crashing every 5 seconds, stopping me from reading it more.

@PotatoMan Maybe it's crashing because 400kHz is too fast for your setup. Is it on a breadboard? Those usually have a relatively high capacitance. If that's the case you could try to decrease your pullup's resistance.

@SimSon I'm doing it all on a breadboard and tried it out with 10kHz to no avail, but nevertheless i can get a few raw readings and i can see, that, when reading those values, the timing still stays around 10ms - 60ms..

Without seeing the code, I can't really help.


text:
Spi based pin expander for Arduino
I don't have enough pins on my Esp32 board. I would like to use a pin expander. All the ones I could find online only use i2c. Are there ones available that use SPI?
I would like send pwm signals to the pin expander outputs. Is that possible?

Pin extenders for when you don't have enough pins on your board.

@Juraj what do you call this https://www.microchip.com/wwwproducts/en/MCP23S17

@Juraj I need to use the pins simultaneously. Multiplexers can only output through one pin at a time.

@NadimAhmed I do those chips in pairs on a breakout board: https://majenko.co.uk/expander32.php

@NadimAhmed The MCP23017 GPIO expander chips are digital only; ie., they can NOT do PWM.

@stevieb thanks for letting me know.

Here you go https://www.microchip.com/wwwproducts/en/MCP23S17. Found it. I am gonna leave this here in case anyone needs it.

I assume you will still have problems sending "pwm signals to these pin extender pins"


text:
How can I rewrite Arduino Code using SPI library into C++?
The issue is that I have code using an Arduino library and need to convert it into C++ so I can use it with a raspberry pi on ROS (Robot operating system). Does anyone know the best way to change it over or know of good resources?
I know that Arduino is essentially C++ but I am uncertain about how to make Arduino libraries into C++.

Arduino libraries already are C++.

Thank you! So I do not need to rewrite anything to use Arduino code in C++? Or do I just need to call the library differently?

Depending on the library you may need to reimplement standard Arduino API calls, like digitalWrite, etc. Or just implement your own copies of whatever functions are needed using whatever ROS provides.

The Arduino API is just a collection of C++ functions and classes. If a library needs one of those functions or classes then just implement it (if ROS doesn't already provide it. No idea what or who ROS is).

Ok, that helps. I am trying to get a grasp on the differences between Arduino and generic C++. (ROS is Robot Operating system and works only on Linux so Arduino doesn't work with it so I am transforming code to work with it on a Rasberry pi).

The sometimes-called "Arduino Language" is C++, but with some upfront work - primarily supplying file inclusions - done for you if you don't.
The Arduino compiler is a GNU C++ compiler. If you write or supply standard C++ to the Arduino IDE, it will compile it.

The Arduino compiler is a GNU C++ compiler HOWEVER there is no c runtime library (which is not part of the compiler).
Probably more significant to the question is that the Arduino compiler supplies support for the ATMEL hardware. This is incompatible with the Raspberry Pi.
The Arduino is a real time microcontroller and has unrestricted access to its hardware, the Pi usually runs a multi-tasking OS, the hardware is not directly accessible from user space, so many tasks need to be written differently; often this means relying on a OS supplied kernel driver.
Any practicable Arduino program would require extensive changes to work on the Raspberry Pi. The effort involved is likely to be more than writing a Raspberry Pi program from scratch.


text:
Problems with Serial.read()
void loop()
{
  if (sensor.begin() == true)
  {
    Serial.print("Current Conversion Mode: ");
    Serial.println(sensor.getConversionMode());
    Serial.println("Enter your mode of Conversion (number 0 - 3): ");
    while (Serial.available() == 0); // Waits for the user input
    mode = Serial.read(); // Reads the input string from serial port
    Serial.print("Number recieved: ");
    Serial.println(mode);
    delay(500);
    if (mode == '0' | mode == '1' | mode == '2' | mode == '3')
    {
      sensor.setConversionMode(mode);
      Serial.println();
      delay(500);
    }
    else
    {
      Serial.println("Conversion mode unsuccessfully set - Please enter a number 0 - 3");
    }
    delay(1000);
  }
  else // Runs when the device was unable to setup properly
  {
    Serial.println("Device failed to setup");
  }
}

I'm currently using the SparkFun red board to run this code on. I have been trying to get this to read from the serial monitor to take an input to send to the library I wrote to change the value of the conversion mode register of a temperature sensor. When I run the code, I can only have it run once correctly, then it jumps directly to the else statement for the inputs, saying that 0-3 was not an input. I tried the other methods that people have suggested  from this website and the Arduino forums but none of them have worked for me yet. I'm not sure if adding more delays would help - that was one of the most common suggestion I found for this specific issue and it wasn't that consistent. Please help! Thanks.

What does your "Number received:" tell you when it fails?

When it fails it has a 0 value, but before sometimes I was getting -1.

What data type is mode?

Mode has the data type of char. I have it declared as a global variable above the loop

Tested it with a dummy implementation of sensor. Works as expected. The problem must be in a part of the code you are not showing.

@EdgarBonet I really wonder how this code can run as expected. | is not the operand for OR. Also, mode is byte but he compares with a char. I guess there is a chance to find the error in the provided code.

@SimSon: You are right that | should be ||, but they turn out to be equivalent as long as their operands are both either 0 or 1. And mode is char according to the OP's comment.

@SimSon thank you for the catch on that- I will change that now

Using a slightly modified version of your sketch, I receive the following output in the serial monitor when I enter the number 2.

Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved: 2
Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved:
Conversion mode unsuccessfully set - Please enter a number 0 - 3
  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved:
Conversion mode unsuccessfully set - Please enter a number 0 - 3
  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):

If you change mode to an int then retest, you'll see the second and third "Number recieved" are 10 and 13. That would be the New Line and Carriage Return characters. When you send data via the serial monitor, do you have "No Line Ending" selected or something else?
Here is a test sketch:
char mode;

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

void loop()
{
  if (true)
  {
    Serial.print("Current Conversion Mode: ");
    //Serial.println(sensor.getConversionMode());
    Serial.println("Enter your mode of Conversion (number 0 - 3): ");
    while (Serial.available() == 0); // Waits for the user input
    mode = Serial.read(); // Reads the input string from serial port
    Serial.print("Number recieved: ");
    Serial.println(mode);
    delay(500);
    if (mode == '0' | mode == '1' | mode == '2' | mode == '3')
    {
      //sensor.setConversionMode(mode);
      Serial.println();
      delay(500);
    }
    else
    {
      Serial.println("Conversion mode unsuccessfully set - Please enter a number 0 - 3");
    }
    delay(1000);
  }
  else // Runs when the device was unable to setup properly
  {
    Serial.println("Device failed to setup");
  }
}

Thank you for the suggestion, it worked! I just changed the the value to an int and then changed the serial monitor to "No Line Ending" and it worked. I never changed that setting before or really realized it was there. Thanks again!


text:
Include guards vs #pragma once
Is there any particular reason why #pragma once doesn't seem to be used in Arduino code? Is this just because it's not a well-known feature, or is there some overriding reason to use #ifndef XXX_H/#define XXX_H/#endif?

Might be that part of the Arduino core source code is older than #pragma once. Which is by the way non-standard. It was introduced in GCC 3.4.

#pragma once is not a standard feature.

Non-standard but damn useful. Would be wise to consider adding support for it.

all #pragmas are non-standard by definition. However, I started using them in about 1986 in various C compilers and it seemed pretty ubiquitous even then. I guess I'm surprised that's not the case in the C++ world.

#pragma once operates on the absolute filename of a file. Include guards work on the content of the file.
If you have multiple copies of the same library (maybe one library has some parts of another included in it - it happens...) #pragma once would have no hope of working right.
Add to that the fact that the Arduino IDE copies some files around the place when building and '#pragma once is pretty much screwed.
Include guards work regardless. So sensible people use include guards and shun #pragma once.


text:
Is there an alternative to soldering to connect boards?
I know that shields are usually soldered to headers so they can be attached to the board with the Arduino. I have a tremor, which makes soldering impossible. Are there ways of connecting PCBs without soldering?
If a concrete example would be helpful, I would like to connect the Adafruit WINC1500 WiFi Shield to a SparkFun RedBoard.

Sparkfun has a lot of sensor boards that use their Qwiic Connect System. Those you can just plug in, and even chain together, with their cables with JST connectors.
Adafruit has their Flora like of products. Mostly tailored to wearables, but with their large connector pads, you can easily connect the board to the sensors wit alligator clips.

It seems to be standard for header pins to not be soldered in, but added separately, in breakouts and shields. You could go to a local maker-space. Those people tend to be more than happy to help solder in a few headers.

Yes, there are ways. There is a system called "Press Fit" where the pins have a bulge in one end of them. This grips the inside of the holes in place of soldering.
A number of companies make them, such as TE Connectivity and Positronic.
Of course, these depend on the holes being just the right size, and finding the right connectors could be tricky... so... your mileage may vary.
But nothing is better than getting someone to solder the pins for you. You could teach one of your younger relatives to solder, for example...

Interesting. I hadn't heard of Press Fit. Thanks for teaching me something new. (voted)

Thank you! I probably will have someone do the soldering for me, but I want to understand the full solution space.

Boards with headers can be connected using jumper wires or hookup wire. If there are no headers then I don't think you will be able to get a reliable connection without soldering.
The RedBoard you linked to uses headers, so you should be able to use jumpers with it, but I suspect you are out of luck with the WiFi shield. You'll probably either need to find a version that is built using headers or ask/hire somebody to solder headers onto it for you.
As for the center portion of the shield you should probably just skip that part and use a breadboard, which uses jumpers or hook-up wires.


text:
How to control motor in trapezoidal manner using arduino
I am Working on a project in that i have to control motor in a Trapezoidal motion profile. on Y-axis is the velocity and X- axis as a time.
Velocity increases linearly for a certain time, then constant velocity for certain time and then Linearly decreasing the velocity and stop the motor

What kind of motor? Step motor? DC brushed? Does it have an optical encoder? How much non-linearity can you tolerate on the acceleration profile?

It is a BLDC motor, With 3000 PPR Optical Encoder. And i just want a trapezoidal motion, after that i can tweak accordingly

Hint: Start by trying to write this from an API point of view. What library function(s) are you looking for? How would you like to express this in a sketch?


text:
16x2 lcd lighting up blue but not showing any text
i should probably start off by saying i am really new to this stuff and have barely any idea what i'm doing. i am triyng to use a DHT22 and a 16x2 LCD to show the temperature and humidity. here is the code i'm using:
#include <DHT.h>
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

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

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

void setup()
{
  Serial.begin(9600);
  dht.begin();
  lcd.begin(16,2);
}

void loop()
{

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

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Temp: ");
  lcd.print(temp);
  lcd.print(" ");
  lcd.print((char)223);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("Hum:  ");
  lcd.print(hum);
  lcd.print(" %");

  delay(2000); //Delay 2 sec.

}`

is it an issue with my code or my hardware? thanks

start by running an LCD example sketch with only the LCD connected

You must use D0-D3 as data lines as you are using 8-bit LCD in 4-bit format

You need to set the correct contrast on these displays. Try turning the potentiometer (connected to pin 3 / VE)  till you see text/blocks appear.

You haven't told us what did you obtained? Anything on LCD? Can you make a clear photo of your hardware setup?


text:
My webswerver works fine when there is only 1 servo used/defined in my code
I am trying to make a webserver which controls my 3 servos for a robotic arm. When I define and use 1 servo it is nice and quick, but whereas if I use more than 1 the webserver is very slow and barely loads. Someone please help.
I will post the code below. With this code the webserver is very slow:
#include <Ethernet.h>
#include <SPI.h>
#include <Servo.h>
String readString;
Servo robotservo1;
Servo robotservo2;

byte mac[] = { 0x2C, 0xF7, 0xF1, 0x08, 0x29, 0xAF };
byte ip []={10,1,1,121};// check back of your shield
   // when the shield connected the serioal monitor will display the ip address
EthernetServer server(80);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
 Ethernet.begin(mac, ip);
server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());// prints my IP address, so you can copy paste in browsr

robotservo1.attach(9);
robotservo2.attach(10);

robotservo1.write(45);
robotservo2.write(45);

}

void loop() {
  // put your main code here, to run repeatedly:
EthernetClient client = server.available();
if (client) {
if (client.connected()){
  if (client.available()) {
  char c = client.read();
  if (readString.length() < 100) {
          readString += c;
        }
  if (c == '\n') {
          Serial.println(readString);
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<hmtl>");
          client.println("");
client.println("<title>Ethernet shield, hopefully works</title>");
client.println("");
client.println("<title>");
client.println("Control the robotic arm using the buttons below");
client.println("</title>");
client.println("");
client.println("");
client.println("<meta http-equiv=\"refresh\" content=\"4\">");
client.println("");
client.println("Control the robotic arm by pressing the buttons below!!!");
client.println("");
client.println("");
client.println("
");
client.println("Servo 1 or Base");
client.println("
");
client.println("<FORM>");
client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?baseserv0\'>");
client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?baseserv45\'>");
client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?baseserv90\'>");
client.println("</FORM>");
client.println("
");

client.println("
");
client.println("Servo 2 or Elbow");
client.println("
");
client.println("<FORM>");
client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?elbowserv0\'>");
client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?elbowserv45\'>");
client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?elbowserv90\'>");
client.println("</FORM>");
client.println("
");

client.println("
");
client.println("Servo 3 or Shoulder");
client.println("
");
client.println("<FORM>");
client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?shoulderserv0\'>");
client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?shoulderserv45\'>");
client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?shoulderserv90\'>");
client.println("</FORM>");
client.println("
");

client.println("");
client.println("");
client.println("");

 delay(1);

  if(readString.indexOf("?baseserv0") >0)
            {
              robotservo1.write(0);
            }

          else{
            if(readString.indexOf("?baseserv45") >0)
            {
              robotservo1.write(45);
            }

          else{
            if(readString.indexOf("?baseserv90") >0)
            {
              robotservo1.write(90);
            }

  }

}

  if(readString.indexOf("?baseserv0") >0)
            {
              robotservo2.write(0);
            }

          else{
            if(readString.indexOf("?elbowserv45") >0)
            {
              robotservo2.write(45);
            }

          else{
            if(readString.indexOf("?elbowserv90") >0)
            {
              robotservo2.write(90);
            }

  }

}

  readString="";
          client.stop();
  }}}}}

you code is hard to read because it is formatted badly ... please correct the indentation ... for instance, all of the if statements should be indented to the same level ... also, the client.println() should all be equally indented

stop the client before handling motors. and some reading https://github.com/jandrassy/StreamLib/blob/master/README.md

I have no Ethernet board so I couldn't test the timings, but when I compiled your code for an Uno, I got a low free-memory warning; that 83% of memory was used and stability problems could occur. That's the compiler telling you that your code might not run right. It may very well be the reason your server was slow. The largest user of data-memory (SRAM) is the text in your client.print() statements.
I put that text into program-memory (Flash, of which there is over 10x as much!) which got the SRAM use down to 29%! Try running that and see if it won't behave a little bit better:
#include <Ethernet.h>
#include <SPI.h>
#include <Servo.h>
String readString;
Servo robotservo1;
Servo robotservo2;

byte mac[] = { 0x2C, 0xF7, 0xF1, 0x08, 0x29, 0xAF };
byte ip [] = {10, 1, 1, 121}; // check back of your shield
// when the shield connected the serioal monitor will display the ip address
EthernetServer server(80);

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Ethernet.begin(mac, ip);
   server.begin();
   Serial.print("server is at ");
   Serial.println(Ethernet.localIP());// prints my IP address, so you can copy paste in browsr

   robotservo1.attach(9);
   robotservo2.attach(10);

   robotservo1.write(45);
   robotservo2.write(45);

}

void loop() {
   // put your main code here, to run repeatedly:
   EthernetClient client = server.available();
   if (client) {
      if (client.connected()) {
         if (client.available()) {
            char c = client.read();
            if (readString.length() < 100) {
               readString += c;
            }
            if (c == '\n') {
               Serial.println(readString);
               client.println(F("HTTP/1.1 200 OK"));
               client.println(F("Content-Type: text/html"));
               client.println();
               client.println(F("<hmtl>"));
               client.println(F(""));
               client.println(F("<title>Ethernet shield, hopefully works</title>"));
               client.println(F(""));
               client.println(F("<title>"));
               client.println(F("Control the robotic arm using the buttons below"));
               client.println(F("</title>"));
               client.println(F(""));
               client.println(F(""));
               client.println(F("<meta http-equiv=\")refresh\" content=\"4\">"));
               client.println(F(""));
               client.println(F("Control the robotic arm by pressing the buttons below!!!"));
               client.println(F(""));
               client.println(F(""));
               client.println(F("
"));
               client.println(F("Servo 1 or Base"));
               client.println(F("
"));
               client.println(F("<FORM>"));
               client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?baseserv0\'>"));
               client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?baseserv45\'>"));
               client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?baseserv90\'>"));
               client.println(F("</FORM>"));
               client.println(F("
"));

               client.println(F("
"));
               client.println(F("Servo 2 or Elbow"));
               client.println(F("
"));
               client.println(F("<FORM>"));
               client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?elbowserv0\'>"));
               client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?elbowserv45\'>"));
               client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?elbowserv90\'>"));
               client.println(F("</FORM>"));
               client.println(F("
"));

               client.println(F("
"));
               client.println(F("Servo 3 or Shoulder"));
               client.println(F("
"));
               client.println(F("<FORM>"));
               client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?shoulderserv0\'>"));
               client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?shoulderserv45\'>"));
               client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?shoulderserv90\'>"));
               client.println(F("</FORM>"));
               client.println(F("
"));

               client.println(F(""));
               client.println(F(""));
               client.println(F(""));

               delay(1);

               if (readString.indexOf("?baseserv0") > 0)
               {
                  robotservo1.write(0);
               }

               else {
                  if (readString.indexOf("?baseserv45") > 0)
                  {
                     robotservo1.write(45);
                  }

                  else {
                     if (readString.indexOf("?baseserv90") > 0)
                     {
                        robotservo1.write(90);
                     }

                  }

               }

               if (readString.indexOf("?baseserv0") > 0)
               {
                  robotservo2.write(0);
               }

               else {
                  if (readString.indexOf("?elbowserv45") > 0)
                  {
                     robotservo2.write(45);
                  }

                  else {
                     if (readString.indexOf("?elbowserv90") > 0)
                     {
                        robotservo2.write(90);
                     }

                  }

               }

               readString = "";
               client.stop();
            }
         }
      }
   }
}


text:
Can I solder wall cord directly to servo?
I have a servo which requires 7.4v and a wall power cord which says the output is 7.4v but the connector does not fit that of the servo. Is it safe to snip off the end of the wall cord and solder the internal wires directly to the servo?

would you have asked this question if the connector fit?

@jsotola - no, I would assume using the products as designed is probably safe.

First choice: Attach compatible, polarized connectors to both pigtails.
Alternatively, you can solder it up but the result is certainly less convenient to use. I like heat-shrink tubing for insulating wire-to-wire solder joints, one over each solder joint and a third, slightly larger one over both. (My favorite way to screw this up is to forget to push all three shrink tubes over the wires before I solder the joints. :)

Yeah, i also like it when I forget to put on the heat-shrink before soldering. Makes me feel really clever.


text:
About ATmega32 event system
From my reading on internet i found that the Event system allows peripherals to trigger each other without involving the CPU...does the event system is software or hardware?also does ATmega32 support it? also can any one give me a real application for event system?

Where did you read this? Can you provide a link?

@NickGammon https://www.microchip.com/design-centers/8-bit/peripherals/core-independent/event-system

The Atmega32 is not listed in the device list for the event system, that is on that site

@chrisl could you give me some example for event system?

Which Arduino are you using? This question might be better put to the AVR Freaks web site as it doesn't seem to directly involve any Arduino as such.

@NickGammon I don't use arduino..I use Atmega32

The 'old' ATmega 8 bit microcontrollers don't have an event system peripheral. The new "megaAVR 0 series" has an event system. Atmega 4809 on Arduino Uno WiFi Rev2 and on Nano Every is "megaAVR 0-series". The event system of the new ATmegas is similar to SAMD event system I know.
ARM MCUs for example SAMD by Atmel/Microchip used in Arduino Zero and MKR have an event system. Event system is a MCU peripheral. It enables direct communication between peripherals without the involvement of the CPU of the MCU.
The MCU peripherals are what makes the MCU a MCU. Examples of peripherals are GPIO pins, external interrupts, timers, SERCOM, watchdog...
To give you an example of use of the event system. To perform AC phase cutting with a Triac the Triac must be pulsed at right time after zero crossing. (It turns off self at next zero crossing.) To achieve this with MCU, the MCU must sense the input from the zero crossing detection circuit, then start timing the requested off time, then start a pulse to triac's gate and then stop the pulse.
It can be implemented with an external interrupt function for zero crossing, which starts a timer to generate a pulse on a wave output pin.
On ARM MCU it is possible to setup the event system to start the timer on external interrupt over an event, without an interrupt function. Then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals.
After setting up the zero crossing detector input pin for external interrupt without interrupt function and setting up the timer to execute one-shot pulse, the event system will re-trigger the timer on external interrupt.
a simple Arduino SAMD lib for a Triac/ZC module (in development):
#ifndef _TRIAC_LIB_
#define _TRIAC_LIB_

namespace Triac {

const unsigned long AC_WAVE_MICROS = 10000; // at 50 Hz
const int TIMER_PRESCALER = 8;
const unsigned long PULSE_PERIOD = ((F_CPU / 1000000) * 200) / TIMER_PRESCALER;

Tcc* TCC;

void syncTCC() {
  while (TCC->SYNCBUSY.reg & TCC_SYNCBUSY_MASK);
}

void zeroCrossing() {
}

void setup(byte zcPin, byte triacPin) {

  // setup the external interrupt
  attachInterrupt(zcPin, zeroCrossing, RISING);
  uint8_t ulExtInt = g_APinDescription[zcPin].ulExtInt;
  EIC->EVCTRL.reg |= (1 << ulExtInt);// enable event
  EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT(1 << ulExtInt); // turn-off interrupt

  const PinDescription& pinDesc = g_APinDescription[triacPin]; // Arduino pin description
  TCC = (Tcc*) GetTC(pinDesc.ulPWMChannel);
  uint8_t tcChannel = GetTCChannelNumber(pinDesc.ulPWMChannel);

  // setup the pin as TCC wave out pin
  PORT->Group[pinDesc.ulPort].PINCFG[pinDesc.ulPin].bit.PMUXEN = 1;
  PORT->Group[pinDesc.ulPort].PMUX[pinDesc.ulPin >> 1].reg |= PORT_PMUX_PMUXE_F;

  // setup the timer

  REG_GCLK_CLKCTRL = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(GCM_TCC0_TCC1)); // assign clock
  while ( GCLK->STATUS.bit.SYNCBUSY == 1 );

  TCC->CTRLA.bit.SWRST = 1; // reset timer
  syncTCC();
  TCC->WAVE.reg |= TCC_WAVE_WAVEGEN_NPWM; // normal PWM as wave output mode
  syncTCC();
  TCC->CTRLBSET.reg = TCC_CTRLBSET_ONESHOT | TCC_CTRLBSET_DIR; //one shot and count down
  syncTCC();

  TCC->PER.reg = ((F_CPU / 1000000) * AC_WAVE_MICROS) / TIMER_PRESCALER; // initial value of period (triac off)
  syncTCC();
  TCC->CC[tcChannel].reg = PULSE_PERIOD; // pin on at compare match and off at 0 (timer counts down)
  syncTCC();

  TCC->EVCTRL.reg |= TCC_EVCTRL_TCEI0 | TCC_EVCTRL_EVACT0_RETRIGGER; // retrigger on event
  syncTCC();
  TCC->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV8 | TCC_CTRLA_ENABLE; // set prescaler and enable
  syncTCC();

  // event system
  PM->APBCMASK.reg |= PM_APBCMASK_EVSYS; // power it on
  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(EVSYS_GCLK_ID_0) | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN(0); // assign a clock
  while (GCLK->STATUS.bit.SYNCBUSY);

  EVSYS->CTRL.bit.SWRST = 1; // reset
  while(EVSYS->CTRL.bit.SWRST);

  EVSYS->USER.reg = EVSYS_ID_USER_TCC0_EV_0 | EVSYS_USER_CHANNEL(1); // set user TCC0 event 0 on channel 0
  EVSYS->CHANNEL.reg = EVSYS_CHANNEL_CHANNEL(0) | EVSYS_CHANNEL_PATH_ASYNCHRONOUS | // channel 0 is async
      EVSYS_CHANNEL_EDGSEL_FALLING_EDGE | EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_0 + ulExtInt); // source is ext.interrupt
  while (!EVSYS->CHSTATUS.bit.USRRDY0);
}

/*
 * r is from interval <0.0, 1.0>
 */
void setPeriod(float r) {
  unsigned long period = ((F_CPU / 1000000) * ((1.0 - r) * AC_WAVE_MICROS)) / TIMER_PRESCALER;
  TCC->PER.reg = period + PULSE_PERIOD;
  syncTCC();
}

}
#endif

other SAMD example

Thank you sir...your answer is very helpful...

The ATmega32 has a coupe of peripheral-to-peripheral communication
features that are in some way similar to the Event System:

You can use the analog comparator to trigger an input capture on
Timer 1.
You can use the analog comparator, external interrupt 0, Timer 0, or
Timer 1 to trigger a conversion on the ADC.

These are the only ones I know about. As you can see, it's a very
limited functionality. From what I read, the Event System looks like a
generalization of this idea. You have many peripherals that can trigger
events (event emitters), many that can be triggered by such events
(event receivers), and you can connect any event emitter to any event
receiver. You thus have much more flexibility than the very limited
peripheral-to-peripheral communication facilities provided by the
ATmega32.
The configuration of the event system (emitter to receiver connections)
is performed by your software. However, once the connection is
established, the peripheral-to-peripheral communication is entirely
hardware, and does not depend on the CPU.

Thank you sir....I am very thankful...