text:
How to draw a bitmap on a tft display?
I'd like to print a bitmap on my TFT.
I setup my screen with this library: http://forum.arduino.cc/index.php?topic=292777.0
It is like the Adafruit_GFX library (only a little bit changed). Everything works.
With the tool Img2Code I converted my image into a bitmap.
void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
                               const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

How to include this code and print the bitmap on the tft?

What is your question?

how to draw a xbm (bitmap) on my tft. I don't know how to include the big bitmap array.

As the function prototype you have show suggests, the data needs to be in a uint8_t array format.
void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
            const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

So your array data would look like:
const uint8_t myBitmap[] = { 0xff, 0xff, 0xc0, 0x00, 0xc0, 0xff,
    0xc0, 0xc0, 0xff, 0xff, 0xde, 0xad, 0xbe, 0xef,
    .... etc ....
    0xff, 0xff, 0xff, 0xff, 0xff
};

You then call the function with the needed parameters:
tft.drawXBitmap(10, 20, myBitmap, 100, 80, 0xFFFF);

That is assuming you want to place it at (top left corner) 10,20 and the bitmap is 100x80 pixels in size.  It will draw it in white (0xFFFF).


text:
Detect DS18B20 sensors and correctly assign them to relays
I'm relatively new to microcontroller programming, so please excuse me if my question is dumb. I've created a simple device that allows me to control 4 relays based on temperature. I bought four DS18B20 sensors, 4 relay board and Wemos D1. Everything works fine - I'm able to read the temperature of each sensor based on their address.
But I started wondering how I can replace a single DS18B20 without recompiling the code; currently this isn't possible. After searching a bit I found a couple of questions about the order of 1Wire sensors. For example, this one. I have no control over the order in which sensors are detected.
Is there a best practice when it comes to configuring DS18B20 sensors?
I would like to set up my device. By set up, I mean that I would like to assign a specific DS18B20 to a specific relay.
I imagine it like so:

Take a new DS18B20, connect it to a device and power the device.
The device should scan for DS18B20 sensors. If it finds one then it should assign it to relay 1 and store its address in EEPROM.
Then unplug the device from power, plug the second DS18B20 and power the device again.
The device again scans for DS18B20 sensors. It finds 2 devices. The first one is known (the address was stored in EEPROM) so it is skipped. The second is assigned to relay 2 and the address is stored in EEPROM.
The same procedure is applied to the third and fourth sensors.
If four sensors are connected (the addresses are from EEPROM), then the device can run.
When the user wants to replace a non-functioning sensor, the same procedure can be used.

As I wrote, I'm new to microcontroller programming, so if there is a better way please let me know. I'm mostly learning by following examples and tutorials, so if anyone knows of an example showing such a configuration procedure I'll be grateful for any materials.

How many ds18b20 sensor are you going to break? There is indeed no control over the order when you use byIndex. Every ds18b20 has a unique identifier, you can store that in eeprom. That is the only way to be sure to read the temperature from a specific sensor. You can do what you wrote, but you could also use a button to scan for a new sensor. The more complex you make the code, the more chance for a bug. It is easier when there is a display or a serial port or a webinterface.

personally, I'd go with a web interface for configuration - though, if it's easy enough to connect to a PC if you need to replace a DS18B20, then a simple serial interface would suffice

@Jot my idea is to build a device that I can give to my friends and put on GitHub so everyone can use. Idea is to remove step where the user must read DS18B20 addresses and put them into code. I want to use the same method to set up a new device or replace a broken sensor.

@JaromandaX I'm planning to add web interface, but I was plannign to use it only to show readings and relays statuses. I wasn't thinking about using it to setup sensors. I must look into this :)

If you can easily disconnect the sensors one at a time then your way is fine.
If you can't easily disconnect them then you can maybe use readings to set the order, although this depends on the environment. If, for example, all the sensors are generally room temperature then you have the code check the temp of all the sensors at start up. If it finds one sensor at less than 0C then assign that sensor to the least-recently-replaced relay index (also stored in EEPROM).
Then when you want to put a sensor into the working set, hold an ice cube on it for a few seconds before powering up the controller. There are other combinations of this technique you can imagine that use a button or jumper wires to specifically set the index of the out-of-range-at-startup sensor.
Alternately if you have an extra pin on the Arduino, then you can make a procedure where you connect a new sensor to that pin before attaching it to the string. You can make a rule like "if you ever see a sensor on pin X then remember its device ID and assign it to relay Y". There are lots of UI ways to pick Y. Note that you do not even need any extra hardware for this.

source: Stack Exchange

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

sort: votes


text:
Wire Library send/receive
I'm doing a project that includes an Arduino Uno and custom hardware made by me. Everything is working perfectly independently, and I'm trying to implement a way for them (the Arduino and my hardware) to work together. In order to achieve that, I am using the Wire protocol (Arduino side) and I2C (custom hardware side). From now I can send data from my hardware to my Arduino in a master-slave relation, and I have no problem with that. Please take a look at my Arduino code for better understanding:
void setup(void) {
  Wire.begin(7);
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int howMany) {
  int x = Wire.read(); // receive byte as an integer
  Serial.print(x);
  if (x==0)
    state = 0;
}

So far so good. Now I want to send data from the Arduino to my custom hardware full duple, and for that I am adding this code:
void frame(void){
  Wire.write('x');
  Wire.write('\r');
}

void loop() {
  if (state == 0){
    frame();
    state = 1;
  }
}

In order to receive the 'x' char in my custom hardware I have switched the I2C protocol bit from Write to Read using I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, _address, I2C_WRITE); to I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, _address, I2C_READ); in my custom hardware code.
I don't know why, I am not receiving the data from the Arduino. Am I missing any configuration on the Arduino side?

Do I need any address in my custom hardware (I2C protocol) to receive data from the arduino side?

Who exactly is the master here? Who generates the clock? Full duplex means both devices can transmit simultaneously; this isnt possible with the I2C protocol. The Wire library is an Arduino implementation of the I2C protocol.

The master is my custom hardware (pic32mx) and the slave is the Arduino. So the master gives the clock which is 5khz for this case. I know they can not simultaneously but i AM trying to find a way for them to work in a question-answer way.

You use the onReceive() and onRequest() methods of the Wire library to implement an Arduino slave. In your case, something like this:
void setup(void){
  Wire.begin(18);
  Wire.onReceive(receiveEvent);  # register receive handler
  Wire.onRequest(requestEvent);  #register request handler
  Serial.begin(9600);
}

void receiveEvent(int howMany){
  int x = Wire.read();    // receive byte as an integer
  Serial.print(x);
  if (x == 0)
    state = 0;
}

void requestEvent(){
  Wire.write("x\r");
  state = 1;
}

See Slave Receiver and Slave Sender examples for more details.

How is the requestEvent is being called in this case? I already use the wire.write to send data to my hardware but I am not using the requestEvent at all. Is it really necessary?

requestEvent is called automatically whenever the master requests data from the slave. The Arduino is not in charge of the I2C bus; it must wait till the master begins driving the clock line and specifically asks for data. Only then should you use Wire.write() else nothing happens.

So from my Pic side which function should I use to request data from the arduino?

The same function you would use to read data from any I2C slave; from the PIC32, you simply send the address of the Arduino slave (7, in this case) followed by a 1 to indicate a READ operation and you wait till this is sent. At this point, the Arduino receives this byte and interprets it as a READ, calls onRequest() and begins to place data on the bus. Your PIC32 reads the data byte by byte until it is satisfied and then sends the STOP condition. I assume you've worked with I2C on the PIC32 before?

That's exactly what I am doing in the PIC32 side but it seems the READ operation is not taking effect in the arduino side and it's not calling the onRequest() arduino function automatically.

@scuba update your post with the pic32 i2c read function. Or provide a link.

The code is kinda big, how can I show you without putting all the code here?

Let us continue this discussion in chat.

In case anyone's interested, I think the problem had to do with the slave I2C address. 0x7 is a reserved address so I've edited the answer to use an allowed address.

I've not done events on an Arduino so this could be a bum steer, but shouldn't the state variable be volatile and protected with a semaphore?
You are accessing it in the main program and in your event/ISR.
Secondly, no offence intended, could you replace your hardware with a bit of tried and trusted hardware to eliminate the remote possibility that your hardware is at fault.

No, you don't need to have a variable defined as volatile and protected to access it in the main program and in any other event/method.
Let's not consider any possible problem with the hardware (which is a thing I don't believe because it's already a established product). What I really want to understand if it is possible to send and receive characters through Wire protocol as long as we have the Arduino defined as slave. I am receiving data with Wire.read and after that I am sending a chunk of chars using Wire.write but I am not getting that info in my hardware.

@scuba - in actuality, Matt's concern is probably correct.  The Arduino documentation is notoriously incomplete, but http://arduino.stackexchange.com/questions/4477/what-is-the-execution-context-of-the-function-registered-via-the-wire-onreceive suggests that the event methods are called in interrupt context, which means that the state variables they share with the main thread of execution do need to be volatile.  This is in contrast to something like SerialEvent() which occurs in the main thread of execution only between calls to loop().

However it looks as if your more primary issue may be that your code would respond to the write address by sending data, when what it needs to be doing is sending data in response to the read address that triggers the request event.

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


text:
My stepper motor connected to a driver and an Arduino is not working
I'm using a 28BYJ-48 stepper motor with a ULN2003 driver board. I'm trying to control the motor using an Arduino MEGA. I initially connected the pins on the driver: IN1,2,3,4 to pins of the Arduino: 8,9,10,11 respectively; as was given in a youtube video I referred to(https://www.youtube.com/watch?v=HdqCtAJxhrs). The power for the motor was given from the 5V and GND ports in the Arduino. What happens is that it rotates 180 degrees,and then stops and then goes at random angles and stops. This was the code:

#include <Stepper.h>

Stepper stepper1(64,8,9,10,11);
int a=1;

void setup() {
  stepper1.setSpeed(50);
}

void loop() {
  while(a<10){
    stepper1.step(2048);
    delay(1000);
    a++;
  }
}

Does anything happen? Have you tried any of the stepper example programs, and do they work? How is your stepper connected? A diagram would be helpful. Is the power supply sufficient for this motor? Can you confirm the supply is working? There is a lot more you could provide in your question - or check for yourself and and provide that information - to help us help you.

@JRobert so it's supposed to keep rotating at 180 degrees with breaks right, but it just rotates once and stops. I was wondering if the power supply would be a problem because right now it's connected to the Arduino. I'll get a power source tomorrow and try again. IN1,2,3,4 were connected to pins 9,11,10,6.

@JRobert, I checked out another video and changed the pin configuration. Other details are updated in the question. If you need any other information then just let me know :)

Most motors need more current than an Arduino pin can supply, so if the stepper driver doesn't power your motors through a separate supply, there is a good chance that is your problem. Arduino pin drivers are supposed to be limited to 20ma nominal, and 40ma absolute max. Trying to draw more than that will likely fail (the device will be under-powered), may damage the pin drivers (by over-heating), and may pull down the Arduino's own supply voltage enough to it to reset (typically cycling itself through startup/attempt to run/reset, ... etc. until you shut it off or something fails).

Hey @JRobert!!! I finally got it working!! So what I did was connected the motor to a 5V 0.3A supply. And then I changed the number of steps per revolution to 2038 and used the code on Michael Schoeffler's website (https://www.mschoeffler.de/2017/09/23/tutorial-how-to-drive-the-28byj-48-stepper-motor-with-a-uln2003a-driver-board-and-an-arduino-uno/). And it finally works!!
Thanks for all the help :)

Glad to hear it - thanks for letting us know.

For those who missed the comments, what I made a mistake in, as @JRobert pointed is that I was suppose to have connected the stepper motor to a separate power supply as the Arduino was not capable of so much resources. I also altered the code as I think I had gotten the steps-per-revolution wrong which is needed in the Stepper function in the Arduino Code. One needs to check this with the datasheet or somewhere online for the respective stepper motor model. The final code that got it working is here. All thanks to @JRobert for helping me figure out the solution :)

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


text:
I'm not getting the readings of sensors connected to an Arduino MEGA correctly using PLX-DAQ
I'm trying to send data from four sensors that are connected to my Arduino MEGA to an excel file using PLX-DAQ. So I want to keep taking readings at an interval of 1 second until I wish to stop. So I have two questions. First, this code is not working, I just get three readings but all in one row. And I try resetting the Arduino the first time using the physical button on it, and again I get the next set of three readings AFTER I press the reset button the second time. So there is no real-time updation. For example, I upload the code and I click on connect in PLX_DAQ. I see nothing in the Excel file. I press the reset button, and I get three readings all in one row. I wait for some time, I press reset again and I get another three readings and that's it.
Second, how do I control when to start taking readings or stop taking readings, either using Arduino code or by PLX-DAQ.

int sensC=A12;
int sensA=A13;
int sensB=A14;
int sensD=A15;

void setup() {
  Serial.begin(9600);
  Serial.println("CLEARDATA");
  Serial.println("LABEL,A0-Voltage,B0-Voltage,C0-Voltage,D0-Voltage");
}

void loop() {
  Serial.print(analogRead(sensA));
  Serial.print(",");
  Serial.print(analogRead(sensB));
  Serial.print(",");
  Serial.print(analogRead(sensC));
  Serial.print(",");
  Serial.println(analogRead(sensD));
  delay(1000);
}

**********EDIT 1**************
@user85471, ok so I added another line right under void loop(), which is: Serial.print("DATA,");
and I ran it again. Now i see my data being stored, but I have four sensors, but only three are of the right output.

A0-Voltage should be somewhere around 330-340, but I'm getting some sort of a time output.

Could you add a copy/paste of what you're seeing in the Serial monitor or your spreadsheet?

@user85471, please check EDIT 1, and help. Thanks :)

The first column must always be a timestamp value by the looks of things.

Go back to using the serial monitor in the Arduino IDE. Edit your question to show that output. My guess is there is some problem with the way you are capturing the data into Excel.

(You should edit your question to explain what PLX-DAQ is, and include a link. I had never heard of it and had to Google it.)

Changing the format of column A to a numeric format should display its true value. It looks like it's being displayed as a time, and since the values are all whole numbers, the time is midnight (00:00:00). If you were to change it to a date format, it would probably show a date around early December 1900.

I'm guessing that your import software assumes that the first column will be a timestamp, hence the change of this column only.

@DuncanC, yes your guess is right. I had originally checked the output from the serial monitor, and I was getting 4 values. But there is some error in the transfer from Arduino to Excel using PLX-DAQ. If you know any way to save the output from the serial monitor, that would be a useful lead for me. And yes, I'll add a link to explain what PLX-DAQ is.

@user85471, but I also tried labelling the first column for time and another four for A,B,C,D. Even then I don't get the expected output.

@Danush, not labelling, but change the actual displayed format of the cells. Select the column, right-click and choose format- you want to change to a number format instead of a date. I don't have Excel here, so I can't tell you the exact wording.

@Danush: alternative workaround. Add a fifth dummy column before your data. IE before printing the sensA value, print something random (zero would probably work, something like millis() would give some kind of timestamp) followed by a comma. If the column doesn't do what you want, jump over it and ignore it.


text:
How do I properly trigger the ATMega328 reset pin via software so that the bootloader runs and the firmware can be updated via RX/TX pins?
I am programming my Atmega328P chip via a USB to TTL converter (https://www.amazon.com/gp/product/B075N82CDL/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1)
I am able to upload hex files via the command line and the Arduino IDE when I have the RTS pin of the adapter and a capacitor attached to the !RESET pin of the Atmega. (http://www.electronics-lab.com/wp-content/uploads/2018/09/programming-Uno-on-breadboard.png)
I am also able to upload via the command line when I have a push button attached to the !RESET pin and manually pull it low then begin uploading the firmware within a few moments. (https://cdn.instructables.com/F0L/2F6U/J7AQSHD1/F0L2F6UJ7AQSHD1.LARGE.jpg)
My problem is that for my application I will only have the TX/RX/Vcc/GND pins available (no RTS or push button) and need to reset the micro controller so the bootloader runs and listens to be programmed with updated firmware.
So far I have written a batch file that sends a command to restart the Arduino, and then calls avrdude to upload a hex file. I have tried two methods of restarting the micro controller. I have told it to go to memory location zero, and I have attached an IO pin to the reset and dropped it low (although it stays low until reset, so the reset doesn't really work until I manually remove the wire between the IO pin and the !RESET pin)
My sequence is as follows:

Have Arduino running code:

    int recvByte;
    int delayS = 400;
    int resetPin = 9; //bttom right pin of uC

    void setup() {
      // put your setup code here, to run once:
    pinMode(txPin, OUTPUT);
    pinMode(rxPin, INPUT);
    pinMode(resetPin, OUTPUT);
    digitalWrite(resetPin, HIGH);
    Serial.begin(57600);
    Serial.write("Booted/reset");
    Serial.write("This setup was uploaded with batch");
    }

    void(* resetFunc) (void) = 0;

    void loop() {

    if (Serial.available() )
    {    // get incoming byte:
        recvByte = Serial.read();
        if (recvByte==int('r'))
        {
        Serial.write("resetting");
        delay(10); //wait for last message to send
        //digitalWrite(resetPin, LOW); //commented out because this method stays low until wire is removed
        resetFunc();
        Serial.write("should not see if reset properly");
        }

    }

    delay(100);
    }

2.I then run my batch file.
echo Running upload bat, sending reset command then calling avrdude
cd "C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\"
python "path\sendR.py"
.\avrdude.exe -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -carduino -PCOM6 -b57600 -D -Uflash:w:"path\Atmega328code.hex":i

The python sendR.py is to send the "r" character, which the Arduino views as the reset command.
import serial
ser = serial.Serial("COM6", baudrate=57600)  # open serial port
bytes = "r".encode()
ser.write(bytes)
ser.close()
print("End python script")

When I send "r" via Tera Term or python the setup code runs again, but I have not been able to upload with the .\avrdude.exe -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -carduino -PCOM6 -b57600 -D -Uflash:w:"path\Atmega328code.hex":i command inside the batch file. If I use the pushbutton to do a hardware reset, this command works without issue.
How can I upload new firmware via the RX and TX pins using software to reset the microcontroller and listen for new code as the bootloader runs?
New ideas tried:
Use a uniform baud rate of 57600 in python and atmega serial setup. I chose this value because the Arduino IDE output this baudrate in avrdude.exe -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -carduino -PCOM6 -b57600 -D -Uflash:w:"path\Atmega328code.hex":i

wdt_enable(WDTO_15MS);  resets the MCU 15 millis after called. it is a full reset like with reset pin.

You wrote:

void(* resetFunc) (void) = 0;

This seems to me like an approach worth trying, except that the function
address is wrong. At address zero of the flash you have the start of the
user's code. The bootloader, if you do use one, lives at the end of the
flash. The start address of the bootloader depends on its size, and is
configured by setting some fuses on the chip. If you are using the
popular optiboot (the bootloader of the Uno), you have to jump to
exactly 512 bytes before the end of the flash, i.e.:
void (*resetFunc)(void) = 0x7e00;

Oh, wait... the flash is organized as 16-bit words, so you may have to
use the wordwise address instead:
void (*resetFunc)(void) = 0x3f00;

But do note that, unlike a real hardware reset, this approach does not
reset the peripherals to their normal initial state. You may want to do
it before jumping to the bootloader.

Edit: I have disassembled a test program that does this kind of
call-by-pointer, then double checked the documentation of the icall
instruction. It appears that the function address you provide is
indeed interpreted as a word-wise address, so you should write half the
byte-wise address. If you write anything larger than the size of the
flash (0x4000 = 16 kilowords), the most significant bits get
lost, and the address gets reduced to the correct range modulo the flash
size.
That is, if 0x7800 worked for you, then presumably the correct address
is 0x3800, i.e. 2 kilowords (4 KB) before the end of the
flash. This is quite a large bootloader, and the largest size supported
by the ATmega328P. Are you sure it is righ? Aren't you sliding through
some uninitialized flash before hitting the bootloader? Here is a table
that gives the bootloader's start address as a function of the amount of
memory reserved for it:
reserved size  start address
    512 B         0x3f00
     1 KB         0x3e00
     2 KB         0x3c00
     4 KB         0x3800

Note that the Arduino Uno uses optiboot, which fits into the
smallest size that can be allocated to a bootloader (512 bytes).

Thank you! The batch file works with the chip after changing the chip code to void(* resetFunc) (void) = 0x7e00;

The location I had to use was 0x7800; but it is working perfectly for me now. Thank you again!

I think this eats up your memory after a few reboot cycles as you call them as a function which requires some space on stack. Wouldn't be using the wdt the way to go for a proper reboot?

@Kwasmich: The bootloader may reset the stack pointer. If it doesn't, the user's program certainly does: it's one of the first things done by the C runtime. The WDT trick can be useful nevertheless because it resets all the I/O ports to their initial values.


text:
Controlling a servo motor with two arduinos?
I have two Arduinos, two buttons and one servo motor.
I want to control a servo motor with two Arduino's when I pressed the buttons. I linked Arduino PWM pins (first Arduino PWM pin is 9, and second one is 3) to the servo motor signal input.
When I pressed button 1 servo motor moving a few, or pressed button 2. but the signal isn't clear, and servo motor doesn't move correctly that I assigned degree.
What can I do for the solution?
My first Arduino code is here:

#include<Servo.h>

#define Buton 8

Servo myServo;

void setup() {
  pinMode(Buton, INPUT);
  myServo.attach(3);
}

void loop()
{
  if (digitalRead(Buton) == 1)
  {
    myServo.write(90);
  }
  else
  {
    myServo.write(180);
  }

}

and second arduino code is:
#include<Servo.h>

#define Buton 8

Servo myServo;

void setup() {
  pinMode(Buton, INPUT);
  myServo.attach(9);
}

void loop()
{
  if (digitalRead(Buton) == 1)
  {
    myServo.write(90);
  }
  else
  {
    myServo.write(180);
  }

}

You do you have 2 Arduino's in the first place? Do you really need both?

we have to use mcu.but it's not have to be arduino. does it change if we use a different mcu's?

that does not answer the question why you need two arduinos

You can't just connect random pins together like that. Connecting two output pins together is a recipe for disaster. Best case scenario: nothing works. Worst case scenario: you break one or both Arduinos.
Only one Arduino can control a servo. If you want a second Arduino to make something happen to the servo you have to make it tell the Arduino that is controlling the servo that something should happen.
That could be a simple output of the second Arduino connected to an input of the first Arduino, in which case it kind of acts like a button. Or you could create some kind of communication channel between them - maybe using a Serial connection, or a Wire (I2C) connection. There's many ways, and which is best depends on how much control one Arduino needs to exert over the other.

thank you for your answer @Majenko, but let me explain. we are a rocket team and we have to use two flight control system. so we use two arduinos for this rocket. first arduino is main controller and second is backup system. we have different sensors but we have one motor to deployment. we want to use second arduino if the first arduino won't work. I don't know if it's descriptive?

Then you need to have some device that sits between the two arduinos and the servo and selects which Arduino is allowed to talk to the servo. You could have one Arduino in "standby" monitoring the other Arduino and, if it fails, flip the "switch" that allows it to control the servo and have it take over.

@Giray Hakan When you are talking about backup in case of failure, you first must define the cases of failure, that you want to mitigate here. There might be many different ways, in that the system can fail and which have to be sensed and mitigated in a different way.

@Majenko what type of device? can you give a example?

You could use a MUX chip. Or a relay. There's many solutions both mechanical and silicon based.

ok, thank you, i will try.


text:
Combining two codes to jump back and forth between them
I have a code for both a magnetometer, and a GPS, both written to give off just one reading at a time. I'm trying to make a sketch that is able to go back and forth between these two codes so I get both sets of data.
Here is the GPS Code:
#include <NMEAGPS.h>
#include <NeoSWSerial.h>

NeoSWSerial gpsSerial(3, 2);
NMEAGPS     GPS;
gps_fix     fix;

void setup()
{
Serial.begin(115200);
Serial.println( F("Run once!") ); // F macro saves RAM!

gpsSerial.begin(9600);
gpsSerial.println( F("$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28") ); // RMC & GGA only
gpsSerial.println( F("$PMTK220,1000*1F") ); // 1Hz update rate

waitForFix();
printFix();
}

void loop()
{
}

void waitForFix()
{
uint8_t fixes = 0;

do {
if (GPS.available( gpsSerial )) {
  fix = GPS.read();
  fixes++;
}
} while ((fixes < 2) && !fix.valid.location);

} // waitForFix

void printFix()
{
Serial.print( F("Time: ") );
if (fix.valid.time) {
if (fix.dateTime.hours < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime.hours);
Serial.print(':');
if (fix.dateTime.hours < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime.minutes);
Serial.print(':');
if (fix.dateTime.hours < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime.seconds);
Serial.print('.');
if (fix.dateTime_cs < 10)
  Serial.print( '0' );
Serial.print(fix.dateTime_cs);
}
Serial.println();

Serial.print( F("Date: ") );
if (fix.valid.date) {
Serial.print(fix.dateTime.day);
Serial.print('/');
Serial.print(fix.dateTime.month);
Serial.print('/');
Serial.print( fix.dateTime.full_year() );
}
Serial.println();

Serial.print( F("Fix status: ") );
if (fix.valid.status)
Serial.print( (int) fix.status );
Serial.println();

if (fix.valid.location) {
Serial.print( F("Location: ") );
Serial.print( fix.latitude(), 4 );
Serial.print( F(", ") );
Serial.println(fix.longitude(), 4);
}

if (fix.valid.speed) {
Serial.print("Speed (knots): ");
Serial.println( fix.speed() );
}

if (fix.valid.heading) {
Serial.print( F("Angle: ") );
Serial.println( fix.heading() );
}

if (fix.valid.altitude) {
Serial.print( F("Altitude: ") );
Serial.println( fix.altitude() );
}

if (fix.valid.satellites) {
Serial.print( F("Satellites: ") );
Serial.println( fix.satellites );
}
}

Here is the Magnetometer Code:
#include <Wire.h> //I2C Arduino Library

#define address 0x1E //0011110b, I2C 7bit address of HMC5883

void setup(){
//Initialize Serial and I2C communications
Serial.begin(9600);
Wire.begin();

//Put the HMC5883 IC into the correct operating mode
Wire.beginTransmission(address); //open communication with HMC5883
Wire.write(0x02); //select mode register
Wire.write(0x00); //continuous measurement mode
Wire.endTransmission();
}
void loop(){

int x,y,z; //triple axis data

//Tell the HMC5883L where to begin reading data
Wire.beginTransmission(address);
Wire.write(0x03); //select register 3, X MSB register
Wire.endTransmission();

//Read data from each axis, 2 registers per axis
Wire.requestFrom(address, 6);
if(6<=Wire.available()){

x = Wire.read()<<8; //X msb
x |= Wire.read(); //X lsb
z = Wire.read()<<8; //Z msb
z |= Wire.read(); //Z lsb
y = Wire.read()<<8; //Y msb
y |= Wire.read(); //Y lsb
}

//Print out values of each axis
Serial.print("x: ");
Serial.print(x);
Serial.print("  y: ");
Serial.print(y);
Serial.print("  z: ");
Serial.println(z);

delay(250);

while(1);

}

I don't know if this is even feasible, considering my lack of coding knowledge, but thanks for looking into it

The solution in short.
Although the link is very stupid, it shows very well what you have to do.
Pretty much make a code that combines both of them together. Put both setup in the new setup and carry on like that. Note that you have declared the serial monitor at 2 different baud rates so you can only pick one. Don't repeat previously declared things in your new code and you should be good to go.

Simple example:
Code 1:
const int buttonPin = 2;

 void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  buttonVal = digitalRead(buttonPin);
  Serial.println(buttonVal);
}

Code 2:
const int potPin = A0;

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

void loop() {
  potVal = analogRead(potPin);
  Serial.println(potVal);
}

Fusionned code:
const int potPin = A0;
const int buttonPin = 2;

void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600); //go for the lowest baud rate for reliability
}

void loop() {
  buttonVal = digitalRead(buttonPin);
  Serial.print(buttonVal);

  Serial.print("  -  ")

  potVal = analogRead(potPin);
  Serial.println(potVal);
}

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


text:
Calculation error with Optical Encoder
I have corrected my code for reading the optical encoder index but I am now getting a different calculation error.  At the index the encoder reset's to zero but now my readouts are as follows:
Index point - resets to zero.
- At the 90 degree rotation mark I have a readout of 180 degrees.
- At the 180 degree rotation mark I have a readout of 0 because the code has it reset to zero after 359 degrees.
- At the 270 degree rotation mark I have a readout of 180 degrees.
- At the 0 degree mark it is zero again and that's what I would expect from the index.  If I restart the Arduino Mega at the 270 degree mark, the index resets itself to zero like it should.  Being new to this, before I had the index working it was working correctly minus the index function, now it seems to be double counting.  Any ideas?
// Wiring connections for my encoder:
// Brown : VCC = 5V
// Blue + Shield : 0V = GND
// Black : ENCODER0PINA, Pin 20
// White : ENCODER0PINB, Pin 17
// Orange : ENCODER0PINI, Pin 19

#define ENCODER0PINA         20      // this pin needs to support interrupts
#define ENCODER0PINB         17      // no interrupt required
#define ENCODER0PINI         19      // this pin needs to support interrupts

// variables modified by interrupt handler must be declared as volatile
volatile long encoder0Position = 0;
volatile long interruptsReceived = 0;
volatile byte INTFLAG1 = 0;

// track last position so we know whether it's worth printing new output
long previousPosition = 0;

void setup()
{

  // inputs
  pinMode(ENCODER0PINA, INPUT);
  digitalWrite(ENCODER0PINA, HIGH);  // turn on pullup resistor
  pinMode(ENCODER0PINB, INPUT);
  digitalWrite(ENCODER0PINB, HIGH);  // turn on pullup resistor
  pinMode(ENCODER0PINI, INPUT);
  digitalWrite(ENCODER0PINI, HIGH);  // turn on pullup resistor

  // interrupts
  attachInterrupt(3, onInterrupt, CHANGE);  // encoder track A on interrupt 3 - pin 20
  attachInterrupt(4, onReset, CHANGE);  // encoder Index track on interrupt 4 - pin 19

  // enable diagnostic output
  Serial.begin (115200);
  Serial.println("Ready.");
}

void loop()
{
  // only display position info if has changed
  if (encoder0Position != previousPosition )
  {
    Serial.println(encoder0Position, DEC);

    previousPosition = encoder0Position;
  }
}

// interrupt function needs to do as little as possible

void onReset()
{
  // read Index input
  int i = digitalRead(ENCODER0PINI);
  if (i == 1)
  {
  encoder0Position = INTFLAG1;
  }
}

void onInterrupt()
{
  // read both directional inputs
  int a = digitalRead(ENCODER0PINA);
  int b = digitalRead(ENCODER0PINB);

  if (a == b)
  {
    // b is leading a (counter-clockwise)
    encoder0Position--;
    if (encoder0Position < 0)
    {
      encoder0Position = (encoder0Position + 360);
    }
  }
  else
  {
    // a is leading b (clockwise)
    encoder0Position++;
    if (encoder0Position >= 360)
    {
      encoder0Position = (encoder0Position - 360);
    }
  }
}

please format your code as "code" .... highlight all the code text and click the {} button

I did it for him/her.

Thank you, I was wondering how to get the code to format as "code".  (him).

What is the encoder that you are using? Does it have a 0.5 degree increment?

It is a Omron E6B2-CWZ6C Incremental Rotary Encoder w/Index (360P/R).

One more comment on the code above.  It ran correctly before the Index was introduced.  I tested the index and it only fires once per revolution.

I have done more testing with the code and have noticed that when the encoder has been rotated clockwise past the index the readings do the following 359, 0, 1, 2, 0, 1, 2, 3, after that it reads correctly. When turning the encoder counter clockwise the following happens 1, 0, 359, 358, 0, 359, 358, 357, and then runs correctly. Does anyone see why the encoder would do this as well as the initial issue?

I have figured out my issue, at least I am getting good results.  With this code I had to change interrupts from CHANGE to RISING.  I want to thank everyone that has made comments on this question.

I have figured out my issue, at least I am getting good results. With this code I had to change interrupts from CHANGE to RISING. I want to thank everyone that has made comments on this question. –


text:
How to make an RC mixer with the arduino
I want to make a RC mixer mixing two channels of a receiver.
What I have: a delta model plane, two servos, a receiver and a Arduino Nano.
So I'd like to mix the aileron (two channels) with the elevator(one channel).
EDIT: What I've done: I read the input of the receiver and wrote it to the servos. The problem: The servo stutters and the arduino displays false inputs.
int pin = A0;
int pin1 = A1;
unsigned long duration;
unsigned long dur;

unsigned long duration2;
unsigned long dur2;

#include <Servo.h>

Servo myservo;
Servo myservo2;

void setup()
{
  Serial.begin(9600);
  myservo.attach(9);
}

void loop()
{
  duration = pulseIn(pin, HIGH);
  dur = duration;
  Serial.println(dur);
  myservo.writeMicroseconds(dur);
  delay(50);
//  duration2 = pulseIn(pin1, HIGH);
//  dur2 = duration2-980/4-200;
//  Serial.println(dur2);
//  myservo2.write(dur2);
}

Can you give me a good instruction how to do that???

"This question does not show any research effort" is a reason for downvoting. Please show us what you tried and how far you got.

That is NOT how we do it. Flying a delta plane should not require anything between the receiver and servos, you just have to program the radio correctly. Almost all the popular RC radios today have built-in delta mixing. The SAFE system planes from E-Flite do the mixing on-board, but it doesn't require any additional hardware.


text:
WiFi connection times out if credentials retrieved via serial terminal
I've implemented a small WiFi connection procedure into my ESP32 project.
The available networks get printed with index, then I'm entering the index and retrieve the network name from it. The password is entered via serial in clear text.
Before connecting, I'm printing the credentials and thus could confirm they are read into const char * strings properly.
Unfortunately when using this procedure the connection to my AP times out. I've also tried to override the strings with hardcoded values and then the connection works as expected.
while (!Serial.available()) {
    // (timeout is implemented here)
}
String index_s = Serial.readStringUntil('\n');
long index = index_s.toInt();

// { same while as above }
String passw = Serial.readStringUntil('\n');

const char *ssid = WiFi.SSID(index).c_str();
const char *pass = passw.c_str();

// with this it works:
// ssid = "my_network";
// pass = "my_password";

Serial.printf("connecting to %s using %s", ssid, pass);
WiFi.begin(ssid, pass);

removing comments now, as they are not necessary :p

Possible duplicate of String compare when using Serial

As you can see, I don't do string compare. So what do you think how I could've found the question you mentioned? Yes, it's the same reason. No, it's not the same issue.

The answer was quite simple but of the kind you need some time get find out. The issue was a hiding carriage return.
passw.trim();

Did the trick. String.trim() removes the \r and thus the password gets accepted.


text:
Arduino app hangs on upload for all boards
I'm at a loss. I have many boards and have not had much trouble in the past uploading to feather, uno, light blue bean and others. I have a lot of boards loaded in the board manager and I'd rather not delete everything just yet.
But, after taking a month off of arduino programming I've come back to the app to discover that I can't upload anything to any board. I've tried a brand new uno, an adafruit feather and the light blue bean. In each case I can see the port, but the upload just hangs like this:

On the board the light that normally blinks during upload never blinks. It's like the upload just isn't happening. But there is no error in the app.
I tried reinstalling the app, but that didn't help. My next thought is to delete everything, and do a fresh install. Which will be annoying. Is that my only hope?

UPDATE:
Here are the settings from the tools menu as requested:

In the Tools menu, what do you have set for the Board, Programmer and Port?

I added that information.

Try changing programmer to AVR ISP.

I tried AVR ISP. Same issue. In fact, that is what I normally have it on. I was trying ArduinoISP when I took the photos to see if that would help.

Do you have an ISP device or not? If not, there is no point in using Upload Using Programmer. If so, you must use that. after taking a month off of arduino programming - it looks like a Mac. Have you upgraded the Mac operating system in the meantime?

Yes I did upgrade. Is there a known issue?

I appreciate that this is an old post but I have recently been experiencing this problem.
I found that the issue was caused when I had a wireless SD shield attached to the Arduino. Taking this shield off allowed me to upload. This occurred across 5 different Arduino's.
After some more testing I found that switching the "serial select" toggle on the wireless shield from "MICRO" to "USB" allowed me to upload as well. Switching it back to "MICRO" subsequently blocked the upload.
Hope this help anyone having this problem in the future.

You should ask the original questioner if a SD shield was used, I don't think so since the OP state "brand new uno, an adafruit feather and the light blue bean".

I was also using brand new Arduino boards. I doubt the original poster is having this issue still 2 years later. I am merely contributing an answer for future readers as I experienced this issue today and this question is one of the first search results when Googled.

Since you are making asumptions, you should use the comment since it's not a answer.

Well it is an answer... Other people gave potential solutions too just like this one - making assumptions. Maybe go and answer a question or two rather than nit-picking people providing input on a problem they have come across.


text:
AC dimmer not smooth dimming
I am trying to create a phase control AC dimmer. But I am not able to achieve smooth dimming. I am using this guide for the circuit:
Link
On the zero detection part I am able to detect its zero crossing, but the output of the zero detection circuit is not a perfect square wave, it's kinda sinoidal.
So I have created my own code that when it reaches a value above 900 (very close to 0v) it will trigger the triac. I am using an Arduino Micro:

#define TPulse 10
#define SW 7
#define ldr A0
#define zeroDetector A1

int x;
int delayDuration = 100;
long int count = 0;

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  digitalWrite(2, HIGH); // pull up
  pinMode(TPulse, OUTPUT);
  pinMode(SW, INPUT);
  digitalWrite(SW, HIGH);
  digitalWrite(TPulse, HIGH);
}

void loop() {

 delayDuration = map(analogRead(ldr), 0, 1024, 0, 9000);

 x = analogRead(zeroDetector);

 if (x <= 900)
    isr();

}

void isr () {
  digitalWrite(TPulse, LOW);
  delayMicroseconds(delayDuration);
  digitalWrite(TPulse, HIGH);
}

I have calculated that in a 60Hz AC it will cross zero voltage 120 times a second thus the delay should be in range of 0 - 8300 microseconds.
But I am not able to achieve a smooth dimming, I am getting either of, flickering, fading (uncontrolled), and so on.
Is there something wrong with my analogy or am I missing something crucial?
I have replaced the LDR with a trimmer pot so I can easily adjust the resistance.
I trying to not use interrupt as of the moment. I am trying to achieve this type of dimming:

you can use a schmitt trigger to make a clean square wave from the analog signal. You might not want to use delays, which can cause sync issues if things get busy.

first sir i will agree with you that it works with interrupt. but i wanted to go with an approach without using interupt, i am confident that with 16mhz micro it can detect every zero cross

@dandavis , i dont think there is a work around to that since i will have to delay for a microsecond to chop the ac voltage

it depends on your "frame rate"; how many times loop() fires. I would only check the level-setting input 1 in 5 loop()s to keep the lanes open for your zero-cross.

I apologize sir i could not get what you mean by your last statement. by check level setting you mean the zero cross right?>

looks like you are leaving the triac turned on ...... digitalWrite(TPulse, HIGH); should be followed by digitalWrite(TPulse, LOW); ....... the triac shuts itself off automatically at zero crossing once it is triggered ..... you only need to send it a short pulse to trigger it

Yes, jsotola 30 is right, you leave the triac gate on until next zero crossing but the short delay from real zero to detection might cause the tyristor to open


text:
MEGA2560 + SIM900A - constantly blinking, not responding
Recently I got new Arduino Mega 2560 and GSM/GPRS module - SIM900A v3.8.2.
I live in Europe, so I flashed European firmware for SIM900 and it was working OK (sending SMS, receive calls, sending http requests with GPRS) on my PC using PuTTY serial port terminal. After few tests, I ran default sketches from MarcoMartines GSMSHIELD library (other libraries weren't working for me) with Arduino Mega 2560 and they were running ok. After that I decided to make my own sketch. Here you go:

#include "SIM900.h"
#include "inetGSM.h"
#include "sms.h"
#include "call.h"

char NumberCalling[20];
char CorrectNumber[20] = {"5", "0", rest of my number here..... };

void InstantSendSms()
{
  Serial.print(F("SMS: Preparing a text message to be sent to: "));
  Serial.println(CorrectNumber);

  char Message[155];
  sprintf(Message, "Hello from Arduino :)");

  Serial.print(F("Message to be sent : "));
  Serial.println(Message);
  sms.SendSMS(CorrectNumber, Message);
  delay(50);
  Serial.println(F("SMS: Message has been sent."));
}

void InstantSendHttp()
{

  char Address[155];
  sprintf(Address, "test.php?text=test-message");
    Serial.println(F("GPRS: Opening a new Internet connection..."));

    if (inet.attachGPRS("internet", "", ""))
      Serial.println(F("GPRS: Attached!"));
    else
      Serial.println(F("GPRS: NOT attached! Error."));
    delay(1000);

    //Read IP address.
    gsm.SimpleWriteln("AT+CIFSR");
    delay(5000);
    //Read until serial buffer is empty.
    gsm.WhileSimpleRead();

    Serial.print(F("GET request : "));
    Serial.println(Address);

    char ReturnedMsg[50];
    int NumberRetMsg;
    NumberRetMsg = inet.httpGET("myserver.com", 80, Address, ReturnedMsg, 50);
    //Print the results.
    Serial.println(F("GPRS: Number of data received:"));
    Serial.println(NumberRetMsg);
    Serial.println(F("GPRS: Data received:"));
    Serial.println(ReturnedMsg);

    inet.dettachGPRS();

    Serial.println(F("GPRS: Query has been sent."));

  delay(2000);  // time to finish
}

void setup()
{
  Serial.begin(9600); // Serial connection via USB for debugging purposes
  Serial.println(F("*** Device is starting... ***"));
  delay(50);
  Serial.println(F("* Setting up the GSM Module... *"));
  // connection state
  boolean Connected = false;
  // establish network connection...
  while (!Connected)
  {
    if (gsm.begin(9600))
    {
      Serial.println(F("** GSM : GSM connection established. Ready. **"));
      Connected = true;
    }
    else
    {
      Serial.println(F("** GSM : Failed to connect to the GSM network. **"));
    }
  }
  delay(50);
  Serial.println(F("*** Setup complete! All systems are ON ***"));
}

void loop()
{
  Serial.println(F("GSM: Checking voice call status..."));
  switch(call.CallStatusWithAuth(NumberCalling, 0, 0))
  {
    case CALL_INCOM_VOICE_AUTH: // Yes! Someone is calling us
      Serial.print(F("GSM: Receiving call... Caller ID: "));
      Serial.println(NumberCalling);
      if(strcmp(NumberCalling, CorrectNumber) == 0)
      {
        Serial.println(F("GSM: Number IS matching whitelist!"));
        delay(1800);  // Wait 1,8 seconds before hang up
        call.HangUp(); // Hang up on me
        InstantSendSms();
        InstantSendHttp();
      }
      else
      {
        Serial.println(F("GSM: Caller is unknown."));
        call.HangUp();
      }
      break;
    case CALL_NONE:
      Serial.println(F("GSM: No one is callin us right now."));
      break;
    default:
      Serial.println(F("GSM: Talking or not responding..."));
      break;
  }
  delay(10);
}

At first, I used 9600 baud for GSM in the sketch. It successfully sent an SMS, but no luck with GPRS - in the Serial Monitor I got always the error message:

GPRS: NOT attached! Error.

I read on the Internet that the baud rate is very important here. Somewhere on this forum I got the information that I should change baud rates in HWSerial.cpp and GSM.cpp in the library files to 4800 baud.
Well, I tried different bauds in my sketch. Finally I got this working with this configuration: in my sketch - 19200 baud, in library - 4800 baud. I run Arduino, SMS was sent ok, GPRS said "GPRS: Attached!" but no data came to my website. Then suddenly SIM900 module stopped working it is weirdly blinking. Power LED is brightening and darkening, and never goes off, and Status LED is quickly blinking. You can see that on the video, SIM900A Mini v3.8.2 - Weird blinking | Module not responding.
I connected it directly to my PC, PuTTy was receiving crazy input from the SIM900, as you can see below:

I thought that maybe the firmware had broken and I flashed again new firmware. It went smoothly and ok, but then again, module is acting in a strange way, the same as before.
What can I do to get it working normally?

UPDATE:
Hello. Today I tried again to work with my module. I communicated with sim900 using http://m2msupport.net/m2msupport/module-tester/ , things are getting better, SIM900 is responding to AT commands. Module still doesn't work as it is supposed to - PowerLed is ON, StatusLed is indicating connecting to the network. It seems to be connected for about a second and then SIM900 is self-resetting and doing that over and over. How to fix that?
I don't think here power supply is guilty - it's 5V 2A.

There are pieces missing from your code I think. Please post the full code.

Well, I am designing a system which has GSM connection and GPS receiver and few more feautures. I started with GSM module and I got stuck with it, so I haven't wrote any more code. For now it's all I have.

What baudrate SIM900 is specified to work at? (The current output you get on your PC seems like you are using the wrong baudrate)

Also, you should not use if GSM.begin, use while(!GSM.begin).

SIM900 is supposed to work at 19200 but many people reccomned lower bauds. Thanks for the tip. I'll absolutely do that, now I'm facing SIM900 problem, with the arduino code I'll deal later :)

The sim problem is most likely caused by your arduino code. I suggest the first thing you'd do is to try out examples proven to work. Also reset your SIM900 to factory defaults.

Hi :) I'm not using Arduino right now, just simple USB-FTDI connected to the PC as serial device. I'm only using AT commands, no arduino code. SIM900 is resetted. It acts weird even when it's not connected to anything but power supply.

SIM900 resetting: check the power supply! It does draw quite a lot of current in spikes, so you need a decent switching mode regulator, or you can give a try with LiPo batteries. 5V2A does not tell too much, the power can still fail under a load spike. Scope the power! Put a 2200uF electrolit capacitor to your power if nothing helps. I suggest to test the whole connection setup on you PC with a terminal emulator first.

I am not familiar to your inet library, but inet.attachGPRS("internet", "", "") looks fishy to me (setting up the APN is very important step - are you sure that "internet" is the name of the APN from your mobile operator? Also check how the DNS servers are configured, as you seem to use a host name to connect to your server.


text:
Can we use an alternate RFID reader to read HID cards?
I'm working on a project where I need to read the HID RFID cards. Behind the card it shows as HID 0008p and based on the documentation, it looks like it uses a 125 kHz frequency. I tried using different 125 kHz RFID readers, but I was unable to read the card. What reader should I use?
I used RC522, and also another 125 kHz reader with Wiegand output, both  without any success.
Card Used : HID Proximity Card 0008p
Additional details about the card type : HID DuoProx II 1336
Here is the code i used - This works fine with SWH 5100 reader
But doesn't work with this reader EDK-125 TTL

volatile unsigned long tagID = 0;
volatile unsigned long lastBitArrivalTime;
volatile int bitCount = 0;

#define MAX_BITS 100                 // max number of bits
#define WEIGAND_WAIT_TIME  3000      // time to wait for another weigand pulse.

unsigned char databits[MAX_BITS];    // stores all of the data bits

unsigned long facilityCode;        // decoded facility code
unsigned long cardCode;            // decoded card code

 unsigned char i;

void ISRone(void)
{
  lastBitArrivalTime = millis();
  databits[bitCount] = 1;
  bitCount++;
  tagID <<= 1;
  tagID |= 1;
  Serial.println(bitCount);
}

void ISRzero(void)
{
  lastBitArrivalTime = millis();
  databits[bitCount] = 0;
  bitCount++;
  tagID <<= 1;
  Serial.println(bitCount);
}

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

  pinMode(2, INPUT);
  digitalWrite(2, HIGH);  // Enable pull-up resistor
  attachInterrupt(0, ISRzero, CHANGE);

  pinMode(3, INPUT);
  digitalWrite(3, HIGH);  // Enable pull-up resistor
  attachInterrupt(1, ISRone,  CHANGE);

  tagID = 0;
  bitCount = 0;
}

void loop()
{
  //  See if it has been more than 1/4 second since the last bit arrived
  if(bitCount > 0 && millis() - lastBitArrivalTime >  250)
  {
    Serial.print(bitCount, DEC);
    Serial.print(" bits: ");

 // 35 bit HID Corporate 1000 format
      // facility code = bits 2 to 14
      for (i=2; i<14; i++)
      {
         facilityCode <<=1;
         facilityCode |= databits[i];
      }

      // card code = bits 15 to 34
      for (i=14; i<34; i++)
      {
         cardCode <<=1;
         cardCode |= databits[i];
      }

 //   Serial.println(tagID);
    Serial.println(cardCode);
 //   Serial.println(facilityCode);

    cardCode = 0;
    facilityCode = 0;
    tagID = 0;
    bitCount = 0;

  }
}

Which RFID cards? Link? Which reader? Link? Please read How do I ask a good question?

TisteAndii & Nick Gammon, Thanks for your comments, updated my question with more details.

Don't do serial prints inside an ISR. If you do, all bets are off.

Were you able to figure out how to read the card?I am trying to do something similar. Thanks

See this article about what TTL means https://www.sparkfun.com/tutorials/215

@RamS did you ever find a solution?


text:
NodeMCU ESP8266 - Which pins can I use?
I'm trying to connect 3 LEDs to a LoLin NodeMCU ESP8266. It seems that several or "all" of the digital pins have some special use that prevents me from using them.

If I connect the LEDs (and set pinmode to output) to D0, D1 and D2, then the blue bootloading LED will glow constantly, and the code does not seem to run at all (nothing in serial output).
D3 seems to constantly have high power, regardless what I code it to.
If I connect the LEDs (and set pinmode to output) to D1, D2 and D4, then the blue bootloading LED will glow constantly, and the serial output is garbled, but I guess the code is running.
If I connect the LEDs (and set pinmode to output) to D5, D6 and D7, then the blue bootloading LED will glow constantly, and the serial output is garbled, but I guess the code is running.

Yes, I have checked the baud rate, that's not the problem.
What's up with this?


text:
NodeMCU V3 and MPU6050 strange values
I am new to this platform, so please if I do something against the regular rules please let me know so I can learn.
Now my problem: I have a nodeMCU V3 connected to a MPU6050. Using my Arduino Uno I do get sensible values in the order of 0 degrees when the device is flat. Using the same code and the same setup I get very strange values in the order of 45 degrees when the device is flat. I have tried the following:

Using the I2C scanner I do get a valid address.
Testing with the Arduino Uno the values are correct.
The GY 521 breakout uses 3V3 datalines with 2k2 pull ups. Datalines are short. Eg on the same breadboard.
The GY 521 has a voltage regulator on board for 5V, so I feed the device with 5V in order to overcome a voltage drop problem.
I have tried to stretch the stretchClock function but no luck.

I have read about people with a similar kind of issue, but I could not find a solution. Anyone that can help me?
Apoligies. It would be more handy to attach my code:
''
/*
 * I2C example sketch for ESP8266
 */
#include <Wire.h>

const int DevID = 0x68;
const int PWR_MGT1_REG = 0x6B;

const int DataReg_AX = 0x3B;
const int DataReg_AY = 0x3D;
const int DataReg_AZ = 0x3F;
const int AccConfigReg = 0x1C;
const int GyrConfigReg = 0x1B;
const int SelfTestReg = 0x0D;

const int TempReg = 0x41;

const int DataReg_GX = 0x43;
const int DataReg_GY = 0x45;
const int DataReg_GZ = 0x47;

const int CalibrationConfigAcc = 0xF0;//set this value for calibration
const int CalibrationConfigGyr = 0xE0;//set this value for calibration
const int NormalConfigAcc = 0x00;//set this value for calibration 2G
const int NormalConfigGyr = 0x00;//set this value for calibration 250dps

/*
  int16_t Acc_X;
  int16_t Acc_Y;
  int16_t Acc_Z;
*/
float Acc_X, accAngleX, accAngleY, Yaw_Angle;
float Acc_Y;
float Acc_Z;

//double Acc_X, accAngleX, accAngleY, Yaw_Angle;
//double Acc_Y;
//double Acc_Z;

int8_t X_selfTest;
int8_t Y_selfTest;
int8_t Z_selfTest;
int8_t Acc_X_Y_Z_selfTest;

int16_t Temp;
/*
  int16_t Gyro_X;
  int16_t Gyro_Y;
  int16_t Gyro_Z;
*/
float Gyro_X;
float Gyro_Y;
float Gyro_Z;

int16_t Gyro_X_selfTest;
int16_t Gyro_Y_selfTest;
int16_t Gyro_Z_selfTest;

//int SDApin = 3;//create I2C pinouts for ESP8266;
//int SCLpin = 4;

unsigned long elapsedTime, previousTime, currentTime;

void setup() {// put your setup code here, to run once:
  Serial.begin(115200);
  Wire.begin ();
 // Wire.setClock(400000);
//  Wire.setClockStretchLimit(40000);
  Wire.beginTransmission(DevID);
  Wire.write(PWR_MGT1_REG);
  Wire.write(0x0);// wake up the sensor
  Wire.endTransmission();
  CalibrationProcedure();// enter calibration procedure
}

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

previousTime = currentTime;
currentTime = millis();
 elapsedTime = (currentTime - previousTime) / 1000;

  Wire.beginTransmission(DevID);
  Wire.write(DataReg_AX);
  Wire.endTransmission();

  Wire.requestFrom(DevID, 14);
  if (Wire.available() == 14) {
    Acc_X = ((Wire.read() << 8) | (Wire.read())) / 16384.0;// divide by 16384 for 2G setting according to datasheet
    Acc_Y = ((Wire.read() << 8) | (Wire.read())) / 16384.0;
    Acc_Z = ((Wire.read() << 8) | (Wire.read())) / 16384.0;
    Temp = (Wire.read() << 8) | (Wire.read());
    Gyro_X = ((Wire.read() << 8) | (Wire.read()))  / 131.0; // divide by 131.0 according to datasheet for setting 250 dps
    Gyro_Y = ((Wire.read() << 8) | (Wire.read())) / 131.0;
    Gyro_Z = ((Wire.read() << 8) | (Wire.read())) / 131.0;
    delay(500);
  }

  //The formulas below have been extracted from another program and uses mathematical
  //values for calulation of pitch roll and yaw. For the moment only pitch is calibrated
  //The next purpose of this program is follow a calibration procedure to take approx 200 samples
  //and average the total value to correct the pitch roll and yaw value
  accAngleX = (atan(Acc_Y / sqrt(pow(Acc_X, 2) + pow(Acc_Z, 2))) * 180 / PI);
  accAngleY = (atan(-1 * Acc_X / sqrt(pow(Acc_Y, 2) + pow(Acc_Z, 2))) * 180 / PI);
  Yaw_Angle = Yaw_Angle + Gyro_Z * elapsedTime;

  float Gyro_X_axis = (float)Gyro_X / 131.0;
  float Gyro_Y_axis = (float)Gyro_Y / 131.0;
  float Gyro_Z_axis = (float)Gyro_Z / 131.0;
  float Temperature = (Temp / (340.0)) + 36.53;
  //Serial.print(" Accelero X \t" );
  //Serial.print(Acc_X);
  //Serial.print(" Accelero Y \t" );
  //Serial.print(Acc_Y);
  //Serial.print(" Accelero Z \t");
  //Serial.print(Acc_Z);
  //Serial.println("");
  //Serial.print(" Gyro X \t" );
  //Serial.print(Gyro_X);
  //Serial.print(" Gyro Y \t" );
  //Serial.print(Gyro_Y);
  //Serial.print(" Gyro Z \t");
  //Serial.print(Gyro_Z);
  //Serial.print(" Temperature \t");
  //Serial.println(Temperature);
  //Serial.println(Temp);
  Serial.println ("Angle X");
  Serial.println(accAngleX);
  Serial.println ("Angle Y");
  Serial.println (accAngleY);
  Serial.println("Yaw Angle");
  Serial.println(Yaw_Angle);
  delay(500);
}

void CalibrationProcedure() {
  Serial.println("Keep sensor steady until calibration process is complete!");
  Wire.beginTransmission(DevID);
  Wire.write(AccConfigReg);//8 g
  Wire.write(CalibrationConfigAcc);
  Wire.endTransmission();
  delay(250);
  Wire.beginTransmission(DevID);
  Wire.write(GyrConfigReg);
  Wire.write(CalibrationConfigGyr);//250 deg/s
  Wire.endTransmission();
  delay(500);
  Serial.println("Selftest enabled, reading data...");

  Wire.beginTransmission(DevID);
  Wire.write(SelfTestReg);
  Wire.endTransmission();

  Wire.requestFrom(DevID, 4);
  if (Wire.available() <= 4) {
    X_selfTest = Wire.read();
    Y_selfTest = Wire.read();
    Z_selfTest =  Wire.read();
    Acc_X_Y_Z_selfTest = Wire.read();
    delay(500);
  }

  //extracting factory trim values after self test
  //unsigned integers for accelero variables
  uint8_t XA_selfTest;
  uint8_t YA_selfTest;
  uint8_t ZA_selfTest;
  //unsigned integers for gyro variables
  uint8_t GX_selfTest;
  uint8_t GY_selfTest;
  uint8_t GZ_selfTest;
  //Factory Trim variables
  float FTGX;
  float FTGY;
  float FTGZ;
  float FTAX;
  float FTAY;
  float FTAZ;

  float SelfTestPercentage_GX;
  float SelfTestPercentage_GY;
  float SelfTestPercentage_GZ;
  float SelfTestPercentage_AX;
  float SelfTestPercentage_AY;
  float SelfTestPercentage_AZ;

  GX_selfTest = X_selfTest & 0x1F; // 0x1F is a bit mask to extract the first 5 bits. unsigned format
  GY_selfTest = Y_selfTest & 0x1F;
  GZ_selfTest = Z_selfTest & 0x1F;
  XA_selfTest = (X_selfTest >> 3) | (Acc_X_Y_Z_selfTest & 0x30) >> 4; //shift the first 3 bits and extract bits with a mask depending on the LSB postion in the last received mixed byte
  YA_selfTest = (Y_selfTest >> 3) | (Acc_X_Y_Z_selfTest & 0x0C) >> 2;
  ZA_selfTest = (Z_selfTest >> 3) | (Acc_X_Y_Z_selfTest & 0x03);

  Serial.println ("XA_selfTest");
  Serial.println (X_selfTest, HEX);
  Serial.println("YA_selfTest");
  Serial.println(Y_selfTest, HEX);
  Serial.println("ZA_selfTest");
  Serial.println(Z_selfTest, HEX);
  Serial.println("Acc_X_Y_Z_selfTest");
  Serial.println(Acc_X_Y_Z_selfTest, HEX);

  //calculate the factory trim settings
  FTGX = (25.0 * 131.0) * (pow(1.046, ((float)GX_selfTest - 1.0)));// Factortrim Gyro X
  FTGY = (-25.0 * 131.0) * (pow(1.046, ((float)GY_selfTest - 1.0)));// Factortrim Gyro Y
  FTGZ = (25.0 * 131.0) * (pow(1.046, ((float)GZ_selfTest - 1.0)));// Factortrim Gyro Z
  FTAX = (4096.0 * 0.34) * (pow((0.92 / 0.34), (((float)XA_selfTest - 1.0) / 30.0)));
  FTAY = (4096.0 * 0.34) * (pow((0.92 / 0.34), (((float)YA_selfTest - 1.0) / 30.0)));
  FTAZ = (4096.0 * 0.34) * (pow((0.92 / 0.34), (((float)ZA_selfTest - 1.0) / 30.0)));
  Serial.println("Selftest ended...please copy data");
  Serial.println(" GX trim value\t" );
  Serial.println(FTGX);
  Serial.println(" GY trim value\t" );
  Serial.println(FTGY);
  Serial.println(" GZ trim value\t");
  Serial.println(FTGZ);
  Serial.println(" AX trim value\t" );
  Serial.println(FTAX);
  Serial.println(" AY trim value\t" );
  Serial.println(FTAY);
  Serial.println(" AZ trim value\t");
  Serial.println(FTAZ);
  SelfTestPercentage_GX = 100.0 + 100.0 * ((float)GX_selfTest - FTGX) / FTGX;
  Serial.println("SelfTestPercentage");
  Serial.println(SelfTestPercentage_GX);
  SelfTestPercentage_GY = 100.0 + 100.0 * ((float)GY_selfTest - FTGY) / FTGY;
  Serial.println("SelfTestPercentage");
  Serial.println(SelfTestPercentage_GY);
  SelfTestPercentage_GZ = 100.0 + 100.0 * ((float)GZ_selfTest - FTGZ) / FTGZ;
  Serial.println("SelfTestPercentage");
  Serial.println(SelfTestPercentage_GZ);
  SelfTestPercentage_AX = 100.0 + 100.0 * ((float)XA_selfTest - FTAX) / FTAX;
  Serial.println("SelfTestPercentage Acclero x, y, z");
  Serial.println(SelfTestPercentage_AX);
  SelfTestPercentage_AY = 100.0 + 100.0 * ((float)YA_selfTest - FTAY) / FTAY;
  Serial.println("SelfTestPercentage Acclero x, y, z");
  Serial.println(SelfTestPercentage_AY);
  SelfTestPercentage_AZ = 100.0 + 100.0 * ((float)ZA_selfTest - FTAZ) / FTAZ;
  Serial.println("SelfTestPercentage Acclero x, y, z");
  Serial.println(SelfTestPercentage_AZ);

  // get data outputs with self test enabled
  Wire.beginTransmission(DevID);
  Wire.write(DataReg_AX);
  Wire.endTransmission();

  Wire.requestFrom(DevID, 14);
  if (Wire.available() <= 14) {
    Acc_X = (Wire.read() << 8) | (Wire.read());
    Acc_Y = (Wire.read() << 8) | (Wire.read());
    Acc_Z = (Wire.read() << 8) | (Wire.read());
    Temp = (Wire.read() << 8) | (Wire.read());
    Gyro_X = (Wire.read() << 8) | (Wire.read());
    Gyro_Y = (Wire.read() << 8) | (Wire.read());
    Gyro_Z = (Wire.read() << 8) | (Wire.read());
    delay(500);
  }
  //print values with self test enabled
  Serial.println("Self test enabled values");
  Serial.println(" Accelero X " );
  Serial.println(Acc_X);
  Serial.println(" Accelero Y " );
  Serial.println(Acc_Y);
  Serial.println(" Accelero Z ");
  Serial.println(Acc_Z);
  Serial.println(" Gyro X " );
  Serial.println(Gyro_X);
  Serial.println(" Gyro Y " );
  Serial.println(Gyro_Y);
  Serial.println(" Gyro Z ");
  Serial.println(Gyro_Z);
  delay(500);

  //setup the device for normal OPS
  Wire.beginTransmission(DevID);
  Wire.write(AccConfigReg);
  Wire.write(NormalConfigAcc);
  Wire.endTransmission();
  delay(50);
  Wire.beginTransmission(DevID);
  Wire.write(GyrConfigReg);
  Wire.write(NormalConfigGyr);
  Wire.endTransmission();
  delay(50);

  //request data with self test not enabled
  Wire.beginTransmission(DevID);
  Wire.write(DataReg_AX);
  Wire.endTransmission();

  Wire.requestFrom(DevID, 14);
  if (Wire.available() <= 14) {
    Acc_X = (Wire.read() << 8) | (Wire.read());
    Acc_Y = (Wire.read() << 8) | (Wire.read());
    Acc_Z = (Wire.read() << 8) | (Wire.read());
    Temp = (Wire.read() << 8) | (Wire.read());
    Gyro_X = (Wire.read() << 8) | (Wire.read());
    Gyro_Y = (Wire.read() << 8) | (Wire.read());
    Gyro_Z = (Wire.read() << 8) | (Wire.read());
    delay(500);
    //print values with self test not enabled
    Serial.println("Self test not enabled values");
    Serial.println(" Accelero X " );
    Serial.println(Acc_X);
    Serial.println(" Accelero Y " );
    Serial.println(Acc_Y);
    Serial.println(" Accelero Z ");
    Serial.println(Acc_Z);
    Serial.println(" Gyro X " );
    Serial.println(Gyro_X);
    Serial.println(" Gyro Y " );
    Serial.println(Gyro_Y);
    Serial.println(" Gyro Z ");
    Serial.println(Gyro_Z);
    delay(5000);
  }
}
'''

You said you get good values then you said you get bad values.  What changes in between?   Do you think posting the code and the wiring would be smart?  Or do you think it’s smarter to have us guess at what you did?

Sorry! I attached my code. The only change I basically did was converting the same code from the Uno to a NodeMCU using the standard I2C pins. When the device is flat the Uno reads 0 degrees which is correct. But with the NodeMCU I get values of 45 degrees jumping up and down.

Aha, so there's a NodeMCU involved?  Why didn't you mention that in the question?  You didn't think that might be important?

I wrote that down in my question right? In case it was not clear, sorry.

I was talking about the "using the same code and same setup" which would imply the same board.  That confused me.

Ah ok, sorry for the confusion. I hope my problem is a bit clear. I am using the same code for the uno and NodeMCU. which compiles fine and I do get reading from both of the boards. The node MCU gives me incorrect values however. I have tried multiple I2C sensors and they appear to have the same issue. Can someone explain what I am missing?

Does I2C work the same on a NodeMCU as it does on Arduino?  Does it take the same code?

Yes from a hardware point of view for sure. I got the NodeMCU last week and I program it using the Arduino IDE. Including the same libraries etc. Is that what you mean?

Yeah, I've never done I2C on a NodeMCU but I've done a lot of other things and it seems pretty typical to have to use a different library or to have to do at least some things differently on the different platform for most of it.  So I wondered if you had checked out anything on I2C for NodeMCU to see if maybe there were any special considerations or if you just moved the code over.

True. It looks like an implementation "thingy" with the wire.h library. But I cannot figure out why or what.

I think I found the solution. Division /16384 somehow does not work on that platform. If I perform the formula with the raw values it works...Scaling of values according to register values seem to be the next challenge...

Division works.  You probably have a variable type issue.  What line?

Oh I see the line.  Could also be a sequence issue.  You don’t have any control over the order of the two calls to wire.read().  You should do those two reads on two lines.

It was a sequence issue I guess. Strange that I was not able to notice it on the UNO though!

The compiler gets its choice there.  If you want things to go in a certain order then make sure there is a sequence point between.   I can never remember what all constitutes that so I just go for separating to two lines of code and I know that will work.

I had the same issue sometime back.I was able to get good results using the example given for the ESP8266 in the MPU6050 library itself.You can make the necessary changes starting from that sketch.Hope this helps.
Heres the github link to the library https://github.com/ElectronicCats/mpu6050

Thank you! My purpose was to write with the Wire.h library. But for reference purposes I will try to use it. I let you know about the result!

It seems to work if I use the very standard output file and implementation of my formulas. But I am really wondering why? Do they use a different I2C library? What am I missing?

see my answer above....Don't know if you had the same issue?

Yeah I had the same issue.What happens when you try to get the readings out of the accelerometer and gyroscope like you have done is that all your reading aren't filtered.So things like gyro drift come into play and have a significant effect on the output.But the library is made so that those raw values you obtain go through a FIFO buffer and also the Digital Motion Processor on your MPU6050. These two will effectively fuse the sensor data and minimize the errors.I found that the best way to get readings is using the library but it has some drawbacks as well.

Well in my case the division after reading data and bitshifting was not working. If you comment it out feel free to try. I am not using any FIFO registers etc. I was just playing around with I2C. Thanks for your input!


text:
Monitoring multi analog ports with ACS712 current sensors
Making a Auto Blast Gate for dust collection in my wood shop. Arduino Nano using ACS712's to detect when tool is in use.  Using DRV8825 to drive a single Stepper motor that will spin a disk to line up blast gate for the tool in use. Code works as expected with one sensor coded but I can't figure out how to make it work with additional sensor coded in.
Not sure if this is the way the question shows up,  Thanks

/*This one is atarting to work.   When tool is turn on the ACS712 detects it and the stepper moves 90 deg/steps.

When the tool is turned off it remains in position which is desireable as I would use the same tool multiable times in a row.
Need to add sensor A1 and assign different steps to it.
Can I declare the values of each sensor 1 time to be used whenever that analog port read > current Threshold?
Can I have a statement that will check all the analogs and act on the one that is >current Threshold?
Need for the stepper to only move if a different sensor (than the previous analog#) is > current Threshold?
IF/Else
*/
#include <Arduino.h>
#include "BasicStepperDriver.h"
#include "DRV8825.h"

#define MOTOR_STEPS 360 // Motor steps per revolution. Most steppers are 200 steps or 1.8 degrees/step
#define RPM 200
#define MICROSTEPS 1    // Since microstepping is set externally, make sure this matches the selected mode
                        // If it doesn't, the motor will move at a different RPM than chosen
                        // 1=full step, 2=half step etc.
#define DIR 2           // All the wires needed for full functionality
#define STEP 3
#define ENABLE 4        // 2-wire basic config, microstepping is hardwired on the driver
BasicStepperDriver stepper(MOTOR_STEPS, DIR, STEP, ENABLE);

#define CURRENT_SENSOR_PIN A0 // Current sensor is connected to analog pin A0

#define CURRENT_THRESHOLD 570 // The analog value above which the relay shall be triggered
#define CURRENT_SAMPLE_PERIOD 500 // The number of milliseconds to sample the current reading

int analogValue = 0; // Stores ADC values read in from the current sensor
unsigned long stopwatch = 0; // Used to keep track of elapsed time

void setup() {
  Serial.begin(9600);
  pinMode(DIR, OUTPUT);
  pinMode(STEP, OUTPUT);
  pinMode(ENABLE, OUTPUT);
 // pinMode (A0, INPUT);

    stepper.begin(RPM, MICROSTEPS);
    stepper.setEnableActiveState(LOW);
  }

void loop() {
    analogValue = 0; // Initialize analogValue to a known state
    stopwatch = millis(); // Store a snapshot of the current time since the program started executing

    // Collect the max ADC value from the current sensor for the predetermined sample period
    while (millis() - stopwatch < CURRENT_SAMPLE_PERIOD) {
      analogValue = max(analogValue, analogRead(CURRENT_SENSOR_PIN));
      Serial.println(analogValue);
    }

    // If the max ADC value from the current sensor exceeds the threshold, set the state to LOW
    if (analogValue > CURRENT_THRESHOLD) {
      stepper.enable();  //  energize coils - the motor will hold position
      stepper.rotate(90);  //Moving motor using the degree notation in ()

   }
    while(analogValue > CURRENT_THRESHOLD)
      stepper.disable();  // pause and allow the motor to be moved by hand
}
// need to return to top of loop

Your current code only works exactly one time, because the code can never leave the last while loop in the loop() function. analogValue doesn't change in the while loop, so the condition will always be true.

First: As written in the comments, your current code will only work once. After the first reaching of the threshold it will permanently stay in the last while loop, since analogValue can never change in there (you don't assign a new value to it). Thus this part should be removed.

To extend your code for multiple sensors, you can organize all the relevant data into arrays, so that you can loop over them. First we define an array of the used analog input pins (together with a define for the array size, so that we can later easily loop over the array and still be able to easily add further sensors):
#define SENSOR_N    2
uint8_t sensor_pins[SENSOR_N] = {A0, A1};

Then we are defining similar arrays for the thresholds and stepper positions:
uint16_t sensor_thresholds[SENSOR_N] = {570, 400};
uint8_t stepper_positions[SENSOR_N] = {90, 180};

Now in the loop() function we can surround the measurement and stepper code into a loop over the arrays. Where you used defines before, we are now using the array elements of the corresponding index:
for(uint8_t i=0;i<SENSOR_N;i++){
    analogValue = 0; // Initialize analogValue to a known state
    stopwatch = millis(); // Store a snapshot of the current time since the program started executing

    // Collect the max ADC value from the current sensor for the predetermined sample period
    while (millis() - stopwatch < CURRENT_SAMPLE_PERIOD) {
        analogValue = max(analogValue, analogRead(sensor_pins[i]));
        Serial.println(analogValue);
    }

    // If the max ADC value from the current sensor exceeds the threshold, set the state to LOW
    if (analogValue > sensor_thresholds[i]) {
        stepper.enable();  //  energize coils - the motor will hold position
        stepper.rotate(stepper_positions[i]);  //Moving motor using the degree notation in ()
    }
}

Now you still have 2 things to consider:

Depending of the number of sensors, your code currently can take rather long. With lets say 6 sensor, you are measuring for 3s in total at the worst case (when the last machine is turned on). You might want to reduce your measurement duration (500ms is rather long).
You need to add code for defining, what happens, when you turn multiple machines on at the same time. Currently that would lead to the stepper motor going back and forth; surely not what you want. The easiest thing would be to only consider the first sensor, that reaches the threshold, which then gets to set the position ("first" not in chronological sense, but in the order of the pin in the sensor_pins array). You can reach that with a break; command at the end of the threshold if condition.

Notes:

The arrays hold, what they say. sensor_thresholds holds all the thresholds. In my example 570 is the threshold of the first sensor and 400 is the threshold of the second sensor. 90 in stepper_positions is the position of the stepper for the first sensor. 180 is the position for the second sensor.
I used 2 sensors in my example. You can extend that yourself by setting the define SENSOR_N to the number of sensors and adding elements for every sensor into the arrays.
uint8_t and uint16_t are unsigned integer types with the mentioned number of bits: uint8_t has 8 bits (1 byte), uint16_t has 16 bits (2 bytes). uint8_t is the same as unsigned char or byte. uint16_t is the same as unsigned int on the Uno/Nano. I used these types, because it is a good practice to use types, that have the same size on every platform. When changing to a different platform, types like unsigned int might have a different size, like being a 32 bit unsigned integer instead of a 16 bit one. As that might break code, that relies on the specific size of the type, I try to always use types with the same size on all platforms. These types have always the same pattern. There are also: uint32_t, int16_t (signed integer) or int8_t.
I've chosen the type sizes according to the expected values. Pin numbers are typically 8bit/1 byte. That is sufficient. The thresholds are above 255, thus 8 bits are not enough, so I chose a 16 bit integer. Depending on the stepper positions, that you need, you might want to change it's type also to uint16_t.

Thanks very much for your input.  Have a few questions that I don't understand.T

Thanks very much for your input.  Have a few questions that I don't understand.  SENSOR_N    2   // this is stating there are 2 sensors  I would change the 2 to=num of sensors. uint8_t sensor_pins[SENSOR_N] = {A0, A1}; Not familiar with the uint  (I will look up) what is the 8?    Next, all my sensors would have the same threshold, so below the 570 is the threshold and 400 is the steps?    uint16_t sensor_thresholds[SENSOR_N] = {570, 400}; The unit  "16/8"?   I will work on this.  Thanks for taking the time to help me

@Greg I added some notes in my answer to address your questions

chrisl, Thanks again.  That explained much.  I haven't decided yet if I will be using steps or degrees.  If I understand this, using degrees 360 would be the largest number so I could use 16.  Is there a problem with using 16  even if you don't need that much?  I will go to work on this. Thanks so much.  Is it OK if I post or send my completed code to you.  Just getting use to Stack overflow

It no problem to use a 16 bit type, when you only need 8 bits. That's more of a best practice; to use only the memory, that you need, as most AVR based Arduinos (like the Nano) have relatively little memory. Though that is only important, when you are reaching the limit with your program.

About posting the completed code: If the completed code works correctly and you want to share with others to help them with the same problem, you can post the finished code as an answer. If you want us check it for errors it is different. If your code still doesn't work because of a problem directly related to this question, you can add the new code at the end of your question. If it is not closely related, then you can ask a new question about it. If you didn't test it to that point, you should test it first, before asking us to check for errors (searching a needle in a haystack is no fund)

chrisl,  Your code works as describe!  I added additional Analog inputs and tested them. I can't fix 2 issues (may be the same)  Need to disable stepper after it moves. If I don't it will overheat the driver, I don't need  to hold position. If I use the Disable() it rotates every time the loop is done, or if no tool is turned on it pulses the stepper, (think this is enable/disable every loop.  Also need to ignore the same sensor if it was the last one detected.  Many times I will use the same tool repeatedly, need it to remain Disabled until it see a different sensor.  Thanks as always.

If i go to a encoder for the stepper might solve my problems.  As i understand a encoder it knows and remembers where its at.  So if I use the same tool repeatedly it should stay in the same position.  Should rotate to the new position.  Am I thinking right and do I need to add code for the encoder.  As a alternate I could add senors to detect that the sensor is in correct position.

chrisl, like most,  2020 has had many obstacles, but I'm back at it and have made progress.


text:
Commucinate two arduino with each other
I have 2 arduino Unos where each one works properly on its own.
I try to make them communicate with each other using serial communication (TX-RX ports).
When I try to upload my code to them I get this error :
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch

what should i do to fix it ? (MY os is windows 10) thanks

Please show us how you have connected the 2 Arduinos together and the sketches you are trying to upload.

have you tried to load the sketch while the arduino has nothing connected to any of the pins?

Pins 0 and 1 on the Arduino Uno are used for serial communication with the computer over USB, including uploading sketches. If you connect anything to those pins you can interfere with the upload process.
To communicate between the two boards using serial communication without using pins 0 and 1 you can do software serial on other pins:
https://www.arduino.cc/en/Reference/SoftwareSerial


text:
Need help with understanding the CapacitiveSensor circuit diagram
Hey guys I need help with understanding the circuit diagram from this link: https://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense
As of now, this is the schematic I drew from what I understand:

I know it is wrong since they make use of 2 capacitors, but I do not know where should the other capacitor be connected to.

look again, they do not use any capacitors

They mentioned adding of capacitors in the documentation and it is also shown in dotted lines.

Looks like the cross-post was removed.

Also asked at: https://github.com/PaulStoffregen/CapacitiveSensor/issues/27 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

The other capacitor shown in the article is the ambient capacitance (that is, the capacitance between the pin and the things around it). There is no actual capacitor.
What it is saying is that there is a RC circuit (the supplied resistor and the capacitance in the air) which will change the charging time of the RC circuit as the capacitance changes, when you move your hand near it.

From a comment:

and the other capacitor with a value of 20-400pF

Yes, it does say that:

Adding small capacitor (20 - 400 pF) in parallel with the body capacitance, is highly desirable too, as it stabilizes the sensed readings.

However that doesn't make any sense to me. How do you add a capacitor in parallel with your body? Do you carry one around with really long wires? And how do you hold it? I would ignore that part.

Based on the documentation, it mentions that 2 capacitors are used. 1 of the capacitor with a value of 100pF and the other capacitor with a value of 20-400pF.

@DominicTeo See amended answer.

So ignoring the capacitor in parallel with the body, does my circuit drawing looks correct?

Yes it looks like what the referenced web site has.

This question appears to get posted every week!
There is NOT 2 capacitors.
The Csensed capacitor in dotted lines is the capacitance added when you touch the plate.
The Cpin capacitor is suggested to stabilise the readings and is not required.
So in the circuit NO capacitors are used.
All you need is a high value resistor between the Send Pin and Receive Pin and put your plate on the Receive Pin.


text:
Arduino crashed my computer when I plug in the USB cable
I have a 2008 Mac that hardly ever crashes. But from time to time (not always) it crashes (the whole computer shuts down as if the power has been cut off) when I plug in an Arduino via USB.
What could cause this?

I've done some testing and the constant in when this occurs seems to be a cheap PIR sensor from eBay. It works some of the time.
Should I get another sensor? Or is there something about PIR sensors that makes them prone to this? It has a lot of caps... Is there another kind of motion sensor?

A faulty cable or board.

What sort of fault?

Which Arduino? Genuine, clone or knock-off? I ask because some of the cheaper ones require unusual USB drivers.

This has happened with multiple micros, from genuine one to a nodemcu esp8266... I'm thinking it's the long micro usb cord that came with my headphones... are short cords better?

Try a different USB cable, see what happens.

Well it could be that something shorts on the board and it draws too much power from mac and it shuts down to protect the motherboard. Most of the times it would just disconnect usb port, but it also could trigger some interrupt on mac itself. Do you have Lab PSU to test if there is a short circuit?

I looked for a short and found none. In the end I resolved it by moving the power supply for my potentiometer from 3.3v to 5v. I don't know why that would matter... but now it's fine.

@futurebird Power supply for your potentiometer?

I'm using the pot for user input. It's connected to power ground and an analog pin.

"It has a lot of caps" implies that the device actually will "look like" a short circuit until those capacitors are charged.  If the total capacitance is high and the USB protection circuit sensitive, it could indeed trip.

Finding resolution in moving the potentiometer to the current-limited 3v3 pin suggests that the potentiometer or something sharing its supply is drawing too much current.  The little 3v3 regulator can't supply enough to load down the USB port, and so would be being abused as a sort of inrush limiter - might be working, but not a very good idea.

It could possibly be that there is a fault that is causing a short circuit. This short circuit could be in the board itself or the USB cable that connects the Arduino. The USB port on the Mac should have protection to protect against a short circuit. Your comments have indicated that you have tested for a short and found none - but this is helpful for others that are looking for a solution.
In your comments you mention that you solved this by changing the positive rail of your potentiometer from 3.3V rail to the 5V rail.

I had this problem with a Chinese knock-off of an Arduino Nano -- looks like it was actually because I had previously installed some CH341 drivers that no longer work with Sierra.
Removing those drivers (sudo rm -r /Library/Extensions/usbserial.kext) stopped the crash (full computer shutdown when I plugged in the Arduino, even through an externally powered USB hub), but unfortunately my Mac doesn't seem to recognize the Arduino.
It looks like there is a newer version of the driver (1.4, 2017-01-11,  downloadable from here), or the 1.3 version is available as a homebrew cask if you tap that repo.
I am a little wary about installing a driver from a random Chinese site. If you want, you can unzip the driver and unpackage the .pkg file with pkgutil --expand package-name.pkg destination-folder. There are a couple subfolders including a Payload that you can inspect a little with zcat -- way over my head.
Alternatively, it looks like this repo may have a C++ driver that may work.

As n8henrie said this is an issue regarding drivers with Mac OS. I updated to Mac OS Mojave (Full disclosure I run a Hackintosh system) and plugging in the arduino nana would cause a massive kept stall causing my computer to loop (if playing a video it would loop back and forth) and I’d need to turn off the PSU in order to successfully boot. However by deleting the current drive I used (CH341) the board would no longer do this (note- I tried 3 boards from different sellers, with 1 genuine and 2 Chinese) in High Sierra this did not happen however