text:
nrf24l01+ contradicting itself?
I have recently bought a few of these chips on boards along with some "adapter boards" which supposedly regulates the 5v to propper 3.3v with the required capacitors.
So power supply shouldn't be a problem although I haven't tried with a separate power supply.
Ok, so I like to build my stuff from scratch to really know everything that's going on so I'm not using a library for this chip but I've read the datasheet in it's entirety and have understood all the features.
At first after going through every option one of the modules was successfully sending out packets as indicated by the TX_DS interrupt but nothing was showing up on the one in receiver mode, and after lots of checking I chose to disable every feature and managed to finally get some action as the receiver interrupted each time the transmitter sent out a packet with no CRC and no ACK.
But now there's an issue, the datasheet clearly states:

The RX_DR IRQ is asserted by a new packet arrival event.
      The procedure for handling this interrupt should be:
1) read payload through SPI,
2) clear RX_DR IRQ,
3) read FIFO_STATUS to check if there are more payloads available in RX FIFO,
4) if there are more data in RX FIFO, repeat from step 1).

However upon getting the interrupt and reading out 33 bytes with the command, the status register reads 4E (0100 1110) saying that the interrupt was indeed RX_DR but also the pipe number bits are all on meaning an empty RX FIFO. The following 32 bytes read 0.
How can this be? Has anyone experienced something similar?
UPDATE: Tested with separate power supply on RX side, issue still stands.
Pictures: https://1drv.ms/f/s!Ag6xBMoahJ8xkOkWMG89RIAa1m71Kw
Arduino code: (feel free to correct me I'm no expert in this language :p)
Main
void setup() {
  attachInterrupt(digitalPinToInterrupt(radio.irq), interrupt, FALLING);
  Serial.begin(9600) ;
  Serial.write("\n    ----Boot----\n\nInitializing radio...\n");

  //Starts radio as PRX
  //Sets channel
  //Sets bitrate to 1Mbps
  if (radio.init()) {
    Serial.println("Radio ready.\n\n ----Boot complete----\n\n");
  } else {
    Serial.write("Couldn't initialize radio!\n\n  ----Boot failed----\n");
    return;
  }
  delay(10);
  digitalWrite(9, HIGH);
}

void loop() {
}

void interrupt() {
  Serial.write("\nINTERRUPT\n");
  digitalWrite(9, LOW);

  radio.readRegister(0x17, 2, true, BIN);
  radio.readRXpayload(true);
  radio.clearIRQ();

  digitalWrite(9, HIGH);
}

Radio class
#include "BitUtils.h"

BitUtils utils;

uint8_t* tmp = (uint8_t*)malloc(sizeof(uint8_t) * 33);
uint8_t initialPipe0[5] = {0x28, 0x18, 0xdb, 0xc2, 0x86};
uint8_t beaconAddress[5] = {0x29, 0x26, 0x13, 0x12, 0x00};

class Radio {
  public:
    uint8_t nullmsg[1] = {0x00};

    uint8_t rx_config[1] = {0b00100011}; //0x00
    uint8_t tx_config[1] = {0b00100010}; //0x00
    uint8_t aa_config[1] = {0b00000000}; //0x01
    uint8_t ch_config[1] = {0b00110100}; //0x05
    uint8_t rf_config[1] = {0b00000110}; //0x06
    uint8_t features_config[1] = {0b00000000}; //0x1D

    uint8_t clear_irq[1] = {0b01110000}; //0x07

    uint8_t clk = 13;
    uint8_t miso = 12;
    uint8_t mosi = 11;
    uint8_t slaveselect = 10;
    uint8_t chipenable = 9;
    uint8_t irq = 2;

    SPISettings spiConfig = SPISettings(2000000, MSBFIRST, SPI_MODE0);

    boolean init() {
      noInterrupts();

      pinMode(clk, OUTPUT);
      pinMode(miso, INPUT);
      pinMode(mosi, OUTPUT);
      pinMode(slaveselect, OUTPUT);
      pinMode(chipenable, OUTPUT);
      pinMode(irq, INPUT);
      digitalWrite(clk, LOW);
      digitalWrite(slaveselect, HIGH);
      digitalWrite(chipenable, LOW);
      delay(11);

      transfer(nullmsg, 1, tmp);
      if (tmp[0] != 0b00001110) {
        return false;
      }

      writeRegister(0x00, rx_config, 2); Serial.print("0x00: ");
      readRegister(0x00, 2, true, BIN);
      writeRegister(0x01, aa_config, 2); Serial.print("0x01: ");
      readRegister(0x01, 2, true, BIN);
      writeRegister(0x05, ch_config, 2); Serial.print("0x05: ");
      readRegister(0x05, 2, true, BIN);
      writeRegister(0x06, rf_config, 2); Serial.print("0x06: ");
      readRegister(0x06, 2, true, BIN);
      writeRegister(0x1D, features_config, 2); Serial.print("0x1D: ");
      readRegister(0x1D, 2, true, BIN);

      pipeAddress(initialPipe0, 0);
      pipeAddress(beaconAddress, 1);

      Serial.print("Pipe 0 address: ");
      readRegister(0x0A, 6, true, HEX);
      Serial.print("Pipe 1 address: ");
      readRegister(0x0B, 6, true, HEX);

      delay(2);
      interrupts();
      return true;
}

    //    -- Operations --

    void clearIRQ() {
      writeRegister(0x07, clear_irq, 2);
      Serial.println("Cleared IRQ");
    }

    void sendTXpayload(uint8_t data[], boolean ack) {
      uint8_t message[33] = {0b10100000};
      if (!ack) {
        message[0] = 0b10110000;
      }
      for (int i = 31; i > -1; i--) {
        message[32 - i] = data[i];
      }

      transfer(message, 33, tmp);
      pulseCE(12);
      delay(2);
    }
    void readRXpayload(boolean report) {
      uint8_t message[33] = {0b01100001};

      transfer(message, 33, tmp);
      if (report) {
        utils.prtArr(tmp, 33, HEX);
      }
    }

    void mode(char m) {
      digitalWrite(chipenable, LOW);

      if (m == 't') {
        writeRegister(0x00, tx_config, 2);
        Serial.println("Set tx mode.");
      }
      if (m == 'r') {
        writeRegister(0x00, rx_config, 2);
        Serial.println("Set rx mode.");
      }
    }

    void pipeAddress(uint8_t* address, uint8_t number) {
      uint8_t pipeNumber = 0x0A + number;
      for (int i = 4; i > -1; i--) {tmp[4 - i] = address[i];}

      if (number < 2) {
        writeRegister(pipeNumber, tmp, 6);
      }else{
        writeRegister(pipeNumber, address, 2);
      }
    }

    void sendTo(uint8_t* address) {
      for (int i = 4; i > -1; i--) {
        tmp[4 - i] = address[i];
      }
      writeRegister(0x10, tmp, 6);
      Serial.print("TX Address: ");
      readRegister(0x10, 6, true, HEX);
    }

    void setChannel(uint8_t ch) {
      writeRegister(0b00000101, new uint8_t[1] {ch}, 2);
      Serial.write("Frequency set to: ");
      Serial.print(2400 + tmp[1], DEC);
      Serial.println("MHz");
    }

    //    -- Low operations --

    void readStatus(boolean prt) {
      transfer(nullmsg, 1, tmp);
      if (prt) {
        utils.prtArr(tmp, 2, BIN);
      }
    }
    void readRegister(uint8_t address, uint8_t amount, boolean prt, uint8_t format) {
      uint8_t message[amount] = {address};
      transfer(message, amount, tmp);

      if (prt) {
        utils.prtArr(tmp, amount, format);
      }
    }
    void writeRegister(uint8_t address, uint8_t* data, uint8_t amount) {
      uint8_t message[amount] = {(uint8_t)(0b00100000 | address)};
      for (uint8_t i = 1; i < amount; i++) {
        message[i] = data[i - 1];
      }

      transfer(message, amount, tmp);
    }
    void pulseCE(int duration) {
      digitalWrite(chipenable, HIGH);
      delayMicroseconds(duration);
      digitalWrite(chipenable, LOW);
    }

    //    -- Bidirectional SPI bus --

    void transfer(uint8_t* data, uint8_t amount, uint8_t* output) {
      SPI.beginTransaction(spiConfig);
      digitalWrite(slaveselect, LOW);
      delayMicroseconds(1);

      for (uint8_t i = 0; i < amount; i++) {
        output[i] = SPI.transfer(data[i]);
      }

      delayMicroseconds(1);
      digitalWrite(slaveselect, HIGH);
      SPI.endTransaction();
    }
};

Can you post the Arduino code?

@MichaelT edited in the code

I am wondering if your issue is related to the problem I am having with my nRF24L01's? See https://arduino.stackexchange.com/questions/85874/nrf24l01-continuously-reading-closed-pipe

My advice would be to strip out all of the unnecessary code to make a minimal complete example (MCVE).  The nRF24L01 is not so complicated when you get to know the data registers, and unfortunately that's where a lot of people get stuck, by trying to use the libraries without reading the datasheet.  However, the posted code suggests that you have done your homework.  This is how I set up nRF24L01 to use IRQ (chronological order from top to bottom):
// Begin SPI
// Register 0x0A: set receiver addresses
// Register 0x11: set payload number of bytes

// flush RX (spi transfer B11100010) and TX (spi transfer B11100001)

// attach ISR on IRQ digital input pin.

// start the main program loop

This is the ISR called:
void isr(){
// Read payload data
digitalWrite(CSN_pin, LOW);
 data_in[0] = SPI.transfer(B01100001); //read payload register
 data_in[1] = SPI.transfer(B00000000);
 data_in[2] = SPI.transfer(B00000000);
 data_in[3] = SPI.transfer(B00000000);
 // etc
digitalWrite(CSN_pin, HIGH);

// flush RX
digitalWrite(CSN_pin, LOW);
 SPI.transfer(B11100010);//flush RX
digitalWrite(CSN_pin, HIGH);

// Read status register 0x07
digitalWrite(CSN_pin, LOW);
 SPI.transfer(0x07);
 reg7 = SPI.transfer(0x00);
digitalWrite(CSN_pin, HIGH);

reg7 |= B01000000; // RX_DR set bit 6
// write back to status register
digitalWrite(CSN_pin, LOW);
 SPI.transfer(0x20+0x07);
 SPI.transfer(reg7);
digitalWrite(CSN_pin, HIGH);
}

Edit: bit 6 of the status register is the RX_DR flag.  If this is 1 (which is the case in the OP's example), then the data have not been received.  Set bit 6 to clear the interrupt.

I thought RX_DR stood for Data Ready, and in page 30 they state:
After the packet is validated, Enhanced ShockBurst™ disassembles the packet and loads the payload into the RX FIFO, and asserts the RX_DR IRQ.

You're right, but the data sheet (p59) also says RX_DR=0 is asserted when new data arrive in RX FIFO, write 1 to clear bit.  This is what the code in my answer does.  Remember also MASK_RX_DR=0, but that's default on startup.

That would be odd no? The reset values for the IRQs are 0, and I do get the interrupt when a packet is sent out by the other radio. RX_DR transitions to 1 in the status register, furthermore, upon writing 1 to clear the bit it does go back to 0. Don't know why they made it this way but at least this is what is happening with me. Main issue was asserted IRQ and rest of device stating empty FIFOs.

I just follow what the data sheet says.  The (pseudo) code written above does work, I use that with my own nRF24 projects.


text:
Need to cycle through LED brightness
So this is pretty much explanatory.  I am new to arduino, and i am learning the best i can.  I need to sketch a code in which will cycle through 5 different brightness settings of an led.  One push will cycle through the five, another push of the button will turn the led off, and another push will restart the cycle.
const int led =11;
const int BUTTON = 7;
boolean lastButton = LOW;
boolean currentButton = LOW;
int ledLevel = 0;

void setup()
{
  pinMode(led,OUTPUT);
  pinMode(BUTTON,INPUT);
}
boolean debounce(boolean last)
{
  boolean current = digitalRead(BUTTON);
  if (last != current)
{
  delay(5);
  current = digitalRead(BUTTON);
}
return current;
}

void loop()
{
  currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledLevel = ledLevel + 51;
  }
  lastButton = currentButton;
  if (ledLevel > 255) ledLevel = 0;
  analogWrite(led, ledLevel);
  analogWrite(led, ledLevel + 51);
  delay(200);
  analogWrite(led, ledLevel + 102);
  delay(200);
  analogWrite(led, ledLevel + 153);
  delay(200);
  analogWrite(led, ledLevel + 204);
  delay(200);
  analogWrite(led, ledLevel + 255);
}

The code above turns the led on and cycles brightness, like it should it however for some reason it does disable the button.  Take the analogWrites out except for the first one, and the button will cycle the led. any suggestions on what i could do?  Im very new at this.

When you are not sure how to continue, split the problem into smaller problems and confirm that a part is working before using it with the other parts. You can split your sketch into different parts. I can see four parts: read button with debounce, notify that a button has been pressed, process that information for the three states (brightness, turn off, restart), and set the brightness for the led. If you show clearly the four parts in your sketch, then it is easy to print a message when a button has been pressed. That makes it easier to test that part.

Something like this, with variable declarations & setup() left to you.  All time elements are of type unsigned long.
pwmValue {} = [51, 102, 153, 204, 255];

void loop(){
  if (digitalRead(startButton) == LOW && pwmCycling == 0){
    // start button pressed, and not already running
    startTime = millis(); // capture the time of the button press
    pwmCycling = 1; // keep track of the running state. 0 for off, 1 for on.
    }
  if (pwmCycling == 1){ // cycling is running
    // this is where the blink without delay is:
    currentTime = millis(); // capture the time now
    elapsedTime = currentTime - startTime; // see how much time went by
    if (elapsedTime >= eventDuration){  // enough?  start next brightness
      currentTime = startTime; // set up for next event time
      brightNumber = brightNumber +1; // keep track of brightness level
      if (brightNumber >= 5){ brightNumber = 0; } // reset after the last level
      analogWrite (ledPin, pwmValue[brightNumber]); // write the LED pin
      }
    }
  if (digitalRead(startButton) == LOW && pwmCycling == 1){
    // start button pressed while LEDs are cycling, stop them
    pwmCycling = 0;
    analogWrite (ledPin, 0);
    brightNumner = 4; //reset the brightness level to the end
    delay (100); // little bit of dumb debounce delay
    }
}

Ive managed to write the declarations and the setup.    int pwmValue[] = {51, 102, 153, 204, 255};
const int ledPin = 13;
int startButton = 2;
int pwmCycling;
int startTime = 0;
int elapsedTime;
int currentTime;
int eventDuration;
int brightNumber;
void setup(){
  pinMode(ledPin, OUTPUT);
  pinMode(startButton, INPUT);
  startButton = millis();    I am not getting an errors when compiling the sketch.  However the button does not turn on the led at all.  Im assuming the problem is within the setup().  what should i be looking for?

also dont know why the 4 space thing doesnt work for me.  I tried keeping the lastbutton and currentbutton lines of code, still no errors, still not working.

changed to unsigned long and still nothing.  Not sure what im missing.

I can't do much more until I get home to try it myself.

All the delay(200) lines keep the sketch from reading button presses.
You need to learn about Blink Without Delay so your sketch can do things other than sit there blindly letting time pass.

So I am now reading up on blink without delay.  If i were to remove the additional analogWrite(led, ledLevel) portions of the code, how would I implement it.  First press of button will turn the led on, and cycle through the following PWMs (51, 102, 153, 204, 255) continously.  Second push of the button will turn the led off no matter what PWM the led is in.  while a third push of the button will restart the process.  If it were to implement millis() how could i do that with analogWrite() to be able to phase through the led brightness? only examples I get is with digitalWrite.

What you are doing is checking how much time is elapsed, and when enough has gone by you do another something. Just like watching a clock on the wall when baking a cake. Capture the time now to start, then capture the time every pass thru loop() after that, and see if enough time has elapsed to do something.

source: Stack Exchange

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

sort: votes


text:
Button to exit a running loop
I have a very basic circuit setup:

A button connected to pin 2
An LED connected to pin 9

Desired Functionality:
When the button is pressed, the user can toggle through 4 LED patterns.
The Problem:
Once the first fade pattern begins, the user has to wait until it has finished running before the button can toggle to the next pattern. What  I want is that the button push will move to pattern 2, even if pattern 1 has already started.
Attempted Solutions:
I've tried to insert a while function in a couple of places i.e while buttonstate =lastbuttonstate, but that doesn't seem to work.
Here's the code: (I realize all the fadeloops are the same right now, they will different in the working model)
//PROBLEM: The fade function has to complete a full loop before allowing toggle to next one

const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 9;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

int brightness = 0;    // how bright the LED is
int firstFadeAmount = 5;    // how many points to fade the LED by
int secondFadeAmount = 5;    // how many points to fade the LED by

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      buttonPushCounter++;
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  lastButtonState = buttonState;

  while (buttonPushCounter = lastButtonState) {
    if (buttonPushCounter == 1 && buttonState == HIGH) {
      fadeLoop1();
      delay(50);//JP Edit
    }

    else if (buttonPushCounter == 2 && buttonState == HIGH) {
      fadeLoop2();
      delay(50);
    }

    else if (buttonPushCounter == 3 && buttonState == HIGH) {
      fadeLoop3();
      delay(50);
    }

    else if (buttonPushCounter == 4 && buttonState == HIGH) {
      fadeLoop4();
      delay(50);
    }

  }
  if (buttonPushCounter == 4) {  //Resets back to zero after 4 presses
     buttonPushCounter = 0;
  }

}

void fadeLoop1()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

void fadeLoop2()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

void fadeLoop3()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

void fadeLoop4()
{
  for (int i = 0; i < 100; i++) {  //Set the length of the first fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + firstFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      delay(1000);                  //Sets the hold at the top and bottom of the cycle
      firstFadeAmount = -firstFadeAmount;
    }
    delay(100);
  }
  for (int i = 0; i < 100; i++) {  //Set the length of second fading cycle
    analogWrite(ledPin, brightness);
    brightness = brightness + secondFadeAmount;
    if (brightness <= 0 || brightness >= 255) {
      secondFadeAmount = -secondFadeAmount;
    }
    delay(30);
  }

  digitalWrite(ledPin, LOW);
}

You might want to expand on the description of the circuit. The button is connected to pin 2 and ???.

Thanks. The button is connected to pin 2 only and is only there as a counter.

The button is also connected to GND (or VCC) with a resistor? You might have connected a open circuit and therefore have erratic input values.

The issue is that the fadeLoopN functions occupy the CPU. There are two approaches to solving this: (1) rewrite the fade patterns in a way that they are performed using timer interrupts; or (2) create an interrupt for the button, and set some global flag in the interrupt service routine, then check for this flag in every loop in your fade functions. The first approach is preferred, but the second approach is less invasive.

all four fade patterns are the same, so you have no way of knowing if you selected a different pattern

Short Answer:
Switch from using a loop for the entire animation and convert to only tracking what needs to happen at a single point in time.
Long Answer:
The 'while' approach is a good way to test out an individual pattern but for the behavior you describe, you need to limit the use of loops inside of the 'loop()' function.
Essentially, if you use a while to control the entire pattern, as you encountered, you have to wait for the while to exit before the rest of the code can check for a button press.
Here is how I've done the same thing.  I don't have the code handy so I'll have to edit the answer later.  The basic form is something like this:
int pattern = 0;
int brightness = 0;
int maxBrightness = 100;

setup()
{
// your setup code here
}

loop()
{
   if (pattern = 0)
   {
      //increment brightness
      //call code to set the LED to the current brightness
      if (brightness => maxBrightness)
      {
          brightness = 0;
      }
   }
   checkforbuttonpress();
}

What you notice is I didn't use a for / while loop to do my animation, because the already existing loop() function already does that for me.  All I have to do is track what needs to happen right now, with variables for which pattern and the current brightness for the code to interact with the hardware.  Remember to handle the repetition manually (maxBrightness in this example) and now when the button is pressed, you can change the pattern anywhere because there is no secondary loop to wait for.

Rewrite the fade loops so they return immediately and instead use global state to adjust the LEDs and millis()-timestamp to set the timing.
You can use blinkwithoutdelay as inspiration.

Thanks. Please explain, what does it mean to "return immediately" and how do I include it in the code? I am reading about 'miilis' now, it looks like it's the way to go.

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


text:
Should I buy Arduino as a Computer Engineering Student?
I'm going to be in the third year of university in a month. I'm satisfied with the software part of my bachelor but I feel like I lack in practice in practical implementation. Would getting an Arduino board and playing around with it worth it and useful for me?

Depends om how much time you want to spend and what are your goals. You can learn a lot about resource constraint software system development from simple boards such as the Arduino. But it is all about how much time you have to spend. The board(s) is cheap in comparison. You could just start off by reading and trying to understand some of the source code that builds the Arduino core and libraries. Often university curriculum's miss teaching how to read large source code systems.

You don't mention your level of experience working with hardware. Do you have experience working with electronic circuits?

Mikael Patel, you should post this as an answer.

It depends. If you don't have any knowledge about microcontrollers it might be useful.
However, Arduino hides a lot of concepts in their libraries. If you want to go more indepth check other systems like STM32 or PIC.
You also can do both, start with Arduino to get a rough feeling, continue with another.
More important is WHAT you try, don't stop with LEDs/switches, but check communication protocols like SPI, I2c, UART etc. And learn what timers, interrupts etc. are and how to use them.

and networking for IoT

The original Arduino boards are based on 8 bit  AVR microcontrollers, and using Arduino libraries with them is entirely optional. There is a lot of information about programming AVR microcontrollers in C and assembly, and the datasheets are quite readable. With STM32, low-level programming is a lot more difficult to learn because various HALs are preferred by developers. Even finding a basic register/pin definition file is a challenge if you do not wish to use any HAL. For this reason I would argue against STM32 for learning low-level programming.

@Im_Int not sure if I agree, about 99% using Arduino use the IDE which hides a lot of the internals (which is ok for most people). With STM32 the HAL is used, but not as often as the IDE for Arduino (relatively). There are many different STM32s/IDEs and ways to program (HAL, CMSIS, StdLib). I didn't mean he needs to go so low level, but the Arduin commands hide so much it's barely needed to understand how a microcontroller works.

As already stated in previous answers, there is no clear-cut answer to
this kind of question. It all depends on what you want to learn.
If that can help, I will share my personal experience. I studied
computer science for only one year at university. Then I stopped to
continue on my physics major. But as I never lost interest in computers,
I continued learning on my own. I started playing with Arduinos just
because it looked like a fun way to learn some microcontroller stuff and
low-level programming. The barrier to entry is extremely low: in no time
you get your LED blinking, and from there you can start exploring plenty
of possibilities. The Arduino IDE and core library make it extremely
easy to make simple programs, but they are quite limited when you want
to get more serious. For many people, this environment, plus extra
downloadable libraries, is all they need to achieve their goals. For me,
it was a stepping stone to learn lower level stuff, like direct hardware
access, use of the avr-libc, and even assembly programming.
Today, what I love most about Arduinos (or, rather, the AVR
microcontrollers at their core), is their simplicity and
understandability. Today, when I disassemble a program I have written,
I can understand basically everything: the C runtime initialization
code, the memory allocation, the way the compiler translates my own
code... I find it extremely rewarding to reach such an understanding of
a (kind of) computer system.
The same level of understanding would be (for me) impossible to achieve
on a typical PC. Even though I use Linux, which is Open Source, and I
have access to the full source code, the whole software stack involved
in running even the simplest program is overwhelming. The kernel itself
is like millions of lines of code. Even the assembly language of an x86
(or x86_64) is something I find way too complex for my taste.
In conclusion, the Arduino has been for me a very rewarding learning
experience. If you want to get your hands dirty with bare metal
programming, I definitely recommend you get an Uno, or something
similar, and start playing with it. Once you get your first program
running (and that takes no time!) start looking under the hood: read the
source of the Arduino core (it's short and very readable), read the
datasheet of the microcontroller, start poking the
hardware, take a look at how the compiler allocates
memory, how it translates your source code...

I don't think there is a should or should not about it, do you want a low cost experimental setup using the C language to toy with ideas and concepts without a massive outlay or proprietary software or NDA's to get chip data that ties you to a single company then why not? You can get Arduino clones very cheaply from the likes of aliexpress etc as well as prototyping kits. While the Arduino IDE is a relatively primitive editor you can use any programmers editor you like to compose your C files and use the Arduino IDE just to do the final compile and linking and upload/burn them to the target device. It can be done so cheaply that even if you decide it does not inspire your imagination you won't have wasted hundreds of $! Just spent a couple of tens of $ to accumulate a significant micro-controller playground! Assuming you already have some kind of personal computer or easy access to one.


text:
Increase PWM bit resolution on only one timer 2 output
I am new here and I know that this basic question has been answered in the past but what I want to know is this. And I cant figure out how to add this to one of those threads. Sorry in advance if I am posting this wrong.
Arduino Uno
I have a motor driven PWM off output 10 and output 9 is used for the display, can I change the resolution of output 10 only to 16 bit? or will both outputs need to be used as PWM when changing timer 2 to 16 bit? All of the coding samples I see are for changing both outputs.

I'm sorry, I'm not familiar with PWM libraries within the Arduino framework, but I've taken a look at the microcontroller datasheet, and it appears there is a way to operate 16-bit PWM on pin 9 (OC1A) while retaining normal port operation on pin 10 (OC1B). Please refer to table 20-4 on page 170 of the datasheet if you are willing to configure the timer manually. It is rather involving unfortunately. Perhaps there is a library for that.

I think I agree with you, after reading the datasheet, therefore I will just rewire the board and not use output pin 9. If I get a little time I will do some testing with variations but for now I don't have the time. Thank you for the info!

@user49780, read the updated answer from Gerben

You mean “Timer 1”. Both outputs 9 and 10 are driven from Timer 1, not Timer 2.

Yes, you are correct, I did mean timer 1.

As long as you don't use PWM (i.e. analogWrite) on pin 9, any changes made to timer1 won't affect pin 9.
It will change both outputs, as both use the same (single) timer.
But you can use code to convert a 8-bit PWM value to a 16-bit value by simply multiplying the 8-bit value by 256.

The title is misleading. I don't think that the question was if you can have different PWM resolution on 9 and 10. I understand  the question so that one of the pins 9 and 10 should be PWM and second a simple digital pin. (I am not the downvoter)

@Juraj I think you might be right there.

Some of the stuff I had read about changing the timer 1 to 16 bit mode made it sound like both pin 9 and 10 could only be used for PWM then. Of course this seemed incorrect but I could not find anything with a clear answer. I have since rewired the project to not use pin 9 in case it was true. I will sometime soon figure this out with some testing. Currently have little time for that. I do have a new issue that I am trying to figure out. It has to do with the scaling. It is not working as expected. But I will look more into it before starting a new thread if I can't figure that one out.

The COM1A1 and COM1A0 bits in the TCCR1A enable PWM on pin 9. As long as you leave them at 0, pin 9 will act like a normal GPIO pin.


text:
Connecting two Arduinos via I2C while I2C Pins A4/A5 are already in use
I have the following problem:
Since the BH1750 Sensor only supports two different I2C adresses, but i need to use 6 of those sensors, i wanna use 3 arduinos, 2 nanos, 1 uno and send the data from the nanos to the uno. Problem is that the I2C bus is already in use and while trying to send data, it does not work properly.
Is this even possible? When trying it out, i can't get anything correct

Update:
That's what i tried now:
Results i get are still not correct

#include <Wire.h>
#include <BH1750.h>

// This code will feature the use of 6 gy 30 light sensors

BH1750 active_sensor(0x23); // We will use this adress for stating the active sensor
BH1750 inactive_sensor(0x5C);

void setup(){

  Serial.begin(9600);

  // Setting the input pins for controling the addr pins of the modules
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(12, OUTPUT);
    pinMode(13, OUTPUT);

    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
    digitalWrite(12, LOW);
    digitalWrite(13, LOW);

  // Initialize the i2c bus
  Wire.begin();

 // Here we will set the mode of the module
  if (active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {
    Serial.println(F("BH1750 Advanced begin"));
  }
  else {
    Serial.println(F("Error initialising BH1750"));
    Serial.println("Problem on 1");
  }
}

void loop() {
  get_values();

}

void get_values(){
  int i;
  Serial.println("----");
  for(i = 8; i<=13;i++){
    digitalWrite(i,HIGH);
    delay(50);
    int lux = 0;
    lux = active_sensor.readLightLevel();
    Serial.println(lux);
    delay(50);
    digitalWrite(i,LOW);
    delay(150);
  }
}

the Question update is based on CrossRoads's answer

comment to question update. with ADDR HIGH address is 5C. change the address of active device to 5C.

you should accept CrossRoads's answer to mark this question solved

Use the ADDR pin as a chip select. Pull both pins high normally. When you want to talk to one, pull the ADDR pin low and use the ADDR = 0 address to talk to the selected device. Then you can have all 6 connected to one Arduino.

I actually tried this before, it did not work properly. Do you have any evidence that this really works?

Post the code of what you tried with all 6 devices connected as suggested. Make sure the devices are all getting power.

There is a simple sketch here you can try for 1 device, then easily modify to cycle thru all 6. Be sure to add 4.7K or even 3.3K pullup resistors to SDA and SCK. The internal pullups in a '328P are not enough.

Ok, i just posted the code i am using, i did not use any resistors by now. So only 1 resistor or one for each sensor?

https://media.digikey.com/pdf/Data%20Sheets/DFRobot%20PDFs/SEN0097_Web.pdf  Yes, one resistor each on SCL & SDA, at the end of the wiring chain preferably.   Not at each device, just at one device.

I tried what you told me, i provided a schematic and the code i used, yet i still don't get what i desire, can you have a look at it?

You can make the nanos use software I2C to isolate those I2C buses from the UNO's I2C bus. Then have the UNO be the master on it's own bus, requesting the data when needed.
Though if you go for software I2C you can make the UNO do all the I2C work, assuming you have enough free pins for that.
Another option is to get a proper I2C multiplexer like the TCA9548A.

Six software i2c busses requires 7 pins. That is 6 sda lines and just 1 scl line. The ADDR selection to bring one sensor in focus is easier, but requires 8 pins. The tca9548a still requires 5 pins (two i2c plus three address for 6 busses).

@Jot But you only need 3 buses because a pair of sensors can share a bus. Also the address pins of the tca9548a can be statically tied, the actual multiplexing is done internally. You write to the tca9548a itself through I2C (that is what the address pins are for) to select which channels should be open and then it passes through the I2C bus signals to those open channels. You can then close the channel when you are done.

Thanks, I didn't think about that. So it will be 4 pins for a software i2c, 8 pins for ADDR selection, and 2 pins for the tca9548a.


text:
The reason for signal not going back to LOW
I have written a simple Arduino sketch, that shall produce a clock signal.
Here is the code:
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(8,HIGH);
  delayMicroseconds(500);
  digitalWrite(8,LOW);
  delayMicroseconds(500);
}

Namely the pin 8 of Arduino Uno is periodicaly set to HIGH and LOW.
The output that I receive, for three different frequencies, is:

My question is: Why is falling edge not as sharp as rising edge? As can be noted, for high frequencies the signal wouldn't go to LOW after all.

Is this your demonstration of what you're calling, "high frequency"? Because this does look like it's going LOW but as you pointed out, it's not as sudden as it going HIGH. Have you also reviewed what the datasheet says about your particular Arduino Uno?

I don't know the details of Arduino hardware, but don't you need to explicitly configure pin 8 to be an output in your setup() function? It looks like you're just enabling/disabling a pullup by default.

@DaveTweed No, it appears that the problem is the OP hasn't declared pin 8 as output.

@DaveTweed Indeed, declaring a pin as output, produced a nice square wave. Can you please elaborate on reasons behind this (e.g. what you mean by enabling/disabling a pullup by default) and that would be answer to this question.

The pin is not configured as OUTPUT.
By default, all of the GPIO pins on pretty much any microcontroller are configured as inputs following reset. This prevents the chip from "fighting" an external device that might be driving any of those pins before the firmware has had a chance to configure the GPIO correctly.
On the MCU used on the Arduino, the output latch controls the state of an internal pullup resistor when the pin is configured as an input. Your code was simply enabling and disabling this resistor. When you set the pin low, it makes the pin open-circuit, and you see a slow decay of voltage through your oscilloscope probe.


text:
7 segment display blinking
I want to display the DHT22 temperature and humidity sensor in a 3 digit 7 segments display. It's always showing the  sensor value and after 2 or 3 sec the display turns off, and then the display turns on, and so on.
I need help to understand where is the mistake on the code to make the display always turned ON.
#include <SevSeg.h>
#include <EEPROM.h>
#include "DHT.h"
#define COMMON_ANODE 0
#define DHTPIN A0     // what pin we're connected to

#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value
SevSeg sevseg;

void setup(){

byte numDigits = 3;
byte digitPins[] = {1,2,3};
byte segmentPins[] = {4,5,6,7,8,9,10,11};
sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
 dht.begin();
}

void loop(){
   temp= dht.readTemperature();

   sevseg.setNumber(temp,1);
   sevseg.refreshDisplay();
}

A good way to avoid display flicker is to only update the display when needed.  The display update is what causes it to flicker.  If you change your main loop as below, the display will only update when needed (when the current reading is different than the last reading).  It's probably also a good idea to only read the temperature every 2 seconds or so which can be controlled with a simple delay().
float temp, last_temp = 0;

void loop() {
    temp = dht.readTemperature();
    if (temp != last_temp)
    {
        sevseg.setNumber(temp,1);
        sevseg.refreshDisplay();
    }
    last_temp = temp;
    delay(2000);
}

SevSeg library author says "Your program must run the refreshDisplay() function repeatedly to display the number", he even warns that delays will produce undesirable effects... I tried this and it didn't work.

You have a multiplexed display. Multiplexed displays have to be constantly updated, or they display the last displayed digit (if there was one) for an extended period.
The reading from the DHT will take time. That time will interrupt the display updates causing it to stop for a while as it reads.
Why does it do it every few seconds? All I can suggest is that the DHT library you are using limits the actual readings to every few seconds - and between those times it just returns the previously stored value.
To get around it you should consider doing your display updates from within a timer interrupt (assuming your DHT library doesn't disable interrupts).

Many thanks Majenko, can you send a sample code to solved

many thanks,i would like to share my idea which i try it this week with all my friends, i just repair DHT22 library and decrease the delay time in, and then the 7 segments blinking every 2 seconds will disappear .


text:
"char inChar = (char)Serial.read();" why is the "char" in brackets? and what is it called
I am sure this is a very simple answer, but I don't know to look it up on google
In the example "SerialEvent" in the arduino IDE (v1.8.7), there is the following function
    void serialEvent() {
        while (Serial.available()) {
           // get the new byte:
           char inChar = (char)Serial.read();
           // add it to the inputString:
           inputString += inChar;
           // if the incoming character is a newline, set a flag so the main loop can
           // do something about it:
           if (inChar == '\n') {
               stringComplete = true;
           }
        }
     }

On the third line "char inChar = (char)Serial.read();" the (char) is given in brackets before the serial read.
Why is this? and more specifically how is called ?

This is actually more a C/C++ language question. The hint is "Please check the return value type for Serial.read()".

So it basically forces the value returned from serial.read() to be a char? Do you know how this is named, so I can look up the documentation?

In C, why are there parentheses around (int) in this example?, Type in parentheses in C variable definition

What topics can I ask about here? On topic: Specific questions about Arduino boards, code…  https://arduino.stackexchange.com/help/on-topic. Is this question not a specific question about Arduino code? Voting to not close.

@will.mendil This is called "Explicit type conversion" or "Casting". https://en.cppreference.com/w/cpp/language/explicit_cast. In some cases it ends up as some extra code but in other cases it is just a hint to the compiler and no extra code is generated.

@will.mendil Why is the explicit cast necessary above? What would happen if the statement was int inChar = Serial.read();? What would the statement inputString += inChar; mean if changing char inChar to int inChar.

It is called type casting and will convert one type to another. The return type of Serial.read() is int, because it will return -1, when you try to read without any bytes being available. The casting with (char) will drop the high byte of the (2-byte long) integer, leaving only the lower byte. This byte will contain the actual read data, in which you are interested here.
Casting is a complex thing, because there can be different ways to convert different types (for example maintaining the bit-content vs. maintaining the decimal value). The casting, that you are seeing here, should only be done, if you really know, what you are doing. The bits will not be changed to maintain the correct value, but the bit-content will be preserved, unless the new type is smaller than the former. In this case the rest is lost. Also, if you try to cast a float value to an int value with this, you will get a totally different decimal value out of it, because the numbers are encoded in the bits in a totally different way. Here it is known to be OK, especially, if you are checking for available bytes before reading with Serial.available(), because the library puts the ASCII data in the lower byte.
For further explanations you should consult C/C++ guides.


text:
rotary encoder spamming output
im building my second arduino project. Im very new to this all so I could certainly use some help fixing everything.
Im trying to make a controller for a pc port of an arcade game. It uses two rotary encoders, something I never heard about before going into this project

 I had found some code on github that works perfectly in my case, but the code has the rotary encoders move the mouse. something that dosent work for the games controls unfortunately (i tried)

so i attempted to change them and now they do spit out text like i need them but when i rotate them instead of getting the needed out put of
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

i get something more along the lines of
babababababababababababababababbabb

like if im turning the knob both ways at the same time when im just turning it one direction.
heres the code im working on
/*
* By Daniel Tam (daniel@danieltam.net)
============ NOTES ============
This will create a SDVX Controller using an Arduino Leonardo.
You will hook up one wire of the button to the Arduino pin and the other to Arduino's ground. When pushed, the button should go to ground.
You will need to download the encoder library and use it in your project for this to work (ww.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino)
===============================
*/

// buttons
#include <Mouse.h>
#include <Keyboard.h>
#define BT_A 2
#define BT_B 3
#define BT_C 4
#define BT_D 5
#define FX_L 6
#define FX_R 7
#define BT_ST 8

// encoders
#include <Encoder.h>
Encoder enc1(15, 14);
Encoder enc2(16, 10);
float knob1 = 0;
float knob2 = 0;
float old_knob1 = 0;
float old_knob2 = 0;

void setup()
{
  // set pins to read, and output high
  // when the pins read low, we know that the buttons have went to ground (aka, pushed down)
  pinMode(BT_A, INPUT);
  pinMode(BT_B, INPUT);
  pinMode(BT_C, INPUT);
  pinMode(BT_D, INPUT);
  pinMode(FX_L, INPUT);
  pinMode(FX_R, INPUT);
  pinMode(BT_ST, INPUT);

  digitalWrite(BT_A, HIGH);
  digitalWrite(BT_B, HIGH);
  digitalWrite(BT_C, HIGH);
  digitalWrite(BT_D, HIGH);
  digitalWrite(FX_L, HIGH);
  digitalWrite(FX_R, HIGH);
  digitalWrite(BT_ST, HIGH);

  Mouse.begin();
  Keyboard.begin();
}

void loop()
{
  // read encoders
  knob1 =  (float)(enc1.read());
  knob2 = (float)enc2.read();

  if(knob1 != old_knob1)
  {
    // if there's a difference in encoder movement from last pass, move the mouse
    if(knob1 < old_knob1)
    {
     // Mouse.move(0, -5);
      Keyboard.press('a');
      delay(100);
      Keyboard.release('a');
    }
    else
    {
    //  Mouse.move(0, 5);
      Keyboard.press('b');
      delay(100);
      Keyboard.release('b');
    }

  // we count the difference in the encoders, but we must not go over arduino's int limit
    if(knob1 < -255)
    {
      enc1.write(0);
      old_knob1 = 0;
    }
    else if (knob1 > 255)
    {
      enc1.write(0);
      old_knob1 = 0;
    }
    else
    {
      old_knob1 = knob1;
    }
  }

  if(knob2 != old_knob2)
  {
    if(knob2 > old_knob2)
    {
     // Mouse.move(-5, 0);
      Keyboard.press('c');
    }
    else
    {
     // Mouse.move(5, 0);
      Keyboard.press('d');
    }

    if(knob2 < -255)
    {
      enc2.write(0);
      old_knob2 = 0;
    }
    else if(knob2 > 255)
    {
      enc2.write(0);
      old_knob2 = 0;
    }
    else
    {
      old_knob2 = knob2;
    }
  }

  // read the buttons for low, if it's low, output a keyboard press
  if(digitalRead(BT_A) == LOW)
  {
    Keyboard.press('f');
  }
  else
  {
    Keyboard.release('f');
  }

  if(digitalRead(BT_B) == LOW)
  {
    Keyboard.press('b');
  }
  else
  {
    Keyboard.release('b');
  }

  if(digitalRead(BT_C) == LOW)
  {
    Keyboard.press('c');
  }
  else
  {
    Keyboard.release('c');
  }

  if(digitalRead(BT_D) == LOW)
  {
    Keyboard.press('d');
  }
  else
  {
    Keyboard.release('d');
  }

  if(digitalRead(FX_L) == LOW)
  {
    Keyboard.press('z');
  }
  else
  {
    Keyboard.release('z');
  }

  if(digitalRead(FX_R) == LOW)
  {
    Keyboard.press('x');
  }
  else
  {
    Keyboard.release('x');
  }

  if(digitalRead(BT_ST) == LOW)
  {
    Keyboard.press('n');
  }
  else
  {
    Keyboard.release('n');
  }
}

Your aren't using the recommended pins to attach the encoders. Because of this the library isn't using interrupts, but depends on you calling encX.read() often enough, to not miss any changes. This, combined with the 100ms delay in your code, will almost guarantee that you will miss some changes, making the library think you are rotating the other way around.
Change the pins to 0, 1, 2, 3 (or at least one of those for each encoder).
Otherwise lower the delay to for example 1ms. I couldn't find whether this delay is even necessary, or how long it needs to be, so you'd have to experiment a bit, and see what works.
Lastly; why are you using float to store the position? Try using long instead, as that's the type enc.read() returns.

was there a first part that got cut off?

Sorry, I had to change the order around. Nothing missing.

changing pins to 0,1 seems to do exactly what i need!
I had the delay in as a test as im still learning and as for the floats that's part of the original guys code so im not too sure.

actually i seem to intermittently get the old result, seems to work sometimes.

nvm seems most of my issues stem from a wonky breadboard thats connecting the pins or something.


text:
Arduino Convert std:string to String
I'm working on BLE project with espressif library. And It returns me founded BLE device.
std::string getManufacturerData();
std::string getName();
int         getRSSI();
BLEScan*    getScan();

When I want to print device name to serial port
BLEAdvertisedDevice founded_dev;
founded_dev=foundDevices.getDevice(0);
Serial.println("Name -> " + founded_dev.getName());

It gives me error like this
no matching function for call to 'HardwareSerial::println(std::__cxx11::basic_string<char>)'

So how can i convert to std:string to String in Arduino?

Don't. Instead just access the underlying C string:
Serial.print(F("Name -> "));
Serial.println(founded_dev.getName().c_str());

That works for getName() but not some of the other methods such as BLEAdvertisedDevice::getAddress() or BLEAdvertisedDevice::getServiceUUID()

@TomAuger That's because they don't return a string.  The first returns a BLEAddress, the second a BLEUUID. Custom types that will need special handling.

For the UUID you can use getServiceUUID().toString().c_str(), For the address you can use: getAddress().toString().c_str().


text:
Using Modbus-RTU with Arduino and temperature controller
I'm trying to connect with a 4 channel temperature controller using Arduino Modbus Library.
This is a part of my temperature controller datasheet. It has register for read PV of each channel.

I have studied example code of the library and now i'm trying to read PV of each channel.
So, I have modified the example code as below,
#include <ModbusMaster.h>

    // instantiate ModbusMaster object
    ModbusMaster node;

    void setup()
    {
      // use Serial (port 0); initialize Modbus communication baud rate
      Serial.begin(19200);

      // communicate with Modbus slave ID 2 over Serial (port 0)
      node.begin(2, Serial);
    }

    void loop()
    {
      static uint32_t i;
      uint8_t j, result;
      uint16_t data[6];

      i++;

      // set word 0 of TX buffer to least-significant word of counter (bits 15..0)
      node.setTransmitBuffer(0, lowWord(i));

      // set word 1 of TX buffer to most-significant word of counter (bits 31..16)
      node.setTransmitBuffer(1, highWord(i));

      // slave: read (4) 16-bit registers starting at register 2 to RX buffer
      result = node.readHoldingRegisters(1, 4);

      // do something with data if read is successful
      if (result == node.ku8MBSuccess)
      {
        for (j = 0; j < 4; j++)
        {
          data[j] = node.getResponseBuffer(j);
        }
      }

    }

My questions are,
Explain below lines in the code
          // set word 0 of TX buffer to least-significant word of counter (bits 15..0)
      node.setTransmitBuffer(0, lowWord(i));

      // set word 1 of TX buffer to most-significant word of counter (bits 31..16)
      node.setTransmitBuffer(1, highWord(i));

I didn't  pass any request to slave, So, can I get the 4 PV value like this?
If not, please explain how can I do it.

The setTransmitBuffer calls are for writeMultipleRegisters, which you removed from the example.
The first parameter of the readHoldingRegisters is the address of the register. The second parameter is the count of registers to read.
Your sketch doesn't show the retrieved data. You have no indication of success or fail.

As I understood, setTransmitBuffer  using for initializing the TX buffer.Am I correct?
Retrieved data stored in RX buffer. can't we get data using getResponseBuffer?

you have data[j] = node.getResponseBuffer(j);


text:
TLC5917 SPI Speeds
I am attempting to use 3 x TLC5917 chips to drive a row of LEDs in PWM. The LEDs share a common anode being powered through a transistor, with each LEDs cathode going to pins on the TLC5917 Chips.
There are obviously other chips specifically designed for PWM but my questions relate to the Arduino SPI Implementation.
The chips I am using are rated for 30MHz Max Speed.
The Arduino (Uno) I am using runs at 16MHz. SPI can only run at half speed which means the SPI Transfer Max Speed for this hardware is 8MHz.
With this in mind, before overhead it should take 1/8Million seconds per clock cycle, equivalent to 1/8th of a Microsecond.
This means that SPI should take 24 clock cycles to send out 24 bits. Clocking out all 3 bytes (24 bits) should take about 3 Microseconds before overhead.
Then a few more microseconds to flip the latch pin.
Instead I see it taking about 12 Microseconds to send the 24 bits and another 12 Microseconds to latch the pin low and high, 4 times what I expected. Obviously there is some overhead but 400% seems excessive.
I have looked at the Arduino SPI Library to see if there is any obvious overhead but I cant see anything that would quadruple the theoretical transfer time.
This is the sketch I used to time the data transfers
#include <SPI.h>

void SSHigh(){
  PORTB = PORTB | 10000000;
}

void SSLow(){
  PORTB = PORTB ^ 10000000;
}

void setup() {
   SPI.begin();
   Serial.begin(9600);
   pinMode(2, OUTPUT);
   digitalWrite(2, LOW);
}

void writeChips(byte red, byte green, byte blue){
    SPI.transfer(blue);
    SPI.transfer(green);
    SPI.transfer(red);

}

long start;
long end;
long delta;

void loop() {

  start = micros();
  writeChips(B11000110,B01110010,B00011110);
  end = micros();
  delta = end - start;
  Serial.println(delta);

}

There is always overhead, since the UNO doesn't have DMA. So it's waiting for the transfer the be completed, before it can send new data. This checking takes a few cycles, and doesn't always neatly align with the exact moment the transfer is done. There might also be overhead from the function call, and the return value, but the compiler might inline all the code. It might be useful to look at the compiled assembly code, to see what's going on.

Is there any way we can meaningfully reduce the overhead without having access to DMA?

You could not use the SPI library. But I'm not sure if this would help, as I wouldn't be surprised if the compiler already optimized the code. Also note that the calling micros and storing it's value takes some time, so your results are already off by a bit.

I'm also not sure how you are going to use this in driving the leds, as you'd need some additional code to do the pretty animations. Do you plan on updating the leds in a timer interrupt? What framerate are you striving for, and how many bit of PWM (how many different brightnesses)?

I have already achieved PWM using an interupt like you suggested. I was looking to gain further PWM bits, but at this point I am limited by SPI Speed (or the Arduino implementation of it).

Have you checked the default SPI clock frequency?

Crap, your right. Setting it to DIV_2 bring it down to about 8 Microseconds. The rest must be overhead.

You could try running the ISR at three times the speed, and only send out one byte at a time in the ISR. Then every third interrupt you set the latch pin. That way your main program can run while the SPI peripheral is sending out the data. Depending on the ISR overhead, you might be able to run the timer a bit faster, while still have enough time spend in your loop to do useful things. But I think it's better to start looking at another chip.

PS I've done some software PWM on shift registers in the past, using a timer to update all the shift registers. I used one of the PWM outputs of that same timer to connect to the enable pin on the shift registers. That way I could set a global brightness on all the leds, while at the same time having software-PWM on all the individual leds. I used that to change the brightness of the display depending on the ambient brightness, without sacrificing any resolution in individual PWM.


text:
Arduino on Windows vs Ubuntu
I have some code that works fine on Windows but is giving me errors on Ubuntu. I noticed that while Windows is running the code using avr-gcc, Ubuntu is trying to make it run using avr-g++. Any functions not defined within void setup() comes up as "was not declared in this scope". Is there a way to force it to use avr-gcc ?

What version are you running on Ubuntu? Did you install it from apt, perchance?

avr-gcc automatically called on arduino-builder binary, let i see what the output of your console log after your compile/upload sketch file and what your the steps tried?

Abu-Ahmed has the right idea on how we can help you. It would be nice if you reproduced the problem on your Ubuntu machine and gave us the exception that it's catching (verbatim). It sounds like you're missing some appropriate libraries. If you did a simple apt-get install arduino on your console, then yeah I believe it's going to give you problems. Refer to Arduino's official page for Ubuntu installation.

In my case, i would tell you compile/upload your sketch Arduino on Ubuntu 17.10 like my owned.
I have

Wemos D1 MINI Board based ESP8266 chip.
Define ttyUSB0 port like my Owned.

Before upload your sketch, you need Arduino Package for Ubuntu in Arduino Official Pages or if you have Arduino Package on your Aptitude Source list / PPA Repository of Arduino with following sudo apt-get install -y arduino. that's same to me.
After your Arduino Package installed, try to following commnand :
cd /path/installation/package/ //for change directory to Arduino Package

ARDUINO-DIR(pwd) //for make environment of Arduino directory

cd $HOME/Arduino/sketch/ //for change directory to your Arduino sketch

ls -l //for list all items in your folder

$ARDUINO-DIR/arduino --verify sketch.ino --board (board) --port (port) --verbose //for compile your sketch

$ARDUINO-DIR/arduino --upload sketch.ino --board (board) --port (port) --verbose //for upload your sketch

NOTE:
e.g --board esp8266:esp8266:d1_mini //for WemosD1Mini board or
e.g --board arduino:avr:uno //for ArduinoUNO board.
e.g --port /dev/ttyUSB0 or /dev/ttyACM0 //if your define ttyUSB0 or ttyACM0 port you have.
See Below to my verbose log appears a avr-gcc and a avr-g++ automatically called in arduino-builder binary to compile all my library defined.

Hope you can get it.

I figured it out. Ubuntu arduino IDE was missing a library. Thank you for helping out

@JustCurious glad to hear that.

@JustCurious which library? It would be nice if you posted the solution as an answer for future visitors.


text:
Making '*' key on keypad a backspace key
Using a 4x3 membrane keypad and I want to make the '*' key a backspace if the wrong number is entered.
I am a newbie and having a hard time trying to figure out how to code that, any help would be great.

int getNumber()
{
  int num = 0;
  char key = myKeypad.getKey();
  while (digitCount <=  1)
  {
    switch (key)

    {
    case NO_KEY:
      break;
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
      num = num * 10 + (key -  48);
      digitCount++;
      break;
    case '*':
      break;
    case '#':
      break;
    }
  key = myKeypad.getKey();
  }

  digitCount = 0;
  return num;
}

Divide your number by 10?

Sorry, don't understand what you mean.

To make room to add a number you multiply by Ten. So to remove that space you divide by 10.

case '*': num /= 10; break; and then you need to echo that to the display (if any).


text:
Krida 4 ch ac dimmer triac fails to initialize from an Arduino
None of my channels initialize. I suspect a driver issue, but I have tried 2 different libraries.
I have this device:
Krida 4 channel
connected exactly like:
GND - > GND
VCC -> 5V
SYNC -> DIGITAL.3
CH1 -> DIGITAL.7

Libraries attempted:
https://code.google.com/archive/p/arduino-timerone/downloads
and the stock Arduino <TimerOne.h> from libraries manager
I tried all the different code samples but here is the most recent.
Code sample:
#include <TimerOne.h>

unsigned char channel_1 = 7;    // Output to Opto Triac pin, channel 1
unsigned char channel_2 = 6;    // Output to Opto Triac pin, channel 2
unsigned char channel_3 = 5;    // Output to Opto Triac pin, channel 3
unsigned char channel_4 = 4;    // Output to Opto Triac pin, channel 4
unsigned char CH1, CH2, CH3, CH4;
unsigned char i=0;
unsigned char delay_time=25;     // delay ms or flashing SPEED
unsigned char clock_tick;        // variable for Timer1
unsigned char CHANNEL_SELECT;    // variable for channel select

unsigned char CH[]={CH1,CH2,CH3,CH4};

unsigned char dim_level[]={5,8,10,12,15,18,20,25,30,35,45,50,55,60,65,70,75,80,82,85,88,92,95};   // don't use this massive for 60Hz
                                                                                // create new massive for 60Hz
void setup() {

  pinMode(channel_1, OUTPUT);// Set AC Load pin as output
  pinMode(channel_2, OUTPUT);// Set AC Load pin as output
  pinMode(channel_3, OUTPUT);// Set AC Load pin as output
  pinMode(channel_4, OUTPUT);// Set AC Load pin as output
  attachInterrupt(1, zero_crosss_int, RISING);
  Timer1.initialize(100); // set a timer of length 100 microseconds for 50Hz or 83 microseconds for 60Hz;
  Timer1.attachInterrupt( timerIsr ); // attach the service routine here

}

void timerIsr()
{
    clock_tick++;

      if (CH[0]==clock_tick)
    {
      digitalWrite(channel_1, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_1, LOW);    // triac Off
    }

      if (CH[1]==clock_tick)
    {
      digitalWrite(channel_2, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_2, LOW);    // triac Off
    }

      if (CH[2]==clock_tick)
    {
      digitalWrite(channel_3, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_3, LOW);    // triac Off
    }

      if (CH[3]==clock_tick)
    {
      digitalWrite(channel_4, HIGH);   // triac firing
      delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
      digitalWrite(channel_4, LOW);    // triac Off
    }
}

void zero_crosss_int()  // function to be fired at the zero crossing to dim the light
{
  // Every zerocrossing interrupt: For 50Hz (1/2 Cycle) => 10ms  ; For 60Hz (1/2 Cycle) => 8.33ms
  // 10ms=10000us , 8.33ms=8330us

    clock_tick=0;
}

void loop() {

for (CHANNEL_SELECT=0;CHANNEL_SELECT<4;CHANNEL_SELECT++)  // fade up
 {
  for (i=22;i>1;i--)
  {
    CH[CHANNEL_SELECT]=dim_level[i];
    delay(delay_time);
  }
 }

delay(2000);

for (CHANNEL_SELECT=0;CHANNEL_SELECT<4;CHANNEL_SELECT++)  // fade down
 {
  for (i=0;i<22;i++)
  {
    CH[CHANNEL_SELECT]=dim_level[i];
    delay(delay_time);
  }
 }
delay(1000);

}

The code uploads error free to one of the many Arduino Nanos (I tried fresh hardware) that I have.
I cannot establish continuity with my load input channel to any of the load output channels. It is though D7 never never does its job and flip the channel open. Nor can I get any continuity on any of the other channels.
The code is supposed to cycling through all of them but no current ever hits any of the 'load' on any of my channels (Chan 1-4).
Deeper inspection of the Arduino with a voltage meter shows that I am getting reverse polarity on my d7 pin. actually, d7 - d4 all have what appear to be incorrect cycles (reverse polarity) on them. These are all the pins that are supposed to be turning on channels. This does not look correct to me at all.
I suspect driver but I cannot find any other libraries to try that look sane.
How do I initialize my d7 Arduino pin correctly to bring my Krida 4 chan triac Load channel live?
or, did I miss something exceptionally ignorant? I am not experienced with this particular module.
photos:

First of all you should test if the SYNC interrupt is working, like turning on one LED or something you can debug. You switch on the mains AC and then you should detect this zero cross interrupt. If not, then maybe you configured an interrupt event on wrong pin.
Further, making do-while loops in interrupt routine is a no go. Your timeISR turns on one triac, then loops for 10us and turns the triac off. Well not so good implementation. You could skip delay, and turn off after another timeISR by making this ISR at 10us instead.
void timerIsr()  //10us
{
    clock_tick++;
    digitalWrite(channel_1, LOW);    // triac Off
    digitalWrite(channel_2, LOW);    // triac Off
    .....
    if (CH[0]==clock_tick)
      {
        digitalWrite(channel_1, HIGH);   // triac firing
      }

I made the code changes  https://bpaste.net/show/428d553e9881  and it stopped the LED from blinking on the device, but all the other behaviors are still the same.

But I am no longer reversed polarity on my arduino.

The reversed polarity is somehow impossible, because you supply the circuit with your Vcc and GND. The device has wired an optotriac to your Arduino outputs. Perhaps you swapped the voltmeter tips?

I can flip that reverse polarity back and forth by changing the code back and forth like a switch. I am using a Greenlee DM-45. Its old but pretty reliable. I can literally watch the flip live.

@boobie, is the problem solved? (you marked the answer accepted)

@Juraj yeah, gross n00b error. I had tested live AC with a 3rd party fan and got no response. But a tradition florescent lamp with an LED bulb fired up. Not sure why, but thats enough for this ticket.


text:
Frequent ON OFF in SSR
I am working on a project on Arduino OLED MAX6675 thermocouple and SSR for my oven.
My problem is when my SSR goes in LOW or HIGH state it  turn ON and OFF several times before going to permanent HIGH or LOW state.
This make my load(Heater) on and off many times. Since the temperature crosses the set-point to change the output state, the process temperature will be cycling rapidly, going from below set-point to above, and back below.
This frequent ON OFF will damage my SSR and heater.
My Question.
Is there any hardware or software solution. To reduce the frequency of ON OFF .
I can’t increase  the delay() time because it make my button input slow.
My codes are below.
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include "max6675.h"

//oled
//oled i2c addresss
#define OLED_ADDR 0x3C
Adafruit_SSD1306 display(-1);
// 128 x 64 pixel display
#define SSD1306_LCDHEIGHT 64

//MAX6675
//Pin initialization
int so = 2;
int cs = 3;
int sck = 4;
MAX6675 thermocouple(sck, cs, so);
float current_temp;
int set_temp;
int const h_temp = 2;

//Button
int button_up = 7;
int button_down = 8;
int button_upv;
int button_downv;

//SSR
int ssr_u = 10;
int ssr_d = 12;

void setup() {
    Wire.begin();
    delay(1000);

    // initialize and clear display
    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(8, 20);
    display.println("Welcome..");
    display.display();
    display.clearDisplay();
    delay(1000);

    //Button
    pinMode(button_up, INPUT);
    pinMode(button_down, INPUT);
    set_temp = 20;
    pinMode(ssr_u, OUTPUT);
    pinMode(ssr_d, OUTPUT);
}

void loop() {
    current_temp = thermocouple.readCelsius();
    delay(100);
    button_upv = digitalRead(button_up);
    button_downv = digitalRead(button_down);

    //button
    if (button_upv == HIGH && set_temp < 180) {
        set_temp = set_temp + 5;
    }
    if (button_downv == HIGH && set_temp > 20) {
        set_temp = set_temp - 5;
    }

    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(5, 10);
    display.println(current_temp);
    display.setCursor(5, 30);
    display.println(set_temp);

    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(30, 40);
    if (button_upv == HIGH) {
        display.println("Up");
    }
    if (button_downv == HIGH) {
        display.println("Down");
    }
    display.display();

    //SSR
    if (current_temp < set_temp - h_temp) {
        digitalWrite(ssr_u, HIGH);
        digitalWrite(ssr_d, HIGH);
        delay(500);
    }
    if else(current_temp > set_temp + h_temp) {
        digitalWrite(ssr_u, LOW);
        digitalWrite(ssr_d, LOW);
        delay(500);
    }
}

Thanks in advance for help

Which arduino board do you use? Are you using a 3.3v arduino board and a counterfeit ssr? Please explain better what you have and how it is powered. Google for hysteresis. You need to put some hysteresis into your sketch.

I am using pro mini 5v and 40 amp SSR.

the keyword is hysteresis http://forum.arduino.cc/index.php?topic=526806.0

Is there any hardware solution like adding a capacitor so that voltage remaining constant for few seconds

Hysteresis will just be way easier in software.

You need to implement hysteresis. Set two temperature points around set_temp. One a little higher to be a limit for turning the heater off and a one a little lower then set_temp to turn the heater on.
You only need to change your if else condition a little
if (current_temp < set_temp - HYST_VALUE) {
  digitalWrite(ssr_u, HIGH);
} else if (current_temp > set_temp + HYST_VALUE) {
  digitalWrite(ssr_u, LOW);
}

you could start with
int const HYST_VALUE = 1;

Is there any hardware solution like adding a capacitor so that voltage remaining constant for few seconds

this is a regulation problem, not simply solvable by hardware. the temperature could oscillate around your set temperature long time. implementing hysteresis is how it is done in all thermostats

I edited the answer

Hello juraj I tried the same as you said but this code freeze loop somewhere. I am doing something wrong somewhere please help.I tried the same code.

Hello juraj I also change my sketch in question please check it.

you have < twice and it is } else if (

Let us continue this discussion in chat.


text:
ESP 12 unusable pins
The ESP 12 board has 22 pins
Are all of them usable?
I understand that there is an external flash memory that is accessed through SPI, but I'm not sure what the impact on the pins is.
And if it is so, then why are the pins available?
Is there a sort of a decoder board that receive as an input, let's say 3 SPIOs and outputs 8 GPIOs?
Is there a way to obtain more GPIO pins?

Like this one?  https://researchdesignlab.com/esp8266-esp-12-breakout-board.html

The flash memory is connected to io 6 to io 11 if it is connected in QIO mode. DIO mode lets two of the pins free. According to Arduino core reference the two pins are 9 and 11. The flash pins are labeled SD and most of them are the first SPI interface of the esp8266. You can't use this SPI pins as digital pins, but supposedly you can connect another SPI device.
Some of the esp8266 'free' pins have some restrictions. Boot configuration pins io 0, io 2 and io 15 need to have some state at boot. io2 not LOW, io 15 LOW and with io 0 flashing mode is activated. The A0 is ADC only pin. And you can't count power, EN, Reset and ground as 'pins'.
You can use a multiplexer or an I2C expansion board to get more pins.


text:
Using AysncUDPMessage for ESP32 to send string data
I am in search for some examples as to how can one use the AsyncUDPMessage in an Application for sending out UDP packets to a host with specific IP address and Port number from an ESP-WROOM-32 (Olimex ESP32-PoE) module?
The Class for AsyncUDPMessage in arduino-esp32 library inherits from Print.
I want to send sensor measurements to InfluxDB in the Line Protocol (InfluxDB specific).
Example
 imu,location=front,nodeid=node1 status=0.00,liac_x=-1.18,liac_y=0.02,liac_z=9.63,eul_x=0.00,eul_y=-6.81,eul_z=0.25 1538507409930

The above mentioned example is stored in the form of a String and the methods to send information via UDP viz. send() sendTo() all mention usage of AsyncUDPMessage as the first parameter.
goal
Send the above measurement to the particular Device's IP and port
udp.sendTo(Message, IPAddress(192,168,3,11), 8089);

I am currently using broadcastTo(const char * data, port) menthod to send information the InfluxDB instance.
Code
void loop(void) {

  DateTime now_time = rtc.now();

 // create a measurement
  influxMeasurement row("imu");
  row.addTag("location", "front");
  row.addTag("nodeid", "node1");

// get information from BNO055
  imu::Vector<3> li_ac = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);
  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);
//  Serial.print(li_ac.x());
//  Serial.print(li_ac.y());
  row.addField("status", 0);
  row.addField("liac_x", li_ac.x());
  row.addField("liac_y", li_ac.y());
  row.addField("liac_z", li_ac.z());
  row.addField("eul_x", euler.x());
  row.addField("eul_y", euler.y());
  row.addField("eul_z", euler.z());

  // add timestamp
  row.addTimeStamp_ms(String(now_time.unixtime()) + String(millis()%1000));

  // print the Line Protocol output
  Serial.println(row.postString());

  // UDP Sending
  char buf[2048]; // make buffer for `broadcastTo()`
  row.postString().toCharArray(buf, sizeof(buf)); // string to char array
  // Serial.println(buf);
  udp.broadcastTo(buf ,8089);

  delay(100);
}

method
I create a Line protocol String, make a buffer, convert the string to char [] and send it out.
Question

how do I use AsyncUDPMessage so I can pass the string to it directly?

I am not sure but will char buf[2048] within a loop is a good idea as every time a buffer allocation might make the ESP32 run out of memory? And if AsyncUDPMessage can avoid this concern?

String has .c_str()

the library has AsyncUDPClient example

Yes but there is not mention of AsyncUDPMessage. there is only AsyncUDPPacket

Use udp.print(row.postString().c_str())
AsyncUDPMessage in AsyncUDP library is only a buffer. It is used only in AsyncUDP send function:
size_t AsyncUDPPacket::send(AsyncUDPMessage &message)
{
    return write(message.data(), message.length());
}

So just connect once and then print the information will send the udp to the destination porT?

udp doesn't connect. only the library takes the server and port parameters in a connect like function. the function can only resolve hostname to IP. but the implementation is hidden in not open source espressif SDK

if you don't need nonblocking UDP sending, then you don't need the AsyncUDP library


text:
Unexpected result with the GSM module A6
I have a GSM A6 module, like this one.
I'm going to use an Arduino Nano as a bridge to communicate with it, I have an external power source (since I read that this module can consume up to 2A at its maximum consumption) (this power supply shares the GND with the module and the Arduino) and I upload the following code in the Nano:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and A6
  mySerial.begin(115200);

  Serial.println("Initializing...");
  delay(1000);

}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

I set the baud rate at 115200 of my SoftwareSerial port (connected to 10 and 11 pins on the ArduinoNano) because (even if the module says that it has auto-detect speed hability) doesn't work if I set the speed at 9600 (or any other), and I modified the SoftwareSerial library for expand the buffer from 64k to 512k (trying to solve this problem) following this page instructions (also: NICE WORK in this page!!!).
And it works ... it works relatively well, I mean:
The AT commands to test (according to the datasheet itself) are AT and ATI (in one I recieve "AT /r OK" and the last one give some usefull information like the OS and other things), and they work, only they do not show me the same answer always, I leave screenshots:

As you can see, the answers are not always exact, there is some garbage characters, and I need them to be exact, because my idea is to create a kind of alarm, in which the Arduino (One, Nano or Mega) sends and receives AT commands. I worked with the SIM900 module before and always received the same answer when I sent an AT command.
So... any help?!

Apparently the SoftwareSerial library have some limitations, so I change the baudrate communication in the moduel ussing this sentence:

AT+IPR=9600

And change the code that I upload to the Nano, changing the baudrate speed in the declaration, from:
mySerial.begin(115200);

to
mySerial.begin(9600);

And now all is well :D


text:
How do I run a bipolar motor with an arduino uno?
At the risk of looking like a complete idiot on the internet, I'll preface with this; I'm incredibly new to this. I'm new even to coding, and not sure what questions I should be asking.
I'm trying to run a bipolar motor with an Arduino Uno. I'm fairly sure it should be as simple as set a pin to high, plug the motor into that pin and a ground and it should run. I did this a week ago, and it worked then.
Now I'm trying to essentially run a modified version of blink with this motor running instead of the LED. Running the code with pin 13 as my positive does still flash the LED. If I set my pin to high with the motor, the motor no longer runs. However, It does run when plugged into the 5V and ground. The motor also runs straight off of the two poles of a 9V battery.
I'm unsure what I'm doing wrong. Do I need to step up the voltage of my pins somehow?
Thanks in advance.
-Alec Rosso
Edit 1:Here's the code:
int motorPin1 = 13;
int interval= 5000;

void setup() {
pinMode(motorPin1, OUTPUT);
digitalWrite(motorPin1, HIGH);
}

void loop() {
digitalWrite(motorPin1, HIGH);
delay(interval);
digitalWrite(motorPin1, LOW);
delay(interval);
}

As far as voltage or current specifications, it says DC 12V.
Edit 2: it is not a stepper motor. The serial number is TS-32GZ370-950. It's apparently a "DC geared motor."
Final Edit: I've got it working using an L298. I used a 9-volt battery in addition to my arduino's 5 volts, and everything works like a dream. Thank you for your help.

@VE7JRO it's possible it's a duplicate, and it would make sense that i'd need a shield or something similar to run it. I'm going to try an L298 motor driver, but my limited expertise make this whole operation somewhat trial-and-error.

If you resolved the issue please "accept" the answer that helped you the most, or make your own answer describing how you solved it. This will help others to realize the problem has been solved.

Just for your knowledge and future reference - Arduino digital pins can deliver maximum of 40mA each. If you power Arduino by USB, Arduino UNO can draw maximum of 1A, and Nano maximum of 500mA. That is, the 5V pin can deliver that current, not a digital pin. Therefore pin 13(digital pin) can deliver 40mA at 5V, which is 200mW power.
Now, looking at your motor, TS-32GZ370-950,from datasheet at maximum efficiency the current needed is 140mA. Stall current is 480mA, therefore you should be able to deliver close to 480mA @ 12V for the motor to work under all possible loads. Now, that is 5.6W or so. Your 5V pin making the motor work simply meant that the load is low to medium. But you are unable to use the motor's full potential anyway.
Your driver choice is ok, because L298 can deliver up to 2 A, which is fine.
The 9V battery(Alkaline I suppose?) will work, but the lifespan will be very very short. You can look at discharge graphs here : https://www.powerstream.com/9V-Alkaline-tests.htm
It will last about 1 hour at moderate load. Consider using other types of batteries. Your motor accepts voltage up until 24V, so feel free to experiment.
Best of luck!

"At the risk of looking like a complete idiot on the internet,"
Without getting personal - you cannot put 10 pounds of potatoes in 5 pounds bag.
AKA you cannot run 12V device with (5V output) Arduino   BECAUSE 12V device / motor requires far more current than Arduino can safely provide.
That is the short version - you probably moved the motor at very slow speed and lucked out before you let the smoke out from the Arduino chip.


text:
HTTP POST/ METHOD to Emoncms doesn't work
So Ive setup the emoncms on my server and posted the example power1:100…power3:300 JSON POST and it logged in my INPUTS.
Now Im trying to send data from my arduino and it seems to post fine, but when I go to the INPUTS its not there for some reason.
Here is my code. Im just posting a temperature value to a new node:
#include "SoftwareSerial.h"
//For DHT22 Grove Pro
#include "DHT.h"
#define DHTPIN A1     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);

String ssid ="myssid";
String password="mypassword";
String server = "www.santiapps.com"; // www.example.com
String uri = "/emoncms/input/post.json";// our example is /esppost.php
#define EMON_APIKEY F("myapikey")

byte dat [5];
String temp ,hum;
String data;
char dataString[200];

SoftwareSerial esp(6, 7);// RX, TX

void setup() {
  esp.begin(9600);
  Serial.begin(9600);
  Serial.println("setup");
  reset();
  connectWifi();
}

void reset() {
  Serial.println("reset");
  esp.println("AT+RST");
  delay(1000);
  if(esp.find("OK") ) Serial.println("Module Reset");
}

void connectWifi() {
  Serial.println("connect to wifi");
  String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
  esp.println(cmd);
  delay(400);
  while (esp.available()){
     String inData = esp.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }

  if(esp.find("OK")) {
    Serial.println("Connected!");
  } else {
    connectWifi();
    Serial.println("Cannot connect to wifi"); }
}

void start_test () {
  //For DHT22 Grove Pro
  static char outstr1[15];
  static char outstr2[15];
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  dtostrf(t, 8, 2, dataString);
  Serial.println(dataString);
}
void loop(){
  Serial.println("loop");
  start_test();
  httppost();
  delay(100000);
}

void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }
  delay(1000);
  String postRequest="POST " + uri + " HTTP/1.0\r\n"+"Host: " + server + "\r\n" + "Accept: *" + "/" + "*\r\n"+"Content-Length: " + strlen(dataString) + "\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n"+"\r\n" + "&node=fortnite&data={a:" + dataString + "}" + "&apikey=" + EMON_APIKEY;
  Serial.println(postRequest);
  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.
  esp.print(sendCmd);
  esp.println(postRequest.length());
  delay(500);
  if(esp.find(">")) {
    Serial.println("Sending..");
    esp.print(postRequest);
    if(esp.find("SEND OK")) {
      Serial.println("Packet sent");
      while (esp.available()) {
        String tmpResp = esp.readString();
        Serial.println(tmpResp);
      }
      // close the connection
      esp.println("AT+CIPCLOSE");
    }
  }
}

Here is my Serial Monitor:
setup
reset
connect to wifi
Got reponse from ESP8266: AT+CWsetup
reset
Module Reset
connect to wifi
Got reponse from ESP8266:
Got reponse from ESP8266: CLOSED
Got reponse from ESP8266: WIFI DISCONNECT
Got reponse from ESP8266: `BԄQR���ȤRN�ɤRN�H��OAT+CWJAP="tha
connect to wifi
Got reponse from ESP8266: %J:E
Got reponse from ESP8266: HըRP=“myssid”,“mypassword”
Got reponse from ESP8266: busy p…
connect to wifi
Got reponse from ESP8266: AT+CWJAP=“myssid”,“mypassword”
Got reponse from ESP8266: busy p…
Got reponse from ESP8266:
Got reponse from ESP8266: O
connect to wifi
Got reponse from ESP8266: AT+CWJAP=“myssid”,“mypassword”
Got reponse from ESP8266: WIFI DISCONNEC
Connected!
Cannot connect to wifi
Cannot connect to wifi
Cannot connect to wifi
loop
31.00
TCP connection ready
POST /emoncms/input/post.json HTTP/1.0
Host: www.myserver.com
Accept: /
Content-Length: 8
Content-Type: application/x-www-form-urlencoded
    &node=fortnite&data={a:   31.00}&apikey=mykey
    Sending..
    Packet sent

    +IPD,422:HTTP/1.1 200 OK
    Server: nginx
    Date: Tue, 02 Oct 2018 21:38:18 GMT
    Content-Type: application/json
    Connection: close
    X-Powered-By: PHP/5.4.16
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Pragm

Here is a snapshot of the posted data when I used this URL directly in my browser:

http://santiapps.com/emoncms/input/post?node=emontx&fulljson={"power1":100,"power2":200,"power3":300}&apikey=mykey
￼=========
Based on jose's suggestion:
I changed this code to:
void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }

//  //CODE USED TO BUILD COMPLETE STRING
  String apiKeyString="apikey=";
  apiKeyString.concat(EMON_APIKEY); //JOIN PARAMETER LITERAL STRING => String Object
  //Serial.println(apiKeyString); //THIS IS NOW A STRING OBJECT
  String nodeData="&node=fortnite&data={\"a\":";
  String combinado=apiKeyString+nodeData; //COMBINE BOTH PREVIOUS STRING OBJECTS
  String finalData=combinado + dataString + "}"; //COMBINE STRING OBJECT WITH CHAR[]
  Serial.println("finalData");
  Serial.println(finalData);
  //unsigned int tamano = strlen(dataString);
//  char postThis[100] = finalData;
//  //ADDING THIS TO POSTREQUEST +finalData; && changing length for strlen(finalData)

  delay(1000);
  String postRequest="POST " + uri + " HTTP/1.1\r\n"+"Host: " + server + "\r\n" + "Accept: *" + "/" + "*\r\n"+"Content-Length: " + finalData.length() + "\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n"+"\r\n" + finalData;
  Serial.println("postRequest");
  Serial.println(postRequest);
  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

but now I dont even get the HTTP200OK response.  The result is:
loop
31.30
finalData
apikey=myKey&node=fortnite&data={"a":31.30}
postRequest

Your Serial monitor output shows the content of the POST as:
&node=fortnite&data={a:   31.00}&apikey=mykey
I can't tell if the & are actually in your serial monitor, or if your copy/paste did some kind of HTML format attempt, but & is wrong and should be &
Your JSON data is not proper JSON
{a:   31.00}
should be
{"a": 31.00}

Strangely, your serial monitor output also writes Host: www.myserver.com, which doesn't match your code, where server was assigned www.santiapps.com, so that makes it difficult to trust that the serial output you show actually came from the code.

Ok I fixed the & format issue, it was indeed copy/paste problem.  It is the proper output, I just went through it and replaced ssid, password, apikey and server name.  Everything else is the same.  How do I get the "" around the letter a?  Im trying this: "&node=fortnite&data={" + "a:" + dataString + "}"; but I get this => &node=fortnite&data={a:29.00}

You can escape the quote character with a backslash: "&node=fortnite&data={" + "\"a\":" + dataString + "}"

Thanks, one last thing, it was brought to my attention that my Content Length for the POST request needs to be the length of everything from &node....up until the json data...{"a":29.40}.  Could that be the cause of the post not working?

You send a content-length generated by strlen(dataString). This is not quite right. The HTTP Post payload portion is found in this part of your code: &node=fortnite&data={a:" + dataString + "}" + "&apikey=" + EMON_APIKEY. Calculate the length of that to find the content-length. I also noticed that you start your POST content with &, but you don't need one at the beginning. It is just to separate fields, like node=fortnite&data={a:" + dataString + "}" + "&apikey=" + EMON_APIKEY

I added my most recent try but it also fails to post.


text:
backup battery for FeatherWing DS3231, RTC
I am working with slightly modified example code for the Adafruit FeatherWing DS3231 RTC (real time clock) board. The DS3231 chip itself is from Maxim. Since the cell is described as a "backup battery" a literal interpretation suggests that you don't need the backup battery in order to operate the board if the board itself is powered and you don't mind that the device cannot remember the time when board power is lost. I might be taking the term "backup battery" too literally since it doesn't seem to work.
The Adafruit (Arduino) code:
> #include <Wire.h>
> #include "RTClib.h"
> RTC_DS3231 rtc;
> void loop()
>{
>     rtc.adjust(DateTime(2018, 1, 1, 0, 0, 0));
>     DateTime now = rtc.now();
>     Serial.print(now.year());
>     Serial.print(" ");
>     Serial.print(now.month());
>     Serial.print(" ");
>     Serial.print(now.day());
>}

The output is:
2165 165 165

The Maxim datasheet says this about the VBAT line which is the line between the DS3231 chip and the missing backup battery:

Backup Power-Supply Input. When using the device with the VBAT input
  as the primary power source, this pin should be decoupled using a
  0.1μF to 1.0μF low-leakage capacitor. When using the device with the VBAT input as the backup power source, the capacitor is not required.
  If VBAT is not used, connect to ground.

So I connected it to ground and it makes no difference. I can't buy a battery until tomorrow morning. Can somebody please confirm that the backup battery is actually essential. EDIT: I installed a battery and it makes no difference.
Aside: A good reason for not having a backup battery if possible is to have fewer user serviceable parts.

Does your code work properly with a battery?

@Gerben, I installed a battery and it makes no difference.

Glad to hear you figured the problem out. Nice job.

The problem was a bad connection for one of the serial lines.
I found the solution at this link.
The battery is not necessary to make this work.

Your code does not include the line(s) necessary to initialise the rtc.
in setup, you need something like
rtc.begin()

If you've followed the instructions from the Adafruit website for installing the RTC library:

Start Arduino IDE
File->Examples->RTClib->ds3231

This will open the RTC usage example.
Else, go to the example on the Adafruit Github page
look to the setup() code and see how they initialise the device

I have the call to rtc.begin in my setup. I only show the loop in the above code.

Using the exact same code as the Adafruit example which is a read-only file so I know it is correct (Files>Examples>RTClib>ds3231) the year is still 2165, month 165, day 165.

Assuming your code is in Arduino IDE "loop".
Assuming

rtc.adjust(DateTime(2018, 1, 1, 0, 0, 0));
  initializes the rtc.

Your code should be continually printing the rtc.adjust value.
Hence move the rtc.djust out of the "loop" and provide some kind of delay , say 1 second, to print rtc every second.
Then we can take a look why your are getting wrong data.

Removing that line makes no difference. Every time through the loop the year is 2165.

Does  rtc.adjust returns anything - true / false /error ? Your rtc is not initializing / running .

I think .adjust is a void function.

The Adafruit example at File>Examples>RTClib>ds3231 also says the year is 2165.

OK  its RTC 23:30 here ( no pun intended  , so I'll tackle this tomorrow.


text:
Arduino Hello World in Serial monitor
Hi we were asked to program something which when i enter something in the serial monitor it prints Hello world but the catch is it only prints hello world under the conditions that your input in the serial monitor is a 3 bit input and after that i need to have a code which then stops it from printing over and over again.
my only problem is that i don't really know how to count the number of bits of an input and also to stop it from printing continuously.
void setup() {
  Serial.begin(9600);

}

void loop() {
  String readSerial;
    String input;
    while(Serial.available() > 0){// put your main code here, to run repeatedly:
    delay(2);
  input.concat(String((char)Serial.read()));
  return input;
  }
  Serial.println("HELLO WORLD");
}

Is this a school class assignment?

Please add your code.

Yes it is. And its also an assignment before the actual lesson

What exactly do you mean by 3-bit input? The serial interface only sends whole bytes. Is this about specific values in 3 of the 8 bits of a single byte?

it says here that 3 ready to be read character(bytes) is that 3 bits? or am is my assumption wrong?

Some separate comments: "// put your main code here, to run repeatedly:". This is a comment that belongs to the loop function, not to the while loop. Also "return input" is not an advised way of coding. One reason because return in the middle of a function is bad coding practice, but moreover it returns a type while the function (void) does not expect anything to return. I don't know what you want to program so I cannot give more useful comments.

Judging from the comments, you lag some basic knowledge. To really learn, what you are supposed to learn in this assignment, you should review your learning material or C/C++ and Arduino Tutorials on the web. Here I will only give you some hints with reasoning, that may help you in solving the assignments task. (Unfortunately it is not really clear, what exactly the task is here)

The Serial interface of the Arduino (an UART interface) sends the data in bytes, one at a time and one after another (hence the name serial). 1 byte is a series of 8 bits, each of them with a value of 1 or 0. Together the 8 bits form a value, that can also be expressed as a decimal value from 0 to 255. For example 01001011 is the binary equivalent of the decimal number 75. (For further explanations google the binary number system) The byte data can also be expressed as characters, as they are defined in the ASCII standard. Every binary value refers to a specific character. This is what happens in the serial monitor of the Arduino IDE. (For more explanations google ASCII)
Since the data is send serially, there may appear some delays in the transmission, which are unnoticeable by humans, but the Arduino is fast enough, so that the Serial.available() command may return 0, because at that moment a little delay in the transmission occurred. Hence it is important to catch the whole message, before trying to work with it. You can do this by either counting bytes (waiting until at least 3 bytes are available in the buffer) or by marking the end of the message with a special character (for example the newline character '\n'). There are a lot of tutorials on the web how to do both. You can start with Majenko's blog.
You can get the number of bytes, that were received, with the return value of Serial.available(). It will return 3, when there are 3 ready to be read bytes in the buffer.
If you define a variable inside the void loop(), it will be thrown away when the function ends and redefined, when the function starts again (In the Arduino world the void loop() function is called again and again forever). You will loose all content, that was written to this variable. If you want to persist data over the executions of the void loop() function, you can define the variable outside of any function at the top of your program. This variable is then global and will be defined only once at the start of the program and hold for the whole lifetime of the program.
As wrote in the comment you should not return a value from a void function, since void mostly means, that there is no return value. And returning from the void loop() function will only restart this function (since we are in the Arduino world).
You can ditch the delay(2). There is no need for it. And if it only works with the delay, then something else is not correct and you are just working with the symptoms instead with the real issue.

Also you should not try to build everything on your own and reinvent the wheel. Instead try to look at the examples, that come with the Arduino IDE. For example the SerialEvent example, which shows how to receive a serial message (which is ended by a newline character '\n'). Also have a look at the other related examples. If you understand, how they work, you will be able to do the assignment without any problem.

Hi again , i think  I'm close to getting it but one quick question is there anyway of resetting the serial.available(); value  and reverting it back to 0 ?

You can do Serial.read() without using the returned value, until Serial.available() returns 0.

Assuming that the sketch should print "Hello World" when the input character has 3 bits high. Here are a few different variants of counting the number of bits set in a byte.
int bits1(int c) {
  int res = 0;
  for (int i = 0; i < 8; i++) {
    if ((1 << i) & c) res = res + 1;
  }
  return (res);
}

int bits2(int c) {
  int m = 0x80;
  int res = 0;
  do {
    if (m & c) res++;
  } while (m >>= 1);
  return (res);
}

int bits3(int c) {
  int m = 0x80;
  int res = 0;
  do {
    res += (m & c) != 0;
  } while (m >>= 1);
  return (res);
}

#define bits4(c) __builtin_popcount(c)

#define bits bits4

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

void loop() {
  if (Serial.available() > 0) {
    int c = Serial.read();
    if (bits(c) == 3) {
      Serial.print((char) c);
      Serial.print(':');
      Serial.print(c, BIN);
      Serial.println(": Hello World");
    }
  }
}