Read both battery voltage and analog sensor value with NodeMCU ESP8266 I have a soil sensor that reports value once every 5 minutes, deepsleep in between.
Is there a way to also report battery voltage (with ESP.getVcc())?

To get the battery voltage reading to work I need to set ADC_MODE(ADC_VCC); but that disables the reading of the sensor.

to read VCC voltage, ADC pin must be kept unconnected. Additionally, the following line has to be added to the sketch:
  ADC_MODE(ADC_VCC);

The setting of a purpose of the analog pin of esp8266 is at low level and must be projected into the compiled binary. It can't be changed at runtime.

On esp8266 if you want to use the power sensing or to have more ADC you must use an external I2C ADC.

reference


Arduino : How to control AC Motor Speed Controlling speed of DC Motor from arduino could be done via PWM and H-Bridge, but how can i control an AC Motor?
Thank you.

I'll google it for you "AC motor speed control": google search

Short answer will be that it depends on motor. Frequency changer (or variable frequency drive if you need variable speed) is usual choice.


Simultaneously reading data from multiple serial ports I have three sensors latched on to three different Arduino devices.

The respective Arduino devices are connected on to an Arduino Mega on Serial1, Serial2 and Serial3.

The data from each device component (i.e., an Arduino with an accompanying sensor) were sent in data packets with different starter byte headers ('$' , '/' & '#' ) accompanying the buffered data from each individual device component onto the Mega on the Tx/Rx lines.

My question here is, how can I simultaneously read out all the data from the different serial ports on the Arduino mega sketch?

My question here is how can I simultaneously read out all the data from the different serial ports on the arduino mega sketch.

As you are using several serial ports data can already be received simultaneously. Each serial software class (Serial1, Serial2, Serial3) has an internal buffer where data is stored until it is read.

You only need to read the data before the internal buffers are filled and there is a risk for over-flow. Check that data is available and read as usual per serial port. Avoid any blocking calls to avoid buffer over-flow.

Cheers!


Getting two trinkets to talk to each other via the serial pins I'm trying to make a quick proof of concept of two trinket M0s talking to each other via their RX and TX pins and I'm not able to get it working.

I uploaded sender and receiver sketches to two trinkets:

//sender.ino
char state[10] = "hello";

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

void loop()
{
    Serial.write(state, 5);
    delay(1000);
}

//receiver.ino
char state[10];

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

void loop()
{
    Serial.println("reading bytes");
    Serial.readBytes(state, 10);
    Serial.println(state);
    delay(1000);
}

After the uploads I wired the two trinkets together, jumping the RX of the first to the TX of the other and TX of the first to the RX of the other. I also connected their grounds to have a common ground.

I plugged the sender into a battery and the receiver into my computer. The problem I'm running into is that when I look at the serial monitor for the receiver instead of getting the expected "hello" I'm getting broken strings of "TestingOpen":

I double checked the pinout diagram and guide for the Trinket M0 to make sure I was using the correct RX/TX pins (pin 3 for RX, 4 for TX) and it all seems fine but obviously something is still going wrong.

Anyone know what I'm missing or misunderstanding?

1) you should use if (Serial.available()) before starting to read with readBytes. now you print random memory

2) readBytes is blocking. it waits for the next character until a timeout. default timeout is 1 second. after "hello" was received it waits a second. you could use readBytesUntil and some 'separator' character for example '\n' (new line)

3) readBytes returns the count of bytes read. you should use it to terminate the buffer

void loop()
{
  if (Serial.available()) {
    Serial.println("reading bytes");
    size_t l = Serial.readBytesUntil('\n', state, 10);
    state[l] = 0;
    Serial.println(state);
  }
}


Avoid global variables with classes I want to avoid global variables when using my own classes in Arduino. Here is a example.

void setup(){
/* setup here */
  classA objectA;
}

void loop(){
  objectA.someMethod();
}

I know that my compiler will complain about it (out of scope, etc) but is it possible to do that or just forget it and use globally?

Thanks in advance!

If you want a variable to be available within more than one function it has to be global. There is no other possible way of doing it.

If you are only using the variable in the loop() function and nowhere else you can declare it static in loop(), which has the same effect of making it global, but it is only possible to see it within loop().

You can make a pointer global, then create a new object in setup() (using new...) and assign it to the pointer, but that has the potential of making a mess of your heap and should be avoided unless absolutely necessary. Also it's pointless, because you don't gain anything over having the object statically created in the global scope.


Trouble when avoiding delays I am new to Arduino and I am learning how to avoid using delay.

I have written some code to move my servo by 20° using delays, but can only move the servo once with my current code. In setup(), I assign the servo 150. The next value the servo receives is 15, which it performs. It does not iterate through the following values though. I have been using this guide, BlinkWithoutDelay, with no luck.

Here is my code:

#include <Servo.h>
Servo myservo;
unsigned long previousMillis = 0;
const long interval = 1000;

    void setup() {
       myservo.attach(9);
       myservo.write(150);
    }

   void loop() {
       unsigned long currentMillis = millis();

       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(15);
       }
       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(35);
       }
       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(65);
   }

You are resetting the timer on the first phase [write(15)] instead of after the last phase [after write(65)]! The previousMillis = currentMillis should be only after the last phase, before the loop repeats. Not only that, but the time at which each phase executes needs to be different. Currently every if() statement is set to run after interval has elapsed. If, for example, you wanted interval to be the delay between each phase, you could use interval*1 on the first phase, interval*2 on the second, and interval*3 on the third. For example:

   if (currentMillis - previousMillis <= interval * 1) {
        // Runs from interval*0 to interval*1;
        myservo.write(15);
   }
   else if (currentMillis - previousMillis <= interval * 2) {
        // Runs from interval*1 to interval*2;
        myservo.write(35);
   }
   else if (currentMillis - previousMillis <= interval * 3) {
        // Runs from interval*2 to interval*3;
        myservo.write(65);
   }
   else {
        // Runs once after interval*3;
        // *or* runs on first iteration when previousMillis is zero;
        previousMillis = currentMillis;// Reset the loop;
   }

To put the above logic in English:

write(15) while time is between 0 and 1 intervals;
write(35) while time is between 1 and 2 intervals;
write(65) while time is between 2 and 3 intervals;
reset the loop once time reaches 3+ intervals.

Note the use of else if instead of simply if on consecutive statements. This prevents more than one code block from running on the same iteration of the loop().

Edit: I highly recommend having a small delay (like 1ms) somewhere in the loop(), such as at the end. It would be a bad idea to constantly run the write() function when the value is the same as on the last call.

On the other hand, if your starting value is indeed 150 and the loop should start only after interval*1, you may want to iterate from interval*2 through interval*4:

   if (currentMillis - previousMillis <= interval * 1) {
        // Runs from interval*0 to interval*1;
        // Do nothing; servo is set to either 150 or 65 during this time;
   }
   else if (currentMillis - previousMillis <= interval * 2) {
        // Runs from interval*1 to interval*2;
        myservo.write(15);
   }
   else if (currentMillis - previousMillis <= interval * 3) {
        // Runs from interval*2 to interval*3;
        myservo.write(35);
   }
   else if (currentMillis - previousMillis <= interval * 4) {
        // Runs from interval*3 to interval*4;
        myservo.write(65);
   }
   else {
        // Runs once after interval*4;
        // *or* runs on first iteration when previousMillis is zero;
        previousMillis = currentMillis;// Reset the loop;
   }


Attach() resets servo's angle I'm working on code that will control micro servo. I use generic servo and built-in library for controling servo. Microcontroller is generic STM32.
Controlling servo Works as expected. But I don't want next behavior - attach() function sets servo to 180°(maybe 0°, not sure).
In my project I want next:

Servo stays at angle before going off/reboot
Servo goes to 90° after turning on/reboot

I googled about this problem and tried with write(90); before attach() in setup() function. Servo goes to 90° but after like 50ms attach() stops write(90) function and it goes back to 180°. So this didn't solve my problem.
Next I've open Servo.cpp and found that attach() function contains next code:

    bool Servo::attach(uint8 pin,
                   uint16 minPW,
                   uint16 maxPW,
                   int16 minAngle,
                   int16 maxAngle) {
    timer_dev *tdev = PIN_MAP[pin].timer_device;

    if (tdev == NULL) {
        // don't reset any fields or ASSERT(0), to keep driving any
        // previously attach()ed servo.
        return false;
    }

    if (this->attached()) {
        this->detach();
    }

    this->pin = pin;
    this->minPW = minPW;
    this->maxPW = maxPW;
    this->minAngle = minAngle;
    this->maxAngle = maxAngle;

    pinMode(pin, PWM);

    timer_pause(tdev);
    timer_set_prescaler(tdev, SERVO_PRESCALER - 1); // prescaler is 1-based
    timer_set_reload(tdev, SERVO_OVERFLOW);
    timer_generate_update(tdev);
    timer_resume(tdev);

    return true;
}

What should I do to fix this problem? Servo will adjust angle of PCB which holds LEDs. PCB will be in case and angle of 90° is default angle. 0°/180° will either destory servo or brake case/PCB/something else.

You can avoid using the attach(); method by programming without the servo library.

  for(x=0; x<150; x=x+1)
  {
    digitalWrite(Servomotor, HIGH);
    delayMicroseconds(2350); //Change the delay here to change the angle it goes to
    digitalWrite(Servomotor, LOW);
    delayMicroseconds(18550);
  }

This is an example code for how it worked for me. It sends a pulse to the servo which makes it turn a bit until it reaches a "barrier".


Converting an array of uint8_t to a char array I'm trying to convert this array uint8_t data[] in the code below to a character array to be printed in the serial monitor. However, when I run this code I see a blank screen. What am I doing wrong?

Serial.begin(115200);
uint8_t data[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x00,0x01,0x02,0x03,0x04,0x05};
Serial.println((char*)data);

When you cast as char *, println thinks you are passing it a string. It will try to print it as a string and stop on the first 0x00.

You can use Serial.write to send the array as integers (no conversion):

Serial.write(data, sizeof(data));

If you want to send the ASCII representation of these numbers, use a loop. Serial.print will convert:

int count = sizeof(data) / sizeof(data[0]);
for (int i = 0; i < count; i++) {
    Serial.print(data[i]);
}
Serial.println();


if(Serial.available()>0) VS while(Serial.available()>0) What's the low level difference between if(Serial.available() > 0) and while(Serial.available() > 0)? On what conditions would you choose one over the other?
I was testing my codes on 4 daisy chained 74HC595 shift registers controlling multiple LEDs. The code takes in a number from the serial monitor and displays it out in binary via the LEDs. Here is the code below that worked:
#define latchPin 8  //ST_CP pin of 74HC595
#define clockPin 9  //SH_CP pin of 74HC595
#define dataPin 7   //DS pin of 74HC595

//number of 74HC595 in daisy chain
#define numOfDaisyChainReg 4

byte registerVal[numOfDaisyChainReg];

void setup() {
    Serial.begin(115200);
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);
    pinMode(dataPin, OUTPUT);
}

void loop() {

  while (Serial.available() > 0) {

    uint32_t num = Serial.parseInt();
    Serial.print(num, DEC);
    Serial.print(" : ");
    Serial.println(num, BIN);

    //breaks the recieved int into 4 unsigned bytes
    //and assigns the byte value into the "registerVal" array
    for (uint8_t a = 0; a < numOfDaisyChainReg; a++) {
      registerVal[a] = (num >> (numOfDaisyChainReg - (a + 1)) * 8) & 0xFF;
      Serial.print("registerVal["); Serial.print(a); Serial.print("] = ");
      Serial.println(registerVal[a], BIN);
    }

    //writes the 4 bytes into the shift register
    digitalWrite(latchPin, LOW);
    for (uint8_t x = 0; x < numOfDaisyChainReg; x++) {
      shiftOut(dataPin, clockPin, MSBFIRST, registerVal[x]);
    }
    digitalWrite(latchPin, HIGH);

  }

}

Originally, I had if(Serial.available() > 0) and that didn't work as no LEDs lit up despite everything else in the code working as it was expected. Switching to while(Serial.available() > 0) solved that problem. Anyone have any idea why that's the case?

I figured out why while(Serial.available()>0) and if(Serial.available() > 0) would or would NOT work in terms of my shift register code. It has to do with the serial monitor line feed and carriage return setting! If it isn't set to no line ending, it will either not register the input number or reset it back to zero right after the input is read. Learned to always check the line return option in the serial monitor! With this solved, the original question is nothing more than a general if vs while statement; which I already know the answer.
Thanks to everyone who contributed to this question! It did help me understand a lot more about Serial.available() in general. @jsotola gave a really good article. Combined with this YouTube video, it makes a lot more sense now.


Accessing Arduino Yun from Internet I am trying to access my Arduino Yun from the internet, and it's not quite working. I have correctly port forwarded the port 5555 from the router to the Yun (verified I am able to access my many other NAT'd resources).

I can access the Yun from my internal network.

In the Arduino sketch I have this (among many other things). Mainly taken from example sketches.

#include <Bridge.h>
#include <HttpClient.h>
#include <YunServer.h>
#include <YunClient.h>

YunServer server;

void setup {
   // Listen for incoming connections on port 5555
   server.noListenOnLocalhost();
   server.begin();
}

Is server.noListenOnLocalhost(); the right one to use to access from the outside world?

Well, I'm not familiar with the Yun, but the first thing that stands out is the missing

Bridge.begin();

line apparently needed to initialize the Bridge library that you use.

And you do have something like

YunClient client = server.accept();

and "more" in the main loop (or a function where applicable) of your code, right ?

And yes, noListenOnLocalhost() is the correct function for serving external clients.


Local char* - keeps its value Sorry for novice question in Arduino, but I'm trying to figure out why res is keeping its value when up_cmd0 is being called again.

for example - if num=8 in first run and the result is :up_cmd0_res: 8, and second run num=12, the result is: up_cmd0_res: 812

void up_cmd0(){
  char num[8];
  char *res = "up_cmd0_res:";
  itoa(counter2, num, 10);
  strcat(res ,num);
  client.publish(inTopic,res);

char *res = "up_cmd0_res:";

In principle, res should be a const char *. Const because it is
pointing to a literal string, and you cannot (ar at least, you are not
supposed to) change a literal string. The compiler should warn you on
that... if you enable compiler warnings.

  strcat(res ,num);

This is very wrong. strcat() expects as its first argument an pointer
to a modifyable array large enough for the resulting concatenation
(and the terminating \0). In other words, you have to allocate enough
room for the whole string, then fill the beginning of the allocated
array with the first substring, then only call strcat():

char res[24];
strcpy(res, "up_cmd0_res:");
strcat(res, num);

What happened is that you initially had, in memory, something like this:

<----- memory reserved for the string literal ---->
'u' 'p' '_' 'c' 'm' 'd' '0' '_' 'r' 'e' 's' ':' NUL
 ^-- res

On the first call to stracat(), you overwrite the terminating NUL and
end up with

<----- memory reserved for the string literal ---->
'u' 'p' '_' 'c' 'm' 'd' '0' '_' 'r' 'e' 's' ':' '8' NUL
 ^-- res

Note that the new terminating NUL is now occupying a byte in memory that
hasn't been allocated for this purpose. You have likely overwritten some
global variable. Next time you call strcat(), you again replace the
terminating NUL and continue to overwrite whatever happens to be stored
in this part of the RAM. Expect a crash or program misbehavior.


always detects same pin as HIGH even when its not connected Im practicing with an arduino UNO board (I'm a begginer) and I'm trying to turn some LED's on depending on which analog pin is connected to 5V.
Here's my code:
int statusLed = 11;
int out1 = 2;
int out2 = 3;
int out3 = 4;
int out4 = 5;
int in1 = A0;
int in2 = A1;
int in3 = A2;
int in4 = A3;
int statusLedBrightness = 3;
int incBrillo = 3;
int fadeDelay = 5;

void blinkFade(int pin){
  analogWrite(pin, statusLedBrightness);
  statusLedBrightness = statusLedBrightness + incBrillo;
  if (statusLedBrightness <= 0 || statusLedBrightness >= 255){
    incBrillo = -incBrillo;
  }
  delay(fadeDelay);
  }

void wait(){
  digitalWrite(out1, LOW);
  digitalWrite(out2, LOW);
  digitalWrite(out3, LOW);
  digitalWrite(out4, LOW);
  blinkFade(statusLed);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(out1,OUTPUT);
  pinMode(out2,OUTPUT);
  pinMode(out3,OUTPUT);
  pinMode(out4,OUTPUT);
  pinMode(in1, INPUT);
  pinMode(in2, INPUT);
  pinMode(in3, INPUT);
  pinMode(in4, INPUT);
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (analogRead(in1)>=500){
    Serial.println("1: ");
    Serial.println(analogRead(in1)); //Print "1" and the read of pin A0
    turnOff();
    digitalWrite(out1,HIGH);
  }
  else if (analogRead(in2)>=500){
    Serial.println("2: ");
    Serial.println(analogRead(in2));//Print "2" and the read of pin A1
    turnOff();
    digitalWrite(out2,HIGH);
  }
  else if (analogRead(in3)>=500){
    Serial.println("3: ");
    Serial.println(analogRead(in3));//Print "3" and the read of pin A2
    turnOff();
    digitalWrite(out3,HIGH);
  }
  else if (analogRead(in4)>=500){
    Serial.println("4: ");
    Serial.println(analogRead(in4));//Print "4" and the read of pin A3
    turnOff();
    digitalWrite(out4,HIGH);
  }
  else{
    Serial.println("Stand By");
    wait();
  }

}

The problem Im having is when I connect a wire from 5V to any analog pin (A0 to A3) it always runs this segment of code:
Serial.println("1: ");
Serial.println(analogRead(in1));
turnOff();
digitalWrite(out1,HIGH);

By my understanding it's detecting as if it always was A0 the one that is connected to 5V but i dont understand why is this happening or how to solve it.
This is a screen capture of serial monitor when 5V is connected to pin A2. It should print "3:" and the reading
[]
1

You're not showing your schematic but I'm sure that you are simply leaving the Ax pins OPEN when you are not connecting them to your +V line.  In that case they are "floating" and as such they can float HIGH or LOW or just about anywhere.  What's happening is that when you hook up +V to any of them, that has the side-effect of pulling at least A0 HIGH along with it since you have allowed it to float.
Two things to do here:

Don't allow lines to float and expect deterministic behavior.  Tie them to +V or to GROUND when you are not using them.
Pull the Ax lines to +V or GND via a resistor like 10K Ohms.  This will prevent them from floating and will give you predictable results.


Limiting motors to a specific position using while and if loops I am currently building a prosthetic hand using an Arduino MEGA, an Advancer Tech Myoware sensor, and 3 TB6612FNG Dual H-bridge breakouts. I have the EMG sensor sending an analog value to the Arduino and want to use that value to open or close the hand.

The problem I have is that the motors cannot turn more than 1 second without tightening too much and breaking the hand, so I want to place a limit on the while loop telling them to move that will restrict their movement under the specified conditions to one second. Also, when the analog voltage is no longer present, I need the motors to reverse their movement so the hand releases.

Here is the code I have where move(motor #, speed, direction) is the function to move the hand (1 = forward, 2 = backward).

void loop(){

  int EMGv = analogRead(EMG);

  while(EMGv >= 900){
    move(0, 255, 1); //motor 1, full speed, left
    move(1, 255, 1); //motor 2, full speed, left
    move(2, 255, 1); //motor 3, full speed, left
    move(3, 255, 1); //motor 4, full speed, left
    move(4, 255, 1); //motor 5, full speed, left

  }

To reiterate. I need the motors to move while the EMG value is over 900, BUT not move more than 1 second, even if the value is 900 for 5 seconds. I then need the motors to move one second backwards when the value dips below 900.

Thanks!

You can use millis() feature

unsigned long starttime;

void loop(){

  int EMGv = analogRead(EMG);
  starttime=millis();
  while(EMGv >= 900){
    if (millis()-starttime < 1000) //limit on 1000ms
    {
    move(0, 255, 1); //motor 1, full speed, left
    move(1, 255, 1); //motor 2, full speed, left
    move(2, 255, 1); //motor 3, full speed, left
    move(3, 255, 1); //motor 4, full speed, left
    move(4, 255, 1); //motor 5, full speed, left
    } else {/*turn off motor here*/}
  }


How do I prevent Arduino from running on startup? I just uploaded a sketch to my Arduino Leonardo, which presses a key on the keyboard. The code was unfortunately bugged and now as soon as the Arduino is powered on, the key is being pressed.

When I try to upload a new sketch that fixes the issue, I am unable to do so as the Arduino is executing the sketch, preventing the new sketch from being uploaded.

How can I prevent the Arduino from executing the sketch once powered on? Pressing the reset button or wiring it in does not work...

The Leonardo should wait a couple of seconds after resetting to see if a new sketch arrives.

Power off the board completely (remove the USB cable).
Hold down the Reset button, and keep it held down (or, run a jumper wire from the RESET pin to the GND pin). This stops the problem sketch from starting.
Still holding down Reset, reconnect the USB cable.
Start uploading a sketch that does not have this problem (eg. Blink)
Once the IDE reports "Uploading" release the Reset button (or remove the jumper wire).


MPU6050 Sending Bad values for Angular Velocity The mpu gives me perfectly fine values for the yaw, pitch, and roll position of the chip, but when I use mpu.getRotation(&gx, &gy, &gz) to obtain the current angular velocity of the chip, the values returned are awful. I wrote a program in Processing to graph the data from my Arduino, and this is what it looks like:

I suggest you click on the picture and zoom in a bit because it's difficult to see. The green line represents zero (0), the Pink line represents the angular position of the mpu6050 chip, obtained from mpu.getYawPitchRoll..., and the Blue line represents the angular velocity on the same rotational axis.

A few extra things to note:

The scale between the Pink and the Blue lines is slightly off, but that shouldn't matter for this purpose.
The time-frame for this graph is about 16s.
Before being graphed, the raw gx value is divided by the gyro's sensitivity scale factor, 131, and then converted from radians to degrees.
In addition to this, it is also put through a complementary filter, so the whole formula looks like this: rollRate = (0.7*rollRate) + (0.3*(-180 * gx / 131 / M_PI));

As you can see, the measurements for angular velocity (Blue) make almost no sense when graphed next to the angular position (Pink).

My question is this: What can I do to clean-up/filter these angular velocities and get rid of all the errors? I need these values to be accurate enough to be used in something like a drone PID.

Things I have tried:

Complementary filters of various proportions.
Adjusting the MPU's built in low-pass filter.

Thanks for any suggestions.

At last! I have discovered the solution.

Quick Solution for those who don't like reading: Amend the previous rollRate formula to rollRate = (0.7 * rollRate) + (-0.3 * gx / 16.4);. Or, if you don't want the filter, rollRate = -1 * gx / 16.4;

The problem starts with the function mpu.getRotation(&gx, &gy, &gz) which accepts int16_t types for gx, gy, and gz. Since int16_t is a 16 bit integer, it has a maximum range of -32,768...+32767. The reason this integer type is used is because the output range for the gyro is -32750...+32750, which fits nicely into the 16-bit integer's range.

The problem was that when I converted these values to a readable angular velocity (and complementarily filtered) using  rollRate = (0.7*rollRate) + (0.3*(-180 * gx / 131 / M_PI)); , the gx value was multiplied by -180 in part of the calculation. This means that if gx was high enough initially, it would have rolled over to -32786 and ruined the whole calculation, causing the horrible spikes in the graph.

At the same time I discovered this problem, I also realized that converting from radians to degrees was unnecessary, as the gyro output was already in units of degrees (just scaled by a sensitivity factor). After that big face-palm, I revised my rate formula to the following: rollRate = (0.7 * rollRate) + (-0.3 * gx / 16.4);. You will notice the scale factor has changed from 131 to 16.4. That is because the gyro range is actually +/-2000 deg/s by default, not 250 deg/s. I tried to change it back to +/-250 with mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_250);, but after examining the graph, it appeares that mpu.dmpGetYawPitchRoll(ypr, &q, &gravity); does not account for this setting change, and resulted in the ypr overshooting and then leveling out to its correct value after a delay. I decided not to mess around with the quaternion container, q, and just accepted the lower sensitivity.

Like the previous image, I suggest zooming in.


Should BLK and GRN of Pro Mini be connected to upload sketch? Is the following connector is valid for Arduino Pro Mini (no BLK and GRN)?

I was told to make a certain Arduino application, and got some Arduino Pro Mini  (ATmeag328 3.3V 8 MHz) with the connector above.

Everytime I tried to upload an example sketch 'Blink', the IDE complains (verbose enabled):

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x83
...
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x83

resp may differ (I saw 0x1f and 0x83)

But, according to the official document,  I think that I should use some FTDI thing, which has 6 pins including BLK and GRN.

I wonder whether I can use the existing 4-pin connector, or whether I must use 6-pin FTDI connector.

If you look at the picture in your link, you would see that BLK is ground (GND) and GRN is DTR, that is used to reset the board and enter the bootloader for programming.

As Majenko said, without DTR you will need to press the reset button at the right time, to enter the bootloader.


Accelerometer fix values I use Arduino Uno with an Accelerometer ADXL345-gy-291 (the full name of the ship) i did hook it up like this

Note I'm using SPI Communication, that was the right one to use in my case.
when I plug in my Arduino here what does my serial monitor give me

as you can see, it sends back fixed values no matter the movement of the ship is.
the code I use is :

#include <SparkFun_ADXL345.h>
ADXL345 adxl = ADXL345(10);

void setup(){

  Serial.begin(9600);
  Serial.println("SparkFun ADXL345 Accelerometer Hook Up Guide Example");
  Serial.println();
  adxl.powerOn();
  adxl.setRangeSetting(16);
  adxl.setSpiBit(0);
  adxl.setActivityXYZ(1, 0, 0);
  adxl.setActivityThreshold(75);
  adxl.setInactivityXYZ(1, 0, 0);
  adxl.setInactivityThreshold(75);
  adxl.setTimeInactivity(10);
  adxl.setTapDetectionOnXYZ(0, 0, 1);
  adxl.setTapThreshold(50);
  adxl.setTapDuration(15);
  adxl.setDoubleTapLatency(80);
  adxl.setDoubleTapWindow(200);
  adxl.setFreeFallThreshold(7);
  adxl.setFreeFallDuration(30);
  adxl.InactivityINT(1);
  adxl.ActivityINT(1);
  adxl.FreeFallINT(1);
  adxl.doubleTapINT(1);
  adxl.singleTapINT(1);
}
void loop(){
  int x,y,z;
  adxl.readAccel(&x, &y, &z);
  Serial.print(x);
  Serial.print(", ");
  Serial.print(y);
  Serial.print(", ");
  Serial.println(z);
  ADXL_ISR();
}
void ADXL_ISR() {
  byte interrupts = adxl.getInterruptSource();

  if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){
    Serial.println("*** FREE FALL ***");
  }

  if(adxl.triggered(interrupts, ADXL345_INACTIVITY)){
    Serial.println("*** INACTIVITY ***");
  }

  if(adxl.triggered(interrupts, ADXL345_ACTIVITY)){
    Serial.println("*** ACTIVITY ***");
  }

  if(adxl.triggered(interrupts, ADXL345_DOUBLE_TAP)){
    Serial.println("*** DOUBLE TAP ***");
  }

  if(adxl.triggered(interrupts, ADXL345_SINGLE_TAP)){
    Serial.println("*** TAP ***");
  }
}

so I wonder what was the mistake I made there?

You need to level-shift the Arduino's 5V signals to the module's I/O range of 1.7 - 3.6 V if you want to use SPI; that is, if you haven't damaged it already. I suggest you follow the tutorial here though. It employs I2C instead of SPI but is specific to your particular module. There are no level-shifters needed in this case. Simply connect VCC and CS to 3.3 V, the I2C pins to 3.3 V through 4.7k pull-ups and the GNDs together.


Password.h and keypad.h change pass sketch for Arduino I have a fixed password. If letter "D" is pressed on the keyboard and the correct password is entered, the fixed password will be then changed. This newly entered password is now the correct password, until the user decides again to change password. It is not working. How to fix it?

#include <Keypad.h>
#include <Password.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns

const char keys[ROWS][COLS] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'}
  };
const byte rowPins[ROWS] = {9,8,7,6};
const byte colPins[COLS] = {5,4,3,2};

Keypad    keypad { makeKeymap(keys), rowPins, colPins, ROWS, COLS };
Password passwd = Password("123A4");
char passwd2;

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

void loop() {

  char key = keypad.getKey();
   if (key != NO_KEY){
      delay(60);
      switch (key){
      case 'D': changepasswd(); break;
      case '*': checkpasswd(); break;
      case '#': passwd.reset(); break;
     default: passwd.append(key);
      }
   }
}

void checkpasswd() {

  Serial.print(passwd2);

   if (passwd.evaluate()){
      Serial.println(" OK.");
   } else {
      Serial.println(" Wrong password!");
   }
   passwd.reset();
}

void changepasswd() {
  char key = keypad.getKey();
      delay(60);
      Serial.print(key);
      passwd2 += key;
      passwd.set(passwd2);

   Serial.print("Password changed to ");
   Serial.println(passwd2);

}

The logic of your function is garbled:

Function checkpasswd(): Most of the function is ok, but you don't need to send passwd2 through Serial, since it doesn't have anything to do with this function. You only use the variable for setting a new password. You can ditch this print statement.
Function changepasswd(): Here lies the problem. Most likely getKey() returns NO_KEY here, which is defined as the null character. So, when outputting it to Serial, you don't see anything there (The null character marks the end of a string in C/C++). You set the password to be the null character, which cannot every be inputted by the user. Also there lies another pitfall: The Arduino Playground Site for the Password library states for the set() function:

  Warning: The new password should be a global variable (not a local
  function variable) as this function copies a pointer to the new
  password into the library, not a copy of the password.

Since the key variable is only local, after the function the Password library has it's internal pointer pointing to a now freed memory space. At some other point in the program this space might be written again, effectively changing to password to something else.

And lastly the function does not contain any loop, so only 1 character will be inputted and the newly set password can only be 1 character long. The buffer variable passwd2 is of type char, so also only 1 character. What you really need there is a char [] (character array).

Here is a bit of code (not tested), that should implement this correctly:

char passwd2[6]=""; //global buffer for new password
                    // 6 bytes, because a C string has to end with the null character

void changepasswd(){
    for(byte i=0;i<5;i++){
        char key = NO_KEY;
        while(key == NO_KEY || key=='*' || key=='#' || key=='D') key = keypad.getKey();
        passwd2[i] = key;
        delay(60);
    }
    passwd2[5] = '\0'; //ensure correct string ending
    passwd.set(passwd2);
}

Note the following points:

This implementation blocks the programs execution, until a full valid password has been typed. It will ignore all invalid characters, that you use for other purposes (#, * and D).
The passwd.set(passwd2) is actually only necessary the first time, we change the password, to let the Password object have a pointer to our buffer. After that we technically can change the password directly in the buffer, without calling the set() function. I included it here for readability and making the code a bit more fail prove (against wrong futher coding).
This is hardcoded to accept only 5-digit passwords. If you want passwords with arbitrary length, you can start programming from this basis.
Debouncing buttons with a simple delay() may be not enough at some point. But as I understand the source code of the Keypad library, it also includes code for debouncing, by only checking every 10ms for a changed button and returning NO_KEY everytime else.


bitClear doesn't work on most significant bit I'm currently working on a project where I read a 32 bit sequence.
The digitalPin is always HIGH when no sequence is received and starts oscilating with about 1kHz when the sequence starts (RC5).
I am setting and clearing bits of an uint32_t depending on which signal is on the digitalPin.
It seems to work very well with every bit except of the MSB.
Here a short code snippet to show what I mean:
const short irPin = 8;
const short msgDelay = 250;

uint32_t data = 0xFFFFFFFF;
long msgArrived = 0;

void setup(){
  Serial.begin(115200);
  pinMode(irPin, INPUT);
}

void loop(){
  long now = millis();

  if( (!(PINB & 1)) && ((now - msgArrived)> msgDelay)){
    msgArrived = millis();
    bitClear(data, 31);

    Serial.println(data, BIN);
  }
}

This gives me an output of
11111111111111111111111111111111

I have already tried
bitClear(data, 32); -> 11111111111111111111111111111111
bitClear(data, 30); -> 10111111111111111111111111111111

So every output is right, but not the when I try to clear the msb.
Has anyone experienced a similar behaviour?

uint32_t data = 0xFFFFFFFF;
Serial.println(data, BIN);
data = 0xFFFFFFFF;
bitClear(data, 30);
Serial.println(data, BIN);
data = 0xFFFFFFFF;
bitClear(data, 31);
Serial.println(data, BIN);

On my mega outputs:

11111111111111111111111111111111
10111111111111111111111111111111
1111111111111111111111111111111

Are you sure you aren't mistaking the fact that println doesn't print leading 0's for the number being nothing but 1's? Try printing as hex, then all the numbers will be the same width:

FFFFFFFF
BFFFFFFF
7FFFFFFF


Programming ATtiny85 with Arduino-IDE and an 8MHz external oscillator I have a digispark ATtiny85 development board and I am using the Arduino IDE to program it along with the Arduino UNO as my hardware programmer.
I have successfully burned the fuses for both the internal 1 and 8 MHz RC oscillators using the original Arduino as ISP sketch (you'll understand why I said original in a moment), but as my application needs precise timing, I would like to use an external oscillator, however, every time I tried to burn/program the bootloader/fuses using the Arduino IDE and using the original Arduino as ISP, the avrdude spits the infamous (Yikes).
I searched online and found an updated version of the Arduino as ISP sketch, which is supposed to an updated version, it has only one downside, which is, it can't do anything other than burn/program the bootloader/fuses, meaning that it can't be used to program the ATtiny85 like the original Arduino as ISP could do.
So without hesitating, I tested it to burn/program the bootloader/fuses for the internal 1 and 8 MHz RC oscillators, and it worked perfectly, and as expected, it fails to upload the code.
But the original Arduino as ISP successfully uploaded the code.
When I tried to burn/program the bootloader/fuses for the external 8MHz crystal oscillator using the updated Arduino as ISP, it worked flawlessly... until I noticed that the ordinary Arduino as ISP can not upload the code anymore and I am presented with the infamous (Yikes!) error.
Let me elaborate the difference in the connections between the two sketches.
The updated Arduino as ISP generates a clock signal on pin #9, which connects to the CLKI of the ATtiny85 (AKA Pin #2 "PB3"), while the original Arduino as ISP does not utilize this pin at all.
I found the updated Arduino as ISP on the electronics stack exchange forum, but unfortunately I lost the link to the question which contained why is this updated Arduino as ISP is better.
I can provide both codes though if someone needs them.
I have my crystal connected in both cases, burning/programming the bootloader/fuses and while trying to upload my code.
This is the infamous (Yikes!) error which I was talking about.

This is my current wiring.

Please note that I connect pin #9 to the CLKI of the ATtiny85 (AKA Pin #2 "PB3"), only when I am using the updated Arduino as ISP.
This is the actual wiring.

My two questions are:

How could I burn/program the bootloader/fuses of the ATtiny85 to use an external oscillator of 8MHz or 16 MHz?
How could I upload my application code after burning/programming the bootloader/fuses?

I hope the answers elaborate how the connections would differ, if it would.
Thank a lot in advance.

If you look at the Digispark Schematic you'll see resistors and Zener diodes attached to XTAL1 and XTAL2:

These are for the USB D+ and D- signals that the Digispark bit-bangs.  I deeply suspect that the crystal is just not going to resonate with these parts connected.
To get back to a working Digispark you'll probably have to inject signal onto XTAL1 again and reprogram the fuses to internal OSC.


How to wire L293D chip to a nodeMCU? How do I wire an L293D motor controller chip to a nodeMCU?
I have tried to follow the instructions from this tutorial: lastminuteengineers.com
One problem. I don't have a 5v pin?
Are there any alternative ways to wire this?
All of the other tutorials i see, only say to use a special other motor driver board with an L293D embedded in it, and with extras connected to the board.

I figured it out. I am putting a logic level converter On the 3v pin to step it up to 5v


DMX on the Arduino without additional driver chip I recently saw this video where the creator controlled a DMX light via the Arduino. There he used the pins 3 and 4 for the data on the Arduino Duemilanove. As DMX library he used DmxSimple.

Based on my research DMX is RS-485 and for this there's a driver chip required.

So I have three questions about this:

Why do all sources I found say that there's a driver chip required when it seems to work without?
I got a Arduino Leonardo compatible device (Devduino). Is it possible to control DMX like stated above on this platform?

The physical layer of a DMX interface is based on differential signaling over an RS485 link.  This is exactly what is said here on the DMX Arduino.cc page.

A differential signal (like RS485 or USB) can travel greater distances than signals which reference ground (like RS232, I2C or SPI).  This is because noise, which affect both sides of a differential signal, can be canceled out at the far end when one of the signals is inverted then added to the other by the differential receiver.

Connecting one side of a differential receiver to ground and driving the other side with logic level voltage is not recommended.  Even if it worked and did not cause harm to the transmitting processor nor the differential receiver the signal will likely be susceptible to undesirable noise.

RS485 is a ubiquitous standard and likely several easily sourced designs exist for the Arduino.


Recommend an Arduino Uno shield to monitor the state of 5 DPDT electrical switches I have a project where I need to monitor the state of 5 DPDT electrical switches with Arduino Uno. Also, the Arduino board will be measuring the output from 3 thermocouples on 3 of the analogue pins as input and sending signals to open and close 3 relays for heaters on the 3 of the digital pins as output. The data with the state of the microswitches and the measurements from the thermocouples will be send over a serial connection to a PC.
I think I need a shield with at least 20 inputs for monitoring the 5 DPDT electrical switches (5 x 2 x 2). The common of the switches will be connected to a common rail. Can I use an I2C extension shield for this purpose? Is this going to create an issue with the serial connection? Any specific shield recommendations?

If you're really set on measuring the state of every single connection of every single switch (though I still don't see the need) then yes, you'll need 20 IO connections.
You could create those with IO expanders (MCP23017 for example), or you could use multiplexing.
Instead of 4x5 (20) IO pins you'd instead need 2+10 (12) IO pins.
Treat all the "Common" connections as the rows of a keypad and all the NC and NO connections as the columns of a keypad. Add a smattering of diodes to isolate everything, and you can then scan through the switches one at a time checking each of the two switch states.
You can read more about keypad matrices here.


Control/count rotations of a DC motor Using an Arduino and an L293D IC, can I control the number of rotations a DC motor makes? Or can I only control the direction and speed of the motor?

I purchased a two-wheeled robot platform to learn Arduino programming and electronics. The platform is here: http://www.robotshop.com/en/dfrobot-2wd-mobile-platform-arduino.html

Each wheel is controlled by a DC motor. I followed Adafruit's tutorial (https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing) to control the motors with the help of an L293D IC.

Now I realize that I can't directly control the rotations of the motor. I can control the direction, voltage, and time of the rotation. For example: turn forward at 50% voltage for 500 milliseconds.

But that's difficult to translate into actual rotations. The speed of the motor varies according to voltage (like if I switch from 2AA batteries to 4AA's) and weight (adding sensors slows the motors down). Every time I change voltage or weight, I have to guess how much voltage/time causes a single rotation.

I think I should just buy stepper motors. Before I do that, I'll ask the community: Is there a way to control DC motors by rotations rather than time?

Stepper would be heavy and battery consuming, as Ignacio says.

Pololu makes an encoder for a wheel: http://www.pololu.com/product/1217, but obviously you can implement this in other ways too.


Replace 6 pin on/off switch on Power Bank with 3pin or 2pin? I'm looking to finish up my project in a box and i'm using a battery bank to power the Leonardo micro pro and other components. The bank has a little on/off which on it which has 6 pins underneath.

To make the project neater I wanted to fit an on/off rocker switch to the project box making it look better and providing a more substantial switch. Mostly the on/off rocker switches come in 3 pin or 2 pin connections though. Is it possible for me to join it the 6 pin combining some of the pins in some way or not? I can also pick up another battery shield which has a 3 pin switch, again could I combine that with a 2pin if required or do I need to use a 3 pin rocker with it?

Some pictures of what i'm (or could be) using

(Current power bank, on/off switch on the right side in the middle, 6 pins)

Possible smaller power bank for my project with 3 pins on the on/off switch (bottom left side)

Two pin rocker switch

Three pin, two way rocker switch

Looks like only 2 of the 6 pins are used. It's a simple on-off. The switch itself is a "Double Pole Double Throw", but the two poles are tied together to make it single pole (like a 3 pin switch), and one throw is ignored, making it 2-pin.

You can see on the underside of your board which pins are tied together with traces. Bridge those pin pairs to turn the board on.


Supply 5V to Arduino I am building a quadrocopter with an Arduino Uno as control unit. I know I can supply 5 volts to the 5V pin, but my ESCs produce 5.5 volts, which I measured with my multimeter. Will this voltage drop to 5 volts when I connect the Arduino and if not are 5.5 volts to the 5V pin a problem?

Edit:

My Arduino was running well for a couple of days on this setup with 5.5 volts to the 5V pin but died yesterday. By dying I mean the ATmega doesn't execute any code anymore, the L LED doesn't blink, and even a loopback test fails, which is a sign of a defective USB connector. But I am faced with the same challenge. Should I run my Arduino on 14.4 Volts from my 3S LIPO to Vin or supply 5.5 volts to the Vin pin?

Actually I just realised when I measure the voltage from the ESCs they deliver 9 point something volts for half a second when connecting the multimeter, I guess this voltage spike killed the Arduino.

I'm going to assume you are using the UNO model - or any other board based around the Atmega328p.

According to the datasheet the voltage limits are 1.8v to 5.5, with an absolute maximum of 6v.
You should be fine - but if you are able to get the voltage down closer to 5 volts, I would recommend doing that instead.


Is there any way to flash sketches using custom firmware? I am using HIDUINO as my firmware (flashing via dfu-programmer), and to upload sketch I need to re-flash original firmware, upload sketch and then flash HIDUINO again.

Is there a way to flash sketches without reflashing original firmware?

I assume you mean you are reprogramming the USB interface chip, which means you no longer have a UART pathway through to the ATMega328P. If so then yes, you can provide your own USB interface in parallel by connecting an FT232 (or similar) breakout board direct to the ATMega328P chip just like you would on a breadboard Arduino:

FTDI TX -> Arduino RX (Yellow)
FTDI RX -> Arduino TX (Blue)
FTDI DTR -> 100nF Capacitor -> Arduino RESET (Green)
FTDI GND -> Arduino GND (Black)

The capacitor is required with later versions of avrdude and newer versions of the Arduino IDE since the DTR signal is now held LOW rather than being pulsed as it used to be.  This is to combat a change in the FTDI drivers that meant that the DTR stopped being driven at all and broke the auto-reset facility.  So now we need a capacitor to convert a constant LOW into a short low-going pulse to initiate a reset without locking it all up.


Can't get 4 digit 7 segment display to show different values I'm an Arduino newbie having problems getting a 4 digit 7 segment display to work. The display is connected to a 74HC595 and the setup is from the elegoo tutorial 28 (I think it is download only).

I figured how to control which number to display, but all 4 digits always share the same number, so it is always like 1111, 5555, 9999 etc.

I've heard about something called multiplexing which might do the trick, but I can't adapt it to my project yet, missing too much experience.

This is the code that toggles between 2222 and 8888.
I want to be able to display any number like 1234 though.

Any help is very appreciated.

int latch=9;  //74HC595  pin 9 STCP
int clock=10; //74HC595  pin 10 SHCP
int data=8;   //74HC595  pin 8 DS

void setup()
{
  pinMode(latch,OUTPUT);
  pinMode(clock,OUTPUT);
  pinMode(data,OUTPUT);
}

void Display(unsigned int num)
{
  digitalWrite(latch,LOW);
  shiftOut(data,clock,MSBFIRST,num);
  digitalWrite(latch,HIGH);
}

void loop()
{
    Display(91);
    delay(1000);
    Display(127);
    delay(1000);
}

You have a common cathode display and all your cathodes are tied to ground through resistors. You have no way at all of separating out the different digits.

You cannot directly drive such a display with a shift register like that - you need a more direct connection to the Arduino (it needs to be high speed) and rapidly switch each cathode on and off in sequence to display each of the four numbers one after another.

Also the resistors should be in the 8 anodes, not the 4 cathodes.


How to store a function in a constant? I'm trying to do something to this affect:

const string first_color = strip.Color(0, 60, 0, 0);

With the intended outcome being that I could use first_color wherever I'd have used strip.Color(0, 60, 0, 0) before.

You pretty much need a helper function to do that; a small local function that calls strip.Color() with the intended arguments and returns strip.Color()'s return value if there is any.

int first_color(void)
{
   return(strip.Color(0, 60, 0, 0));
}

(assuming strip.Color() returns an int) which you would call with:

value = first_color();

If strip.Color() is a void function, then delete the 'return(' and one ')', fix the definition of first color to be void instead of int, and of course, don't try to use any return value from first_color().


Standalone chipset, power regulation & pinout I have succesfully (or so the ide says) burned a bootloader on an ATMega328P-PU chipset, and uploaded my sketch on it.

It appears a voltage regulation is absolutely needed, if I want to solder a pcb with the standalone chip, rather than an arduino. Is that correct? Can I build one out of my starter kits parts (assortment of transistors, diodes, zeners, resistors and capacitors)?

In the meantime, I would like to make sure the chispet is functional. Can I power it from GND/5V of an arduino? Will it take care of that power regulation?

If I can, what is the correspondance between the arduino pins, and the ATMega328P-PU pins? I have this page here : http://www.learningaboutelectronics.com/Articles/Atmega328-pinout.php
referencing the chipset pinout. Am I correct in assuming there is a correspondance with the arduino pinout in the reading order of this chart, ie. :

PD0 to PD7 are Rx, Tx, digital pins 2 to 7 on the arduino, PB0 to PB5 are digital pins 8 to 13, and PC0 to PC5 are A0 to A5 on the arduino?

Thanks for reading.

Voltage regulation is needed if the voltage you are providing to the chip is outside (or can drift outside) the allowed range for the chip to operate.

At the upper limit that is 5.5V. The lower limit is 1.8V. Note that at lower voltages you can only reliably run at lower clock speeds.

If your power source is between those two voltages (say a 3.4V LiPo battery) then you don't need a regulator.

If your power source is above 5.5V (say a 9V PP3 battery [urgh]) then you definitely need a regulator.

A proper regulator is quite a complex device, and it is highly unlikely that you have the components to make one.  A simple, very inefficient one, though, can be made using a resistor and a 5V Zener diode if you have one.

Until you have your own regulator of whatever form, yes, you can power the chip from the 5V pin of the Arduino.

The pin mapping for the chip -> Arduino IO numbers is in the file pins_arduino.h for the Uno variant in the IDE.  In the top of that file is this handy drawing:

// ATMEL ATMEGA8 & 168 / ARDUINO
//
//                  +-\/-+
//            PC6  1|    |28  PC5 (AI 5)
//      (D 0) PD0  2|    |27  PC4 (AI 4)
//      (D 1) PD1  3|    |26  PC3 (AI 3)
//      (D 2) PD2  4|    |25  PC2 (AI 2)
// PWM+ (D 3) PD3  5|    |24  PC1 (AI 1)
//      (D 4) PD4  6|    |23  PC0 (AI 0)
//            VCC  7|    |22  GND
//            GND  8|    |21  AREF
//            PB6  9|    |20  AVCC
//            PB7 10|    |19  PB5 (D 13)
// PWM+ (D 5) PD5 11|    |18  PB4 (D 12)
// PWM+ (D 6) PD6 12|    |17  PB3 (D 11) PWM
//      (D 7) PD7 13|    |16  PB2 (D 10) PWM
//      (D 8) PB0 14|    |15  PB1 (D 9) PWM
//                  +----+
//
// (PWM+ indicates the additional PWM pins on the ATmega168.)


Problem with the Frequency meter code I am trying to build a frequency meter using Interrupts and Timer1, which works as if the system receives an Interrupt it would get the timer's data and would calculate

  Signal's Frequency = 1 / (Counter * Timer's Period) => F_s = F_t/TCNT

but the result is way off, and it does not even make sense. I have had altered my code to look that if the timer's data is not valid or sth, but the number that the timer counter has counted is sth that I expect.

Here is my code:

int f=0;
char msg[50];

void setup()
{
  Serial.begin(115200);
  noInterrupts();           // disable all interrupts
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  TCCR1A = 0;
  TCCR1B = 0;
  OCR1A = 0;
  OCR1B = 0;
  TCCR1B |= (0<<CS12)|(1<<CS11)|(0<<CS10);    // Clock 2MHZ
  TCNT1  = 0;
  TIMSK1 = 0; // disable timer overflow interrupt
  interrupts();
  attachInterrupt(1,pin_ISR,RISING);
}

void pin_ISR(){
  //digitalWrite(13,!digitalRead(13));
  f = 2000000/TCNT1;
  TCNT1=0;
}

void loop()
{
  sprintf(msg,"Humidity:%d \n",f);
  Serial.print(msg);
}

As stated in my comment, your code is kind of fine. Id mostly works,
but it looses a few microseconds on each iteration. If you are looking
at multi-kHz frequencies, you probably want to avoid loosing
microseconds. The solution is simple: never reset the counter. I
changed you ISR as follows:

uint16_t previous_counter;

void pin_ISR(){
    uint16_t counter = TCNT1;
    f = 2000000/(counter - previous_counter);
    previous_counter = counter;
}

and now it gives the correct frequency... on average. There are some
variations though, dues mostly to delays caused by other interrupts.

Edit 1: If you want to avoid the fluctuations caused by other
interrupts, your best bet is probably to use the input capture feature
of Timer 1.

Edit 2: Here is why your measurement was somewhat off. Your original
ISR essentially does something like this:

void pin_ISR() {
    uint16_t temporary_value = TCNT1;
    loose_some_time();
    TCNT1 = 0;
}

The time you loose in the ISR is the part of the signal period you are
not measuring, which means you are underestimating the period by that
much. In the ISR you posted, this is mostly the time taken by a 32-bit
division, which is quite significant. A simple improvement would be to
clear TCNT1 right after reading it:

void pin_ISR() {
    uint16_t temporary_value = TCNT1;
    TCNT1 = 0;
    loose_some_time();
}

and now the average period you measure is almost right. It is not
perfect though, as the whole reading and writing of TCNT1 takes
8 CPU cycles.

The alternative I am suggesting, where you never clear the timer, is
the correct way of measuring a period with a timer interrupt: you don't
loose a single CPU cycle. The best way is to use input capture: you get
rid of the software-induced jitter.

Note: You should also take care of the very valid points raised in
Jot's answer, about making f volatile and reading it with interrupts
disabled.


RSSI stop sketch on a gboard (atmega) I have this function in my code and works fine (it returns a valid value, I put this value into a int variable outside function), but when end the function (or continue the code), my sketch stop/die...

///FUNCION PARA RSSI XBEE///
byte rss() {  ///PARA RSSI
union {byte B; char C;} atCmd[3];
AtCommandRequest atCmdReq;
AtCommandResponse atResp;
byte respLen, *resp, dBm;
strcpy(&atCmd[0].C, "DB");
atCmdReq = AtCommandRequest(&atCmd[0].B);
atResp = AtCommandResponse();
xbee.send(atCmdReq);
if (xbee.readPacket(5000)) {
   if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
       xbee.getResponse().getAtCommandResponse(atResp);
       if (atResp.isOk()) {
           respLen = atResp.getValueLength();
           if (respLen == 1) {
               resp = atResp.getValue();
               dBm = resp[0];
                  return dBm;
           }
           else {
             //  Serial.println("Unexpected response");
           }
       }
       else {
         //  Serial.println("ERROR");
       }
   }
   else {
     //  Serial.println("Unknown response");
   }
}
else {
 //  Serial.println("No response");
}
}///fin rss()

¿Any tips?

Your function is only returning a value when everything works OK. If an error occurs, the problem is reported to serial but it doesn't return anything. It seems likely that this could cause stack corruption which could make the program stop.

A simple solution would be to put return 0; (or some other number) just before the end of the function.


#define VS local static const char Could someone give me a hint regarding what would be the best practice to save memory: should I #define strings or use local static const char arrays?

Code example, option #1:

#define         LCD_LIMIT   "Number of hours"
...
setup(){
    DisplayData(LCD_LIMIT, actual_Data);
}
...
void DisplayData(const char *theme, String data){
}

Code example, option #2:

setup(){
    DisplayData(actual_Data);
}
...
void DisplayData(String data){
    static const char theme[] = "Number of hours";
}

Cheers

The #define will be substituted in at compile time. So as far as memory usage goes

#define MYSTRING "hello world"
DisplayData(MYSTRING);

and

DisplayData("hello world");

are completely identical.

but

static const char theme[] = "hello world";
DisplayData(theme);

Will store the text in memory and then call DisplayData with a pointer to that memory location. This will require one memory pointers worth of memory extra (unless that is the compiler is being smart that day and realizes it can substitute in the string and save a few bytes).

However if you are using the same string twice or more then things are different.

The static const will only include the string once and then point to it each time, each reference to the string adds only a couple of bytes to the code size.
If you #define the string then every time it is referenced the whole string is inserted into the code at a cost of n+1 bytes where n is the string length.


Switch case problem in Arduino code I am trying to develop an IR remote for appliances. I have written Arduino code for this purpose. I have used switch case to determine an action from the corresponding IR decode result (HEX), but I am not getting the output.

My code is:

#include <IRremote.h>

int RECV_PIN = 6;
int led = 13;//1FE50AF
int led1 = 12;//1FED827

boolean previousState=LOW;
boolean previousState1=LOW;
boolean state;
boolean state1;
IRrecv irrecv(RECV_PIN);

decode_results results;

void setup() {
  Serial.begin(9600);
  pinMode(13,OUTPUT);
  pinMode(12,OUTPUT);
  irrecv.enableIRIn();// Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    switch(results.value) {
       case '0x1FE50AF':
       if (previousState == LOW) {
         state=HIGH;
         digitalWrite(led,state);
         Serial.println("LED ON");
         previousState=state;
       } else {
         state=LOW;
         digitalWrite(led,state);
         Serial.println("LED Off");
         previousState=state;
       }
       break;

       case '0x1FED827':
       if (previousState1 == LOW) {
         state=HIGH;
         digitalWrite(led1,state1);
         Serial.println("LED ON");
         previousState1=state1;
       } else {
         state1=LOW;
         digitalWrite(led1,state1);
         Serial.println("LED off");
         previousState1=state1;
       }
       break;
    }
    irrecv.resume(); // Receive the next value
  }
}

Replace all:

case '0xZZZZZZZZ':

with:

case 0xZZZZZZZZ:

That's because value in decode_results structure is declared as unsigned long, 0xZZZZZZZZ is an unsigned long, but '0xZZZZZZZZ' is not (actually, it should not even compile).


What is the sizeof() Arduino's built in HIGH and LOW? This might be a stupid question to ask but I'm curious. I decided to test this myself and I got a value of 2 for both HIGH and LOW, why would it output 2?

In Arduino AVR Boards, HIGH and LOW are currently macros:

https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/Arduino.h#L40-L41

#define HIGH 0x1
#define LOW  0x0

This means that sizeof(HIGH) is equivalent to sizeof(0x1). 0x1 is an integer constant. The default type of integer constants is int. On an 8 bit microcontroller like the ATmega2560 used by your Arduino Mega, an int is 16 bits.

That is why sizeof(HIGH) returns 2 (16 bits / 8 bits/byte = 2 bytes).


Integrating 2 push buttons to toggle the LED ON and OFF Hey guys need your help in verifying out this program about toggling the LED ON and OFF using 2 push buttons.What i actually want is to let my LED stay ON when i press and even leave the push button-1 , and on pressing and leaving the push button-2 i want the led to turn off and no matter how many times i press the push button-1 i want it to turn ON the LED and the push button-2 should only turn off the LED.but with my program i am only able to see the LED to be at HIGH state,It is not shifting to LOW state on clicking push button-2.

This is my sketch :-

    /* LED CONTROLLED WITH 2 PUSH BUTTON PROJECT
       BY ARSH BANSAL

 CIRCUIT :-
 i) LEDPIN CONNECTED PIN 13.
 ii) PUSHBUTTON1 CONNECTED TO PIN 8.
 iii) PUSHBUTTON2 CONNECTED TO PIN 7.
 iv) BOTH THE PUSH BUTTONS CONNECTED PARALLELY, EACH WITH A 1K PULLUP RESISTOR AND BOTH THE PUSH BUTTONS CONNECTED TO 5V SUPPLY.
   */

 int ledpin = 13;
 int pushbutton1 = 8;
 int pushbutton2 = 7;
 boolean lastbuttonstate1 = LOW;
 boolean lastbuttonstate2 = LOW;

 void setup()
 {
   pinMode(ledpin,OUTPUT);
   pinMode(pushbutton1,INPUT);
   pinMode(pushbutton2,INPUT);
 }

 void loop()
 {
   if ( digitalRead(pushbutton1)== HIGH && digitalRead(pushbutton2) == LOW && lastbuttonstate1 == LOW )
    { digitalWrite (ledpin,HIGH) ;}

   else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW && lastbuttonstate1 == HIGH)
    ; { digitalWrite (ledpin,HIGH) ; }

    if ( digitalRead(pushbutton1)== LOW && digitalRead(pushbutton2) == HIGH  && lastbuttonstate2 == LOW)
    { digitalWrite (ledpin,LOW) ;}

   else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW  && lastbuttonstate2 == HIGH)
    ; { digitalWrite (ledpin,LOW) ; }
    }

You are better off, in this case, remembering the state of the LED not the state of the buttons:

If the LED is OFF and BUTTON1 is PRESSED then turn the LED on.
If the LED is ON and BUTTON2 is PRESSED then turn the LED off.

For example:

void loop() {
    static bool ledState = false; // LED is off by default
    if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
        digitalWrite(ledpin, HIGH);
        ledState = true;
    }
    if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
        digitalWrite(ledpin, LOW);
        ledState = false;
    }
}


AtTiny analog read always 1023 I am trying to replicate Low power LED firefly project. So what I'm trying to do is to do an analog read from a LED, to detect light. To simplify it a bit, I am using different pins and different leds for IN and OUT. The code:

#define PIN1 don't use this pin! /*this is RESET*/
#define PIN2 3
#define PIN3 4
#define PIN4 don't use this pin! /*this is GND*/
#define PIN5 0
#define PIN6 1
#define PIN7 2
#define PIN8 don't use this pin! /*this is VCC*/
#define ANL1 PIN7
#define ANL2 PIN3
#define ANL3 PIN2

// the setup function runs once when you press reset or power the board
void setup() {
  digitalWrite(PIN3, LOW);
  pinMode(PIN3, INPUT);
}

#define BLINK true
// the loop function runs over and over again forever
void loop() {

  const int value = analogRead(PIN3);
  if(value>=1023) {
    pinMode(PIN2, OUTPUT);
    digitalWrite(PIN2, HIGH);
    delay(500);
    digitalWrite(PIN2, LOW);
    delay(3);
  }
  else {
    delay(1);
  }
}

This is the setup. I am using much smaller resistor, but I'm still getting 1023 on analog read, as indicated by the output led always being on:

simulate this circuit – Schematic created using CircuitLab

What's wrong?

In this article the following steps are used when using an LED as a light detector:

Light up the LED by making the anode positive (logic one) and the
cathode negative (logic zero) - this fully discharges the LED as a
capacitor.
Charge up the capacitor by making the anode negative and the cathode
positive, as this is a small capacitor it will take no time at all
in other words for as short a time as you can.
Put the diode into the measurement mode, by making the anode
negative (it already is) and the cathode connected to an analogue
input.
Make a measurement of the analogue voltage, this is a reference
level to be used later.
Wait while the photon current is integrated - the longer the more
sensitive but too long and effects other than photo current
dominate.
Measure the voltage again and subtract it from the reference value
you took before the integration time. This figure is your light
reading.

Looking at the code in the above question it is not apparent where you switch from forward bias to revers bias.  Also, it does not appear there are two samples taken and the difference between the two samples is found.


Can't make my stepper motor run clockwise and counterclockwise with AccelStepper Library I'm relatively new to arduino thus need your help to figure out why my stepper motor doesn't rotate clockwise and counterclockwise. All I could do was to make it rotate only in one direction.

Here is my code:

#include <AccelStepper.h>

int pos=16000;
AccelStepper stepper(1,4,5);

void setup() {
stepper.moveTo(pos);
stepper.setMaxSpeed(6400);
stepper.setSpeed(6400);
}

void loop() {
if (stepper.distanceToGo() == 0)
{
  stepper.setCurrentPosition(0);
  pos = -pos;
  stepper.moveTo(pos);
  stepper.setSpeed(6400);
}
   stepper.runSpeed();
}

Will appreciate any help you can give me :)

The  “Performance” paragraph of the “Detailed Description” section of AccelStepper documentation says:

  The fastest motor speed that can be reliably supported is about 4000 steps per second at a clock frequency of 16 MHz on Arduino such as Uno etc. ...

and the AccelStepper::setSpeed () documentation says:

  ... Speeds of more than 1000 steps per second are unreliable

Try changing your 6400-steps-per-second setting to a some plausible number, eg 500 or 1000.

Actually, it would make sense to start out with moderate destination settings and speeds, like a target position of 200 instead of 16000, and steps-per-second of 100, or whatever count it takes for say exactly two shaft revolutions.  Once you have that working right, then start doubling numbers until it no longer works, after which you can back off by a factor of say four (to allow for variations in load, etc).


How to power Arduino Uno from L298N motor driver's 5v terminal? I am trying to setup L298N motor driver controller with my Arduino. Different online schematics about how to connect them are mostly similar - but they differ in powering the Arduino from the drive controller's 5v pin.
I am connecting 7.5v to the Vin and Gnd to the motor driver controller screw terminal , and I wish the power the Arduino from the 5v screw terminal. Since I am planning to use the 5v screw terminal as output I am choosing to leave the 5v jumper on.
Here are 3 of the schematics I've found online,

Source Homemade-circuits:

This is what I was expecting to see. But from Arduino Uno Rev3 Faq,
Vin -- The input voltage to the Arduino board when it's using an external power source (as opposed to 5
volts from the USB connection or other regulated power source). You can supply voltage through this pin,
or, if supplying voltage via the power jack, access it through this pin.

5V -- This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power
either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V).
Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

This one looks wrong to me. I am under the assumption that Vin pin is expecting 7-12V because it's connected to voltage regulator which will cause a 2v drop. Which mean I should not connect 5v from the motor controller to Vin - making this schematic incorrect. Is my analysis correct? Here is an answer that says I can not use the 5v pin to power an Arduino since it an input pin and not an output pin.

Source teachmemicro:

This one looks ok to me since the 5v source at motor controller is a regulated source and that's what exactly Arduino is expecting on 5v pin based on aforementioned FAQ. Can I implement is safely?

Source Instructables:

I do not know if it's correct or not. Notice that the 5v screw terminal is not connected to Arduino in any way. Is it setup going to work? I am wondering where the Arduino is getting its power from?
I am wondering which schematic should I follow. I am hesitant to hook up my L298N motor driver and Arduino without without understanding why each schematic is choosing to power the Arduino differently.

Clearly, your design (last image) won't work, because as you expected, the Arduino won't have power. It is a feasible design however, if you use it while still developing and you have the USB cable connected. Because then the Arduino will draw the power for itself from there.
Vin expects 7-12V, but allows an unregulated input (which is fine for connecting a battery). You can use the 5V pin to supply power from a regulated output as well. Since (pressumably) the output of the motor driver is regulated, that could work, however I would not advise it and directly connect the battery to the VIn pin.
Connecting the 5V output of the motor driver to the VIn pin might work. While this will likely not destroy anything, it may be to low to drive the internal regulator, which might cause the Arduino to run on undervoltage levels. You might see weird behavior in that case (pins not correctly recognizing high from low, incorrect measurements on analog inputs or even software crashes).


Interrupts don't work I tried to run a sketch that tests my AVR's interrupts,
I have an UNoriginal Arduino Uno, and I've checked pins 2 and 3 like the following:

- at void setup()
attachInterrupt(2, inter, CHANGE);
- at void inter()
Serial.println("Interrupt pin 2");

I did the same on pin 3, I checked them by attaching the pins to a button with a Pull-Up,
When I click the button it goes from HIGH to LOW.
But yet, the arduino doesn't run the 'inter'.
Is it possible that because my Arduino is not original it won't work?
And this type of interrupts are software not hardware right?

On all Arduino boards except the DUE, attachInterrupt() does not use the pin number as first argument but the interrupt number, which is different:

void attachInterrupt(uint8_t interrupt, void (*ISR)(void), int mode);

As documented on Arduino reference, for an Arduino UNO, the mapping is as follows:

Interrupt 0 -> Pin 2
Interrupt 1 -> Pin 3

So just change the code in setup() to:

attachInterrupt(0, inter, CHANGE);

And that should work for pin 2.


Arduino as wireless network host I have a rather simple question, which I cannot seem to find the answer to online.

I would like to host a wireless network using an arduino. Other devices could connect to and communicate with the arduino. Could I do that with a shield like this?

Also, once a device (say a phone) is connected, how would it go about requesting a web page, or other information?

Thank you!

Yes!

You can absolutely do the above said task with the shield that you provided information about.

All you have to do is to connect the Shield to the Arduino and upload the WiFiWebServer sketch from the Arduino's examples in the WiFi library!

Then you'll have to replace the SSID and Password with your WiFi's password.

Once uploaded, then you'll get your Arduino's (Server's) IP Address on the Serial monitorl.

Note the IP Address and open any browser on any device of your choice.

NOTE-
Your device must be connected to the same WiFi network to which your Arduino is connected to. If you wish to access the Arduino server from outside your LAN then you'll have to forward/open a port on your WiFi router and direct it to the IP Address of your Arduino. But I am assuming that you just want to access it from your LAN therefore the port forwarding can be ignored.

You'll see the default webpage in the Sketch which you can change/edit as per your own wish by using HTML.

Here's the link to the detailed explanation from arduino.cc itself.

Coming to the Second part of your question: "Also, once a device (say a phone) is connected, how would it go about requesting a web page, or other information?"

Well once the server is started on the Arduino all you do is type the IP of Arduino in the browser of the device and then the browser sends a HTTP request to the server.(This is the same way in which the browser sends requests to any other website or server like google/youtube/stackexchange . It is same for all ).


What's the most direct way to assign Serial.read() bytes to an array? I'm trying to send NMEA 0183 sentences through LoRa.
Every dinstict NMEA message looks like several char arrays (sentences) followed by '\n'.
In the below picture we see one NMEA distinct message:

This message arrives in the Arduino input buffer every 1 second with differentiated values (numbers) and it has to be sent over LoRa as fast as possible.
In order to send it over LoRa I need to read all bytes on the input buffer and assign them to an array and send them as an array, not one by one. I know that Serial.read() reads only one byte, and that's the problem.
How can I read all bytes and send them as a whole?
This is my code:
  if (Serial.available()) {
     c = Serial.read();
     rf95.send((char *)c, sizeof(c));
     rf95.waitPacketSent();

I use RadioHead library, and the definition of rf.95.send is:
RH_RF95::send  (const uint8_t * data, uint8_t len)
c is of char type.

@DataFiddler suggested something like readBytesUntil.  In fact, you can just use readBytesUntil.  It returns either when timeout happens or when you reach the specified terminator.  It consumes, but does not include the terminator.  The timeout defaults to 1000 milliseconds, and can be modified with the setTimeout() method.
One downside is that you can't differentiate timeout, full buffer, and terminator reached.  This shouldn't be a problem except for serial transmission errors.
If your data is coming in at the NMEA standard 4800 baud, you could reasonably change the timeout to 5 milliseconds and still work.

One thing that might bite you, is the line:
     rf95.send((char *)c, sizeof(c));

It is a mistake to cast the first parameter.  The error you got indicated you should write:
     rf95.send(&c, sizeof(c));

But the sizeof is also wrong.  The return type of Serial::read() is int, in part because there are 257 possible values.  If you declared c as an int, its size would be 2, not 1.
In any case, if you are using readBytesUntil, you pass the same buffer you passed it to rf95.send(), and the return value from the first as the second parameter of the second.


What is the difference between Serial.write and Serial.print? And when are they used? What is the difference between Serial.write and Serial.print? And when are they used?
Both have been used to print on serial monitor, what are their actual differences?

Serial.write is more down to earth , it is simple and fast, it is made to talk binary, one byte at a time.
example:

Serial.write(0x45);   // will write 0100 0101 to the cable

Serial.print in the other hand is more versatile , it will do the conversion for you from ASCII to binary it also can convert to BIN/ HEX/OCT/DEC but you need to specify a second argument like so

Serial.print(76, BIN) gives "0100 1100"
Serial.print(76, OCT) gives "114"
Serial.print("L", DEC) gives "76"
Serial.print(76, HEX) gives "4C"

more examples with visual serial output :

Code:

  Serial.write(0x48);   // H
  Serial.write(0x45);   // E
  Serial.write(0x4C);   // L
  Serial.write(0x4C);   // L
  Serial.write(0x4F);   // O

SERIAL OUTPUT :

Code:

  Serial.print("HELLO");

SERIAL OUTPUT :

Serial.println() in the other hand will add end of line 2 bytes 0x0D and 0x0A as you can see in the frame

Code:

  Serial.println("HELLO");

SERIAL OUTPUT :


How to know if my Bluetooth HC-05 is connected through serial monitor I want to connect a Bluetooth module to arduino and check if my module is connected or not.. Through serial monitor. Is there and particular code to connect with that?

If your board is actually a HC-05, you can

Pull the KEY pin to Vcc (see note)
Write the serial command AT on the serial interface
Look at the output: if you receive AT or OK then the module is connected, otherwise it is not

Note: The key pin is the number 34 on the SMT module (with the antenna pointing upwards, its the pin in the top-right corner). If you have a THT module (so the one with about 6 pins) MAYBE this pin is connected to one of the pins you don't usually use (they are named EN, STATE, ...). Check with a multimeter if it is connected to one of these. If it is not, then you'll have to solder a wire from it to an arduino pin.

If, on the other hand, your board is a HC-06 (almost identical to HC-05, but with a different firmware - it is a slave-only bt device), then keep it disconnected from the master and perform steps 2 and 3: when not connected, in fact, the HC-06 is already in AT mode.

More information on this webpage


Changing preferences.txt to 4-space tabs, how to AutoFormat existing code? Title says it all really, but to elaborate, in my preferences.txt file, I've changed the editor.tabs.size variable to 4, which works wonderfully, and now produces 4-space tabs as do my other IDEs for all the languages I write in.

However, I was told that using the Tools->AutoFormat feature would update all lines in my previously-written sketches that had the standard 2-space tabs with the new 4-space tab layout.

This isn't so. Whether I CTRL-a to select all and run the Auto Format function, or whether I leave everything de-selected, nothing happens.

Should auto-format "fix" the 'incorrect' indenting to the new style? If so, what am I missing?

I'm currently on Arduino IDE 1.8.5 on Linux Mint, if that makes a difference.

The auto formatter (astyle) uses a separate configuration to the editor (crazy, I know, but that's the Arduino mentality for you...).

It uses a separate configuration, which is in the lib folder of your Arduino program, called formatter.conf.

Copy that file to the same location as preferences.txt so it doesn't get overwritten when you upgrade the IDE.
Edit the file and change indent=spaces=2 to indent=spaces=4

The auto format should now be the same as the editor format.


How to find the deferenced value of a transmit Port Register? So I am working with the SoftwareSerial library. I'm looking at the write function and I see a *reg value being manipulate. I want to find the value of *reg so I traced the value by stepping into each function call.so here we go.

*reg = _transmitPortRegister
_transmitPortRegister = portOutputRegister(port) //I'm working with pin 1 in register D

Continuing...

#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )

const uint16_t PROGMEM port_to_output_PGM[] = {
    NOT_A_PORT,
    NOT_A_PORT,
    (uint16_t) &PORTB,
    (uint16_t) &PORTC,
    (uint16_t) &PORTD,
};

My first question is what is the point of (uint16_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.

Continuing on,

#define PORTB _SFR_IO8(0x05)
#define PORTC _SFR_IO8(0x08)
#define PORTD _SFR_IO8(0x0B)

#define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET)
#define __SFR_OFFSET 0x20

#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.

LASTLY, the write function takes in a parameter b, which is a byte. Now in the write function, this is the code to write.

// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);
  b >>= 1;
}

In that block of code, I am not quite sure why they are doing b & 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte"
and inside the if-else blocks, they're just oring *reg with reg_mask. How does that translate to sending a one?

Sorry for any confusion, i am glad to clarify any confusing parts of this question. Please let me know.

My first question is what is the point of (uint16_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.

No.  You're mistaking the operator.  In this context & means the address of, so it is getting the address of the variable called PORTD and casting it to an unsigned 16-bit integer, which it's then storing in the array.

  Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.

Again, we're talking addresses.  The port register number is (for port D) 0x0B.  Add that to 0x20 and you get 0x2B which is the address of the register in memory.  Then comes the tricky bit:

#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

Expand that out with 0x2B and you get:

(*(volatile uint8_t *)(0x2B))

Now, working from the inside out we have:

(volatile uint8_t *)(0x2B)

That says this is a pointer to address 0x2B.

Then that is de-referenced to get the value from that pointer with a * operator:

*(volatile uint8_t *)(0x2B)

So you end up with "The value that is in the address 0x2B"

If we then feed that back into the first part of your question, so:

PORTD = (*(volatile uint8_t *)(0x2B))

then &PORTD would be:

&(*(volatile uint8_t *)(0x2B))

The initial & and * cancel each other out (you can think of them as opposites - one is get the address from a value, the other get a value from an address), so you effectively end up with:

(volatile uint8_t *)0x2B


Sending wav file on ESP32 to flask server I'm just starting to learn about ESP32, and recently I'm trying to send a SPIFFS wav file to a flask server. does anyone know how to do it. I would love to thank and appreciate your every answer.

You need to do socket programming here for sending chunks of data to a socket server(Python end). Here is the link that can help you. Try establishing a connection between esp and python using socket programming and then you can send small chunks of audio.


Taking String Input from NodeMCU Webpage and Printing it on Serial Monitor I've started working with NodeMCU recently. I've very little knowledge about this device and how a website works. I'm trying to take a long string input from a website hosted by NodeMCU, store it on a variable and then print in on NodeMCU Serial Monitor.

I've got the following program. Here I only have created a text box for typing. But I don't know how to take that input inside a variable and use it later for serial printing.

#include <ESP8266WiFi.h>

const char* ssid = "****";
const char* password = "*************";

WiFiServer server(80);

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

WiFi.begin(ssid, password);

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

void loop() {
    WiFiClient client = server.available();
    if (!client) {
    return;
    }

    Serial.println("new client");
    while(!client.available()){
    delay(1);
    }

    String request = client.readStringUntil('\r');
    Serial.println(request);
    client.flush();

    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("");

    client.println("<!DOCTYPE HTML>");
    client.println("");

    client.println("Serial Printer (Put Text here: ): ");
    client.println("

");
    client.println("<input type='text' id='name' name='name' required minlength='0' maxlength='800' size='100'>");
    client.println("");

    delay(1);
    Serial.println("Client disonnected");
    Serial.println("");

}

Try this. It uses the webserver library. I thought it was cleaner code. I also have a nicer way to include the pure html code.

For your original form go to yourIPaddress/single

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "MTS61752";
const char* password = "6900979039";

ESP8266WebServer webserver(80);

//------------------------------------------------
static const char PROGMEM singleLine[] = R"rawliteral(
<!DOCTYPE html>

<title>Single Line Input</title>

<form method="post" action="/save" >
Serial Printer (Put Text here: ):

<input type='text' id='name' name='name' required minlength='0' maxlength='800' size='100'>
<input type="submit" name="clk_action" value="accept">
</form>

)rawliteral";

//------------------------------------------------
static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!DOCTYPE html>

<title>Clock Settings</title>

<form method="post" action="/save" >
Turn on time:
<input name="onTime" type="text" size="16" value="" >

Turn off time:
<input name="offTime" type="text" size="16" value="" >

<input type="submit" name="clk_action" value="accept">
</form>

)rawliteral";

//------------------------------------------------
void handleRoot() {
  webserver.send(200, "text/html", INDEX_HTML);
}

//------------------------------------------------
void handleNotFound() {
  webserver.send(404, "text/plain", "Page not found ...");
}

//------------------------------------------------
void handleSave() {
  String str = "Settings Saved ...\r\n";

  Serial.print("number of arguments ");
  Serial.println(webserver.args());                    // number of arguments

  if (webserver.args() > 0 ) {
    for ( uint8_t i = 0; i < webserver.args(); i++ ) {
      str += webserver.argName(i) + " = " + webserver.arg(i) + "\r\n";

      Serial.println("Arg "+ String(i)+"="+ webserver.argName(i));
      Serial.println("Arg "+ String(i)+"="+ webserver.arg(i));
    }
  }
  webserver.send(200, "text/plain", str.c_str());
}

//------------------------------------------------
void handleSingleLine() {
  webserver.send(200, "text/html", singleLine);
}

//------------------------------------------------
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  webserver.on("/", handleRoot);
  webserver.on("/save", handleSave);
  webserver.onNotFound(handleNotFound);
  webserver.on("/single", handleSingleLine);

  webserver.begin();
  Serial.println("Web server has started");
}

//------------------------------------------------
void loop() {
  webserver.handleClient();

}


RFID system for proximity detection with data logging I am wondering if anybody has ideas for developing an Arduino-based system that would use RFID to log occurrences when two people are in close proximity to each other (e.g., <= 1 meter).  Ideally, I would like to construct something that would operate in a manner very similar to the OpenBeacon system -- and, preferably, the events/data would be transmitted via wi-fi in real time.

My ideas are as follows, so any feedback or alternative solutions would be greatly appreciated.  (Please keep in mind that I am not an engineer!)

I am thinking of using a wi-fi enable microprocessor (e.g., Arduino Yun) that would serve as the reader or detection system.  For beta-testing, this device could be set in an enclosed case and attached to a belt.  I presume it would require a fairly robust battery supply.  The other person would be wearing an RFID tag that has a range of <= 1 meter and would log the event.  Ideally, a reading would take place roughly every 30 seconds, and the captured event would be transmitted over wi-fi.

Here are a few other things to keep in mind:

The people using the hardware should not have to do anything other than simply wear the constructed devices.
The reader itself should be as small as possible.
My ultimate goal is the data logging of the proximal events.

I am certainly open to other technologies, as my ultimate goal is simply the proximity detection with data logging (preferably via wi-fi).

Thanks in advance!
Brian

Consider using two basic XXMhz transceivers:

-Master loops through used ID's and transmits them one at a time.
-If a belt receives an ID other than it's own, it remains quiet.
-If a belt receives it's own ID, it transmits "Marco" (quietly) to the other belts.
-For a receiver to hear the very quiet signal, it will need to be very close.
-The RSSI signal can be monitored for signal strength to determine close(enough) proximity.
-If sufficient proximity is detected, the event is reported to the Master.
-If it receives no response, it informs the Master.
-Master proceeds to the next ID.

In this setup, you only need to provide networking (WiFi/Ethernet) to the master. (cheaper)

So that each belt can identify the others, "Marco" could be the transmitter's ID, but you'll need to add some sort of "protocol" so the belts know if the ID they hear is from the Master or another belt.

If ID is only 7 bits, the "protocol" could be as simple as a bitmask:

Server = Send(ID &  (1 << 7)); //1XXXXXXX
  Belt = Send(ID & ~(1 << 7)); //0XXXXXXX

Belts only reply to their ID if MSB is 1

This example has excessive range for your purpose (250m); these radios will be screaming at each other and the RSSI signal is unlikely to provide meaningful data.
http://www.seeedstudio.com/depot/nRF24L01Module-p-1394.html

Using RFID, you are wanting (very)long range from an (intentionally) short-ranged system.
Using ISM, you are wanting (very)short range from an (intentionally) long-ranged system.

Neither is 100%, but both should work.


Arduino TFMini Lidar sensors and speaker I have this code for the TFMini Lidar sensors and Speaker. I Need help figuring why I'm using this calculation in my code and why if I removed it the lidar will not give me any measurement? (see below plz).
And my code now it's only one sensor is working pins (4,5) I don't know why the three of them don't work together.   Thanks in advance.
I took this code from the internet My coding experience is basic .
rx[i] = TFMiniOne.read();
if (rx[0] != 0x59) {
  i = 0;
} else if (i == 1 && rx[1] != 0x59) {
  i = 0;
} else if (i == 8) {
  for (j = 0; j < 8; j++) {
    checksum += rx[j];
  }
  if (rx[8] == (checksum % 256)) {
    *distance = rx[2] + rx[3] * 256;
    *strength = rx[4] + rx[5] * 256;
  }
  i = 0;
} else {
  i++;
}

Here is the complete code:
#include "Talkie.h"
#include "Vocab_US_Large.h"
#include <SoftwareSerial.h>
#include "TFMini.h"
TFMini tfminiOne;
TFMini tfminiTwo;
TFMini tfminiThree;

Talkie voice;
const int Speaker = 3;

//Declaring variables and constants

SoftwareSerial TFMiniOne (4,5);    //(RX, TX)
SoftwareSerial TFMiniTwo (6,7);
SoftwareSerial TFMiniThree (8,9);

void getTFminiData(int* distance, int* strength) {
  static char i = 0;
  char j = 0;
  int checksum = 0;
  static int rx[9];
  if (TFMiniOne.available()) {
    // Serial.println( "tfmini serial available" );
    rx[i] = TFMiniOne.read();
    if (rx[0] != 0x59) {
      i = 0;
    } else if (i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if (i == 8) {
      for (j = 0; j < 8; j++) {
        checksum += rx[j];
      }
      if (rx[8] == (checksum % 256)) {
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }
      i = 0;
    } else {
      i++;
    }
  }
}

void setup() {
  pinMode(Speaker, OUTPUT);

  //Initializing
  Serial.begin (115200);
  while(!Serial);                     //Wait for USB Serial Port to connect
  Serial.println("Initializing...");
  TFMiniOne.begin (TFMINI_BAUDRATE);

  //Initializing TFMini Sensors
  tfminiOne.begin(&TFMiniOne);
  tfminiTwo.begin(&TFMiniTwo);
}

void loop() {
  int distance = 0;
  int strength = 0;

  getTFminiData(&distance, &strength);
  while (!distance) {
    getTFminiData(&distance, &strength);
    if (distance) {
      Serial.print(distance);
      Serial.print("cm\t");
      Serial.print("strength: ");
      Serial.println(strength);
    }
  }

  delay(100);

  if (distance > 30) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_F);
  } else {
    digitalWrite(Speaker,LOW);
  }

  if (distance > 20) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_L);
  } else {
    digitalWrite(Speaker,LOW);
  }

  if (distance < 15) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_R);
  } else {
    digitalWrite(Speaker,LOW);
  }
  delay(300);

I don't know why the three of them don't work together.

I already answered that question in my answer to your previous question.

why I'm using this calculation in my code and why if I removed it the lidar will not give me any measurement?

That code part is reading the data from the first SoftwareSerial interface. If you don't read this data (by removing this code part) you are not reading any data from the TFMini, thus you don't have any measurement. If you want measurements from the lidar sensor, don't remove the code part, that actually reads the measurements.
Besides that I will explain the complete function here in comments to the code. Before that, you should understand what the static keyword means here. Normal variables, that get declared inside a function, (aka local variables) will get destroyed, when the code reaches the end of the function. Variables marked with the keyword static will continue to exist and hold their value also after the function ended. They act a lot like global variables, though their namespace is local to the function (thus you can declare other variables with that name in other parts of your code).
void getTFminiData(int* distance, int* strength) {
  static char i = 0; // this counter variable denotes the position of the next to be received byte in the buffer rx.
  char j = 0; // temporary counter variable
  int checksum = 0; // will be used to calculate the checksum, so that it can be compared to the one send with the data
  static int rx[9]; // this is the receive buffer, where the received data will be put

  if (TFMiniOne.available()) { // When data is available on the serial interface, read one byte
    // Serial.println( "tfmini serial available" );
    // read one byte into the current position in the buffer
    rx[i] = TFMiniOne.read();

    // A valid message starts with two bytes of the value 0x59, so we restart, if the current message doesn't have that. (checking the first two bytes with these two if statements)
    if (rx[0] != 0x59) {
      i = 0;
    } else if (i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if (i == 8) { // if we received 9 bytes (positions 0 to 8 in the buffer), the message is complete --> process it

      // Calculating the checksum by adding all bytes together
      for (j = 0; j < 8; j++) {
        checksum += rx[j];
      }

      // Comparing the calculated checksum with the last byte, that was received, (which is the checksum)
      // as the checksum is only one byte, we calculate the modulo with 256, thus only leaving the number range 0-255.
      if (rx[8] == (checksum % 256)) {
        // The checksums are equal, so the data is valid and we can proceed
        // The values for distance and strength have two bytes. Thus we need to put these bytes together into one value.
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }

      // reset the counter, since we have a full message and can now receive the next message
      i = 0;
    } else {
      // increment the counter variable to the next position, if we are currently receiving the bytes of a valid message
      i++;
    }
  }
}

I hope this makes the code clearer. As already said the my previous answer, it doesn't make much sense, to first use the TFMini library (declaring the corresponding objects) and then doing the communication yourself. I would suggest, that you look closer into the TFMini library. Try the examples, that surely come with the library. Use the libraries functions to communicate with the sensors. That will make it way easier for you, since the library will do the communications for you.


How can I add two different programs of bldc motor and servo motor in one so that they work in parallel? This is for the servo motor:

#include <Servo.h> //Servo library

Servo servo_test;
//initialize a servo object for the connected servo
int angle = 0;

void setup() {
  servo_test.attach(9);
}

void loop() {
  for(angle = 0; angle < 180; angle += 1) {
    servo_test.write(angle);
    delay(15);
  }
  delay(1000);
  for(angle = 180; angle>=1; angle-=5) {
    servo_test.write(angle);
    delay(5);
  }
  delay(1000);
}

This is for the bldc motor with esc:

#include <Servo.h>

Servo esc_signal;

void setup() {
  esc_signal.attach(12);
  esc_signal.write(30);
  delay(3000);
}

void loop() {
  esc_signal.write(55);
  delay(15);
}

Depending on how the code is driven. The simplest would be to simply run loop1 and loop2 in the new loop.