Serial communication between a single Android device and multiple Arduino boards I am thinking about a project, but I will need let's say two Arduino Uno. I can see that we can just use different USB ports on a PC, but what about an Android device?

I want to "run commands" from it on both Uno boards. Is it possible to connect it as it is single board, just both in parallel? I do not need communication between the boards, just with the smartphone.

For example, let's say that one of the boards will control a green LED and the other a red LED. I want to send from my phone on the serial "toggle green" or "toggle red" and both the boards will change the state of the LED connected to it accordingly to the "command" received. Will both boards be able to receive the "command"?

Thank you!

EDIT:
I see that I forgot to add that I may need to receive on the phone from any of the boards. Something like feedback.

Use a third Arduino, which serves as a hub. It is connected to your Android and to all Arduino Uno devices you want to interface. It passes the commands to all Arduino devices, and the feedbacks to the Android device. You could use for instance an Arduino Mega, with the Android on Serial0, and the Arduino Uno devices on Serial1 and Serial2.


Missing arduino bootloader problem? I have a arduino clone that is not being assigned a /dev/tty by Debian Stretch (Stable).  It does have the ch340g chip.  I have tried the driver from the manufactures site with no joy.  Would the lack of a bootloader cause this problem?

Thanks.

No.  On Arduino-style boards which use distinct chips for the main processor (ATmega328p) and Serial interface (CH34x/ATmega8u2/ATmega16u2/FT2232 etc) the presence or absence of a bootloader on the main processor has no bearing on the recognition of a USB/Virtual Serial device by a host.

However on ATmega32u4 and some ARM-based boards it can.

Since you are describing a classic board with distinct chips, whatever your actual issue is, it is something else.


How to set time for 15 seconds When user used one password after close the servo the password will valid for 15 seconds then it will not work. Other 9 will be same process

Here is code I need just this to set

int locker = 13;
int lockerState = 0;
const int buzzer = 49;
String readString;

#include <Servo.h>
Servo myservo;
int pos = 0;

void setup() {
  Serial.begin(9600);
  pinMode(locker, OUTPUT);
  pinMode(buzzer, OUTPUT);
  myservo.attach(9);
}

void loop() {
  lockerState = digitalRead(locker);
  while (Serial.available()) {
    delay(3);
    char c = Serial.read();
    readString += c;
  }

  if (readString.length() >0) {
    Serial.println(readString);
    if ((readString == "2028") || (readString =="1234") || (readString =="1294") || (readString =="4795") || (readString =="5651") || (readString =="7616") || (readString =="5648") || (readString =="1487") || (readString =="7095") || (readString =="2554"))
    {
      digitalWrite(locker, HIGH);
      for (pos = 0; pos <= 180; pos += 1) {
      myservo.write(pos);
      delay(30);
      }
      delay(5000);
      digitalWrite(locker, LOW);
      /* for (pos = 180; pos >= 1; pos -= 1) {
      myservo.write(pos);
      delay(30);
      } */
      readString="";
    }
      /* else if (readString == "proceed") {
        digitalWrite(locker, HIGH);
        for (pos = 0; pos <= 180; pos += 1) {
        myservo.write(pos);
        delay(30);
        }
      digitalWrite(locker, LOW);
      readString="";
      } */
      if (readString == "decline") {
         digitalWrite(locker, HIGH);
         for (pos = 180; pos >= 0; pos -= 1) {
         myservo.write(pos);
         delay(30);
         }
      digitalWrite(locker, LOW);
      readString="";
      }

    else {
      tone(buzzer, 500);
      delay(1000);
      noTone(buzzer);
      delay(1000);
      readString="";
  }
 }
}

In programming, there are many cases where designing data structures is
more important than the code itself. Once you have a data structure that
makes sense, the code flows very naturally. I think this is one of those
cases, so let's start by looking at what data you have to store for each
of your passwords:

the password itself (let's call it the code)
whether it has ever been used and, if so, whether it has expired
if it has been used but has not expired yet: when it was used for the
first time

This can be saved in an object with the following data fields:

const char * const code;
enum { UNUSED, USED, EXPIRED } status;
uint32_t first_use;  // valid if status == USED

Now think about what kind of actions you want to perform on such a
password:

you want to be able to test whether it matches some user entry
you want check whether it can be used and, if so, take note that it is
being used

Based on these requirements, I propose the following class:

const uint32_t PASS_LIFE_TIME = 15000;

class Password {
public:
    Password(const char *c)
        : code(c), status(UNUSED) {}
    bool matches(const char *entry) {
        return strcmp(code, entry) == 0;
    }
    void update() {  // expire if it needs to be
        if (status == USED && millis() - first_use > PASS_LIFE_TIME) {
            status = EXPIRED;
        }
    }
    bool use() {  // returns true on success
        if (status == UNUSED) {
            status = USED;
            first_use = millis();
        }
        update();
        return status != EXPIRED;
    }
private:
    const char * const code;
    enum { UNUSED, USED, EXPIRED } status;
    uint32_t first_use;  // valid if status == USED
};

Now you need to store all the passwords in an array, and a couple of
functions to operate on the password collection as a whole:

const int PASS_COUNT = 10;

Password passwords[PASS_COUNT] = { "2028", "1234", "1294",
    "4795", "5651", "7616", "5648", "1487", "7095", "2554" };

void update_all_passwords()
{
    for (int i = 0; i < PASS_COUNT; i++)
        passwords[i].update();
}

// Returns true on success, and uses the matching password.
bool try_entry(const char * entry)
{
    for (int i = 0; i < PASS_COUNT; i++)
        if (passwords[i].matches(entry))
            return passwords[i].use();
    return false;  // no match found
}

The function update_all_passwords() is meant to be called on each
iteration of loop(). It may seem superfluous, as a password is updated
whenever you try to use it. However, without regular updating, a used
password could be reused 49.7 days later, because of the millis()
rollover.

Now, in your program, you just need to:

Put a call to update_all_passwords() at the beginning of loop()
Replace the big condition that tests for a valid password by
if (try_entry(readString.c_str()))


Making analog telephone calls? How can we make the Arduino board interact with old, analog telephone, and to make phone calls?

I guess it involves connecting the board to the telephone with some specific cable (how it's called?)

In addition, I assume it will require us to use the telephone low-level dialing protocol (in order to actually interact with the phone and to send commands). Where can I read about it?

Is there a reason to concern about conversation between the digital/serial board and an analogous device?

By the way, I've read that analog telephones have relatively high voltages that can easily damage the board. I'd love to get any information about things like this, related to connecting Arduino to analog telephones, in order to know about such issues and about what to be concerned and to explore.

Thanks a lot!

Buy an external voice modem with a RS-232 connection. Connect it to a RS-232C shield. Use AT commands to dial numbers and pick up calls. Use voice AT commands to transmit or receive audio.

Never attempt to connect the telephone line directly to an Arduino since, yes, you will fry it. The voltage is all wrong in the first place, and goes even higher when the phone line rings.


How to burn bootloader into arduino uno without using another arduino I need to bootload my Uno board but I do not have another Arduino at my disposal so how do I bootload without another Arduino board

There are 3 main options how to write bootloader or program to AVR over ISP.

dedicated AVR programmer or Arduino ISP programmer
other Arduino with Arduino as ISP sketch or similar
parallel port of a computer


Serial.println not outputting I ran the following really simple code on my micro and the monitor is just blank, not displaying any zeroes or anything and the Tx light isn't lighting up. I haven't used analog inputs much so I don't know what could be causing this. Can anyone help? Thanks, here's the code

int sensePin = 0;
void setup() {
    analogReference(DEFAULT);
    Serial.begin(9600);
}

void loop() {
  Serial.println(analogRead(sensePin));
  delay(500);

}

The answer to no ouput, and suspecting your data source is to replace the data source with a constant value or a string until you get that problem sorted, and then go back to your data source and debug that if necessary.

That said, I don't see any issue with you trying to print the output of an analog read. Obviously you should get something, even if it's just a single zero on each line, twice a second.

Is your monitor the Arduino built-in monitor?
Is it set to 9600 baud, as you've set your output rate in the program?
Is there anything else connected to the Tx pin, Pin-1 (Arduino numbering, not chip numbering)?
There were no error messages from the compiler or loader, right? (The libraries, bless-'em, always get a few warnings; unfortunately we have to ignore those).
You've no reason to believe the Arduino is other than 100% good?


Encoding an entire Byte for File Reading I'm using an Arduino Yun to read from a data file, which will then populate a data structure. The file.read() function "returns: The next byte (or character), or -1 if none is available."

This functionality is identical to the SD.read() function in the SD card library.

The data file will never have any value that exceeds 1 byte with all numbers in the range 0-255. If I print these numbers as a long string in the data file, each character is read as a byte. So I need to call file.read() 3 times to read in a single 0-255 value. And then do some additional processing to construct the final 8-bit value for storing.

I could reduce this to 2 calls by printing the Hex code in the data file, but this isn't much of an improvement.

Is there a way to encode a full byte in a single character?

Effectively , is there a particular way I can format my data file so that I can read in an 8-bit unsigned value in a single call to file.read()?

This is a fragment (untested) of how you can do it:

char datafile[512];
int ch;
int index = 0;

while ((ch = file.read()) != -1) {
  datafile[i] = (char)ch;
  if (++i == 512)
    break;
}


How to stringtok this long string? I have a string,

"id,port,password,ssid,delay,flag,class,category"

Please tell me how can stringtok this and find out the "flag" value(0 or 1)?

Here is what I tried:

void setup()
{
    char input[] = {"id,port,password,ssid,delay,flag,class,category"};
    char *ptr;
    Serial.begin(115200);
    ptr = strtok(input, ",");
    Serial.println(ptr);
    while (ptr != NULL) {
        ptr = strtok(NULL, ",");
        Serial.println(ptr);
    }
}

void loop(){}

For strings with a fixed format like that (I assume it's a fixed format...) I normally just do a manual strtok of the whole thing into a set of pointers. No need for a loop.  You can then just test the last one to see if the whole thing tokenised properly, since if anything before that fails then all other subsequent ones will fail and the last one will have failed.

void setup()
{
    char input[] = {"id,port,password,ssid,delay,flag,class,category"};
    char *ptr;
    Serial.begin(115200);

    char *id = strtok(input, ",");
    char *port = strtok(NULL, ",");
    char *password = strtok(NULL, ",");
    char *ssid = strtok(NULL, ",");
    char *delay = strtok(NULL, ",");
    char *flag = strtok(NULL, ",");
    char *class = strtok(NULL, ",");
    char *category = strtok(NULL, ",");
    if (category != NULL) { // Everything up to and including category worked
        Serial.print("Flag: ");
        Serial.println(flag);
    }
}

void loop(){}

As an aside: if there is ever a chance any of the fields could be empty ("flag,,category" for example) then you should use strsep() instead of strtok() as I detail in my tutorial on splitting strings in C.


Parse Bluetooth string I'm developing on android with bluetooth LTE, I can send hex codes, but I send one code at time, so I need to send many informations in this way, how can I recognize a string and save the datas inside an array to parse it later?

Here is my sketch:

 char c=' ';
 String inString,one,check;
 char inData[11];
 char inChar;
 int counter=0;
 bool started = false;
 bool ended = false;
 byte index;

boolean NL = true;
const int LED1 = 6;
const int LED2 = 7;
const int LED3 = 2;
const int LED4 = 3;
const int LED5 = 4;
const int LED6 = 5;

void setup() {
   Serial.begin(9600);
    Serial.print("Sketch:   ");   Serial.println(__FILE__);
    Serial.print("Uploaded: ");   Serial.println(__DATE__);
    Serial.println(" ");

    BTserial.begin(9600);
    Serial.println("BTserial started at 9600");

    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    pinMode(LED5, OUTPUT);
    pinMode(LED6, OUTPUT);

}

void loop() {

  if (BTserial.available()>0)
    {
      Serial.print("bts: ");
      Serial.println(BTserial.available());
      c = BTserial.read();
      check =  String(c, HEX);

      if(check=="ffbc"){
        Serial.println("check");
        index=0;
        while (BTserial.available()>0){

            inChar = BTserial.read();
            check=String(inChar,HEX);
            if(check != "0xfff3")
            {
                inData[index] = inChar;
                index++;
            }
        }
        for (int i=0;i<=11;i++){
          one =  String(inData[i], HEX);
          Serial.print(i);Serial.print(": ");Serial.println(one);
        };

      }

             if(check=="ffca"){
             // Serial.write(c);
              digitalWrite(LED1, !digitalRead(LED1));
             }
             if(check=="ffcb"){
              //Serial.write(c);
              digitalWrite(LED2, !digitalRead(LED2));
              }
              if(check=="ffcc"){
              //Serial.write(c);
              digitalWrite(LED3, !digitalRead(LED3));
             }
             if(check=="ffcd"){
              //Serial.write(c);
              digitalWrite(LED4, !digitalRead(LED4));
              }
              if(check=="ffce"){
             // Serial.write(c);
              digitalWrite(LED5, !digitalRead(LED5));
             }
             if(check=="ffcf"){
             // Serial.write(c);
              digitalWrite(LED6, !digitalRead(LED6));
              }
    }
}

Without the loop I can read all the single datas, but for my job it's not enough, to recognize the data applications I send a "sample string" to recognize the type of informations I want to send.

i think i solved in some way, i send always the same codes at the start and at the end of the datas, so i can racognize the end and then i parse the first element of the destination array. tell  me what you think abou, if it could help someone else:

 if (BTserial.available()>0)
{
  c = BTserial.read();
  check =  String(c, HEX);
  if(check!="fff3"){              // i always start wit an fff3
  inData[index] = c;
  index++;
 }
  else if(check=="fff3"){         //end of data
  index=0;                        //reset the index for the next set of data
  if(String(inData[1], HEX)=="ffbc"){
    Serial.println("read the next 10 data of the array");
    }else if(String(inData[1], HEX)=="11"){
    Serial.println("turn on led 1");
    }

    // for more operations use a switch/case over the if

  }


Concave button wiring with Arduino I am new to working with Arduino and I have a basic question.

I have an entire circuit set up and functioning, but I would like to add an arcade style button (Larger concave style) like this.

So my question is, how would I go about wiring this button to the Arduino? I don't need this button to control any lights or any other functions. The basic function of this button is for my code to register if the button is pressed or not. I also have the code done. I just want to know how to wire this.

Also I don't know if this helps, but I already have two normal tactile buttons (with 4 pins) in the circuit connected with a pull-up resistor and I know how to connect them. I just have no idea how to go about with only 2 pins.

Any help would be greatly appreciated. Thanks.

A simple switch, frequently called single pole single throw, will have only two pins. A switch works by breaking the circuit. This is shown in a wiring diagram in this manner:

It matters not that the switch in this image is not the same switch as in the image you linked, the operation is identical. You may find momentary switches with similar appearance and identical diagrams. The difference is that one has to hold the button to make (or break) a circuit, which reverts once released.

You mention four pins. Those switches are electrically identical to the SPST switch, except that you may find you can control two independent circuits that both activate when the button is pressed. That would be a double pole single throw. There is also the possibility that the four-pin switch has common connections on each side. That is to say that if you connect your circuit to one pin, it is conductive to the other on on the same side, while the closure of the switch will also equally effect the two pins on the opposite side. I've found some tiny switches that have this arrangement, ostensibly to provide for four points to solder to the circuit board, making for a more sturdy attachment.

One can find some useful switch information on Electronics Hub, which is too exhaustive to cover here.

There are many other types of switches


Can two electronic speed controllers be connected to the same ground pin? I have a setup to read two sets of signals from a radio control receiver using an Arduino NANO: the throttle channel and the rudder channel. With some programming knowledge (which I have) this isn't too difficult, but I need help on the electrical side of things. This is the current setup I have (it works, though I'm told there is the possibility that my computer is acting as a ground for the PWM signal wires from the receiver):

OK, great. I'm able to control the motor programmatically, mix values from the receiver, etc. See this video for what I'm doing. However, this setup leaves some gaps:

Question 1
I actually need two motors for dual thrust. Each motor is to be controlled individually by the program (for asymmetric thrust). Since there are only two grounds on the Arduino, can I plug both ESC grounds to the same pin? Currently, the receiver is getting power from the Arduino, and grounds back. The speed controller grounds to the second ground pin. Diagram below:

Question 2
All that is great, but the NANO is still powered by USB: obviously I'm not putting my laptop in the RC boat just to supply a few volts! Incidentally, both electronic speed controllers (ESCs) have battery eliminator circuits (BECs), usually used to power the receiver. Would I be able to connect one of them to the VIN pin of the Arduino?

I tried something like that, but the Arduino got very hot near the pin, and it smelled. Unfortunately, I don't have my circuit at the time. The Arduino's Amazon page states support for 5V to 12V external power supply. Each ESC can supply 5V at 3A. Maybe there's a way to plug them to make 10V?

Question 3
My idea also calls for three sets of LEDs, which will be lit also based on inputs from the receiver. Can these be grounded to the same wire, like I was suggesting above for the ESCs?

You can connect all the grounds together and the circuit will be safe. If the BEC outputs 5V, you can feed it directly to the Arduino's 5V pin. Any more volts and you'll need to feed the BEC output to the Arduino's VIN pin.


7segment display on Multi Function shield - Arduino Uno I’ve bought this shield .
I’m looking for a way to display decimal point, without using any a designated library.
Most examples as this one shows only 0-9.
EDIT1 update link
Link

So if you click your 2nd link, it includes sample code for various sections of the multi-function shield.
One of them is titled "segment display".
If you look at that code, line 7 defines the bit patterns for each of the digits from 0 to 9:
const byte SEGMENT_MAP[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0X80,0X90};

If you map them out in binary, you get:
0xC0,   1100 0000   0
0xF9,   1111 1001   1
0xA4,   1010 0100   2
0xB0,   1011 0000   3
0x99,   1001 1001   4
0x92,   1001 0010   5
0x82,   1000 0010   6
0xF8,   1111 1000   7
0X80,   1000 0000   8
0X90    1001 0000   9

A 0 character has all the segments lit except the middle "cross-bar". An 8 character has ALL of the segments lit. But the bit pattern for 8 is 1000 0000. That suggests that a 0 bit means a segment is lit, and 1 means it is off. Since the highest order bit of all of those characters is 1 (off) it suggests that the high-order bit is the decimal place bit. (It's the only bit that never changes.)
So if you replace
const byte SEGMENT_MAP[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0X80,0X90};

with
const byte SEGMENT_MAP[] = {0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0X00,0X10};

You should get all the digits drawn with their corresponding decimal place lit.
I'd try that first to verify that I'm correct.
I'd then suggest writing code that reads the segments value for each digit, decides if you want a decimal place at that position, and if so, doing a bitwise AND (& in C/C++) on the value with 0X7F to clear the decimal bit for that character. (Remember it looks like a 0 means a given LED segment should be lit.
You could modify the function WriteNumberToSegment() to take a "lightDot" parameter, and have it change the bit if you pass TRUE (1):
void WriteNumberToSegment(byte Segment, byte Value, bool lightDot)
{
    digitalWrite(LATCH_DIO,LOW);
    bool bits = SEGMENT_MAP[Value]);
    if (lightDot) {
       bits &= 0x7F; //To light the decimal for this digit, clear the 0x80 bit
    }
    shiftOut(DATA_DIO, CLK_DIO, MSBFIRST, bits);
    shiftOut(DATA_DIO, CLK_DIO, MSBFIRST, SEGMENT_SELECT[Segment] );
    digitalWrite(LATCH_DIO,HIGH);
}

(I don't remember for sure if bool is a valid type in Arduino C/C++. If not, just replace bool with uint8 in the above.)


Arduino Uno 2 I2C devices problem I have two I2C devices connected to an Arduino Uno: an RTC and an OBD interface (see links below). The SCL/SDA of both devices connect parallel to SCL/SDA (respectively) of the Uno. My problem: when I set the time on the RTC (either using the autoset option, or explicitly) it reports back odd readings, like the date set back by 4 days, the hour set back by 2 hours etc. This happens even with the default bare-bones RTC sample sketch.

I tried two RTCs (one DS1307, and the one linked below): both show the same strange behavior. I tried 2 configurations: 1) NO pull-up resistors on either device, 2) two 10K pull-up resistors on BOTH devices. Both situations produce RTC errors. If I detach the OBD sensor from SCL/SDA, the RTC shows the proper time. If I remove the RTC, the OBD by itself (works fine. Before I spend more time experimenting: any advice how to solve this pull-up resistor situation (if this is what it is)?

Adafruit DS3231 Precision RTC

OBD Freematics interface

I imagine you are using the Adafruit Library, since thats the URL of the product you posted.

If so, in RTClib.h:

#define DS1307_ADDRESS  0x68
#define DS3231_ADDRESS  0x68

And in the OBDs product page:

OBD I2C Address: 0x68

MEMS I2C Address: 0x62

Which obviously causes a conflict.

It seems that they have a fixed I2C address (some devices are configurable via software, others with external pins). So the solution would be to use other RTC, other OBD (or change its address) or use a bus splitter, or use a MCU with more than one I2C bus.


Where are RX and TX pins on the GT2560? I'm adding WiFi (ESP8266) to my GT2560 board. Does anyone know where on the board are the RX and TX pins and the best place to connect to them?

This is all, no more info on the board in the internet and forums: https://www.geeetech.com/Documents/Users%20Manual%20of%20GT2560.pdf

Does anyone know where on the board are the RX and TX pins

The serial Rx and Tx signals from the ATmega2560, go to the nearby FT232RQ USB-to-serial adapter. You can look at the part numbers on the ICs and find those two devices on the PCB.

  no more info on the board in the internet and forums

It's good news that there does seem to be more information available :-) After a few minutes with Google (searching for GT2560 schematics) I found this download link for the schematics on this forum page.

Although it would be possible to reverse-engineer the PCB (or at least the relevant part of it) the schematics are still helpful, since the white coating makes the actual copper traces harder to follow visually.

The schematic shows that two 1k resistors, R3 and R13, are in series with serial signals:

R3 between ATmega Tx -> FT232 Rx
R13 between ATmega Rx <- FT232 Tx

You may want to confirm that the linked schematic still applies to your specific PCB (since PCB and schematic versions could have changed). With the power disconnected, you could check with a multimeter that there is continuity between the appropriate ATmega pin and one end of each resistor R3 & R13, and between the other end of each resistor and the appropriate FT232 pin, as shown on the schematic.

I have put a red ring around those 2 resistors on the GT2560 top view below, to help you to find them:

(original image source)

  best place to connect to them

If you are going to drive those serial signals from an ESP8266, you must first disconnect them from the on-board FT232, to avoid contention and so the ESP8266 replaces the FT232. Removing those two resistors would make each resistor's (now vacant) pads leading to the ATmega serial port, an ideal place to connect the ESP8266. (Of course you could attach wires directly to the pins of the ATmega or FT232, but I don't see any advantage to doing that.)

One issue which you need to consider, is the voltage compatibility of the serial port signals. The ATmega2560 uses 5V signal levels, whereas the ESP8266 is a 3.3V device. There have been discussions on various websites (example) that suggest the ESP8266 is 5V-tolerant on I/O pins. You will need to satisfy yourself whether to use voltage translation, or to rely on information discussed on web pages like that one.


Working or functionality of pinMode(), digitalWrite() and digitalRead() I'm a newbie in Arduino. I find out a couple of examples.

Here, below arduino simple code I just uploaded.

Here, what is functionality or working of pinMode, digitalWrite and digitalRead ?

const int kPinLed = 7;
const int kPinBtn = 8;

void setup()
{
  pinMode(kPinLed, OUTPUT);
  pinMode(kPinBtn, INPUT_PULLUP);
}

void loop()
{
  if(digitalRead(kPinBtn) == LOW)
  {
    digitalWrite(kPinLed, HIGH);
  }
  else digitalWrite(kPinLed, LOW);
}

{
  pinMode(kPinLed, OUTPUT);
  pinMode(kPinBtn, INPUT_PULLUP);
}

This block of code used to define mode of Pin i.e. making pin as Output pin or Input pin.

if(digitalRead(kPinBtn) == LOW)
{

}

This block of code is used to read value from defined digital pin either High or Low. And in return will give pin state High or Low. For example if we want to make LED ON which is connected to one of digital pin of Arduino at certain condition, we will define that pin under above block of code and can read state of that pin as High or Low.

 {
   digitalWrite(kPinLed, HIGH);
 }
 else digitalWrite(kPinLed, LOW);

This block of code is used to make Pin state High or Low i.e. Under certain condition this function will make pin state either High or Low.

To learn more, visit......

PinMode Click here

DigitalRead Click here

Digital Write Click here


How does Arduino IDE for mac deal with functions in other files I'm a longtime C programmer. I've also done a little C++, a little Java, and a LOT of Objective-C, but am fairly new to the Arduino platform and it's IDE.

So far all my sketches have had a single source file.

I see how you copy libraries into the libraries sub-folder of your Arduino source folder, either from the Mac finder or from the IDE.

I'm trying to understand somebody else's project (The "Camera Axe" device for high speed photography.) in that project there is a folder for the entire sketch, "cameraAxe". In that folder there's a file called "cameraAxe.ino", which follows the usual convention that the sketch's main source file needs to be inside a folder with the same name.

However, for this project there are 17 other source ".ino" files. Looking at the main "cameraAxe.ino" file, it only #includes 2 files, "EEPROM.h" and "DogmCA.h", both using the convention of enclosing the filename in angle brackets so the compiler knows to look in it's libraries directory. That makes perfect sense to me, and works like any other C compiler I've ever seen.

What I DON'T understand is how the compiler knows where to find the code for the many functions that are defined in other files in the same folder. There a function projectileMenu() which handles the menu for configuring a projectile sensor. That function is defined in the file menu01_projectile.ino, but it doesn't have a header, and there's no #include anywhere.

Does the compiler treat all the ".ino" files in your sketch folder as part of your source and compile them all together and as if they are one large file? I see tabs in the IDE for each of the files, which suggests that it does.

What if there are dependencies among the files? What defines the order in which they are compiled? Or is it a 2 pass compiler where the order of function definitions doesn't matter?

::wanders off, muttering in confusion::

arduino has its own little .ino preprocessor that generates forward declarations (like in a header file) for all function in the project's .ino files. Most of the time this just makes things less confusing for new users.

I'm not familiar with the entire process, but the effect is that any function in any .ino is known to all other .ino code.

Anything with .h or .cpp in a library or in the project file is treated as normal c++ code and not subject to arduino's manipulations. It will need "#include"s.

If you are interested, there is a hack to make arduino not mess with a function in a .ino file: add an empty "throw()" like this:

void foo() throw() {
}


NRF24l01 Channel switching I have a NRF24L01 radio module. The description indicates that it can work in the ISM frequency range of 2.400 ... 2.525 GHz. The channel step is 1 MHz, and there are 125 channels in total.

The channel number can be set using
radio.setChannel (0x125);
The maximum number is supposedly 125. However, I examined the signal spectrum in Sdrsharp using a radio tuner and it turned out that the frequency at the maximum channel is very low.

I started increasing the number and got to 180 radio.setChannel (125); the frequency was 2525 MHz as stated. It turns out that the number of channels of the radio module is not 125, but 180? I determined the 180 number experimentally. The literature says that it has 125 channels 1 MHz wide.
The most interesting thing is that the Arduino IDE does not give errors when entering a large number of channels. Tell me how you can speed up the process of switching channels in order to understand how they switch. To manually reflash it for a long time when changing each channel.
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

RF24 radio(9, 10); // use 9 и 10 pin arduino uno
byte address[][6] = {"1Node", "2Node", "3Node", "4Node", "5Node", "6Node"};
byte counter = 1;

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

  radio.begin(); //activate module
  radio.setAutoAck(0); //confirmation mode, 1 on 0 off
  radio.setRetries(0, 15); //(time between attempts to reach out, number of attempts)

  radio.setPayloadSize(32); //packet size, in bytes

  radio.openWritingPipe(address[0]); //we are pipe 0, we open a data channel
  radio.setChannel(125); //select a channel (in which there is no noise!) 0 ... 125

  radio.setPALevel (RF24_PA_MIN); //transmitter power level. To choose RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH, RF24_PA_MAX
  radio.setDataRate (RF24_2MBPS); //exchange rate. To choose RF24_2MBPS, RF24_1MBPS, RF24_250KBPS
  radio.powerUp(); //get started
  radio.stopListening(); //do not listen to radio broadcasts, we are a transmitter
}

void loop(void) {
  while (1)
  {
    radio.write(&counter, 1);
    //Serial.println(counter);
  }
}

Is it possible to toggle the channel number radio.setChannel (0x180) sequentially in a void loop?
thanks!
I tried to do this:
void loop (void) {
     for (int n = 0; n <126; n ++)
     {
       radio.setChannel (n); // select a channel (in which there is no noise!) 0 ... 125
       radio.write (& counter, 1);
       delay (1000);
     }
}

However, radio.write (& counter, 1) should work separately from any loops to avoid delays. Otherwise, it doesn't work correctly.

You're getting confused with number bases. A number prefixed with 0x is hexadecimal. That's base 16 - not base 10.
0x125 is actually 293. If you try squeezing 293 into an 8-bit register it will truncate to 37.
Channel 125 is 0x7D in hexadecimal.
I can't recall off hand how big the register is for the channel number, but either 7 or 8 bits would suffice (probably only 7 bits actually used) so the highest channel number you could possibly enter would be 127, which is 0x7F, after which it will start at channel 0 again for 128 or 0x80.


2.8" TFT Touchscreen Prohibits Access to Unused Pins This is probably a beginner question. You've been warned.

I recently purchased a touchscreen (http://www.adafruit.com/products/1651#tutorials) specifically because it left so many pins open to work with and I needed to hook up one, possibly two more items to my Arduino. However the touchscreen fits over the Arduino and covers all the pins.

How do I access the pins that the LCD isn't using?

To be specific, I will be adding a Galvanic Skin Sensor on two analog pins.

Several options:

Use wires to connect it rather than sticking it directly onto the Arduino.
Use a header extension to lift the display away from the other headers.
Use right-angle headers on the other pins.


Does ATMega 328/2560 chips support JTAG-type programmer and hardware debugger? As stated in www.Arduino.cc FAQ, "Can I use an Arduino board without the Arduino software? Sure. It's just an AVR development board, you can use straight AVR C or C++ (with avr-gcc and avrdude or AVR Studio) to program it."

For UNO/Pro Mini(ATMega328) and ATmega2560, does these two chips support JTAG type (some chip manufacturers may use different name) programmer / hardware-based debugger in same manner as the ST-Link/J-Link programmer/debugger where one can load code into the MCU and perform hardware break point and single stepping? Example as in  STM32 development board with ST-LINK programmer / debugger where the chip has built-in debug circuit that communicate with ST-Link.

Many thanks in advance.

The ATmegaXX8 does not support JTAG, but the ATmegaXX0, 'XX1, and 'XX4 do. The 'XX8 (as well as other AVR families) supports debugWIRE, which allows debugging over ISP. You will need one of Atmel's debuggers such as the AVR ONE! or the Atmel-ICE as well as Atmel Studio in order to use it.


Are pins 2 and 3 supposed to be connected? I was playing with my arduino ad realized that pins 2 and 3 are somehow connected. When I press a button to for pin 2, it sets both pin 2 and pin 3 to HIGH even though nothing is connected to pin 3. The code I have is set up for pin 2 and mentions nothing about pin 3 but if i change the hardware to plug it into pin 3, it behaves as pin 2 would. None of the other pins do this. Is it supposed to be like this or is something wrong?

int switchState = 0;

const int led1 = 12;
const int led2 = 8;
const int led3 = 3;
const int button = 2;

void setup() {
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(button, INPUT);
}

void loop() {
  switchState = digitalRead(button);
  if(switchState == HIGH){
    digitalWrite(led3, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led1, HIGH);
    delay(500);
    digitalWrite(led3, LOW);
    digitalWrite(led2, HIGH);
    digitalWrite(led1, LOW);
    delay(500);
  }
  else{
    digitalWrite(led3, HIGH);
    digitalWrite(led2, LOW);
    digitalWrite(led1, LOW);
  }
}

An input that isn't connected to anything "floats". It will give you unpredictable values. It could be influenced by nearby pins. That is probably what you are seeing. (The metal traces for the 2 pins probably run next to each other on the Arduino's PC board.)

You should either tie an input to ground with a resistor, tie it to +5V with a resistor, or use INPUT_PULLUP mode, which ties it to an internal pull-up resistor. Any of those things will prevent the input from "bouncing around" and giving unpredictable results.

(Note that using a pull-up resistor, either internal or external, has the result of inverting the logic state you get from that input (you get HIGH when the input is not connected to ground, and LOW when it is connected to ground.)


dns lookup only works with DHCP and not with static setup (EtherCard library) When I use DHCP with ether.dhcpSetup() the DNS lookup for NTP ether.dnsLookup("0.pool.ntp.org") works fine, but when I use a static setup (because my Android app needs to know the IP address) with ether.staticSetup(myip); then this returns false and I don't get an IP address from the NTP pool. How come?

I have an Arduino Nano ATmega328 with a ENC28j60 ethernet shield, and therefore use the EtherCard libray.

Full MWE:

#include <EtherCard.h>      // https://github.com/jcw/ethercard
#include <Time.h>           // http://www.arduino.cc/playground/Code/Time

static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
static byte myip[] = {192, 168, 2, 106};
const char poolNTP[] PROGMEM = "0.pool.ntp.org"; //pool to get time server from
uint8_t ntpMyPort = 123; //port for the time server, no idea why needed

byte Ethernet::buffer[700];

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

 //do not forget to add the extra '10' argument because of this ethernet shield
  if (ether.begin(sizeof Ethernet::buffer, mymac, 10) == 0) {
    Serial.println(F("Failed to access Ethernet controller"));
  }

  //static setup
  ether.staticSetup(myip);
  ether.printIp("Address: http://", ether.myip);

 //this works
//  if (!ether.dhcpSetup())
//    Serial.println(F("DHCP failed"));

  //Find ip address of a time server from the pool
  if (!ether.dnsLookup(poolNTP)) {
    Serial.println("DNS failed"); //with static setup this line is executed, not so with DHCP
  }
  ether.printIp("Lookup IP   : ", ether.hisip);
}

void loop () {}

DHCP does more than just give you your IP address: it also gives you the Net Mask, the Gateway IP address, and the DNS Server IP address. If you don't call dhcpSetup(), you'll have to do it yourself.

According to the EtherCard documentation, you can do that as follows:

const static uint8_t ip[] = {192,168,0,100}; // Example
const static uint8_t gw[] = {192,168,0,254}; // Example
const static uint8_t dns[] = {192,168,0,1};  // Example

...

if (!ether.staticSetup(ip, gw, dns)
{
    // handle failure to configure static IP address
    // (current implementation always returns true!)
}


Arduino Leonardo(Atmega32u4) - Detecting if USB is connected to a computer? The closest thing I can find is if(Serial) but that only returns true if there's a serial port open.

The function I want, ideally, should:

Return true if plugged into a computer

Return false if plugged into a USB power bank

Return false if not plugged in at all(Running off of its own lithium cell)

ADDEN of UDADDR is set if the '32U4 has been assigned a USB address by the host and the firmware wants to enable USB connectivity.

UDADDR & _BV(ADDEN)


How do I add Gyroscope, Accelerometer, Euler, and Temperature data to one Arduino board? I have to use a BNO055 to get temperature/accelerometer/Euler/Gyroscope data into one Arduino board for a school project. I am very new to coding so I am not familiar with the commands. I have gotten my BNO055 to give me all the data individually but I am having problems getting them all compiled into one code file to upload. I have googled it but I keep getting links to upload them individually. Posted below is my latest attempt.

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Orientation Sensor Test"); Serial.println("");

  /* Initialise the sensor */
  if (!bno.begin())
  {
    /* There was a problem detecting the BNO055 ... check your connections */
    Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
    while (1);
  }

  delay(1000);

  bno.setExtCrystalUse(true);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  /* Display the current temperature */
  int8_t temp = bno.getTemp();

  Serial.print("Current Temperature: ");
  Serial.print(temp);
  Serial.println(" Celsius");
  Serial.print("");
}

void loop(void)
{
  /* Get a new Sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> gyroscope = bno.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(gyroscope.x());
  Serial.print(" Y: ");
  Serial.print(gyroscope.y());
  Serial.print(" Z: ");
  Serial.print(gyroscope.z());
  Serial.println("");
  delay(100);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> accelerometer = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(accelerometer.x());
  Serial.print(" Y: ");
  Serial.print(accelerometer.y());
  Serial.print(" Z: ");
  Serial.print(accelerometer.z());
  Serial.println("");
  delay(100);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(euler.x());
  Serial.print(" Y: ");
  Serial.print(euler.y());
  Serial.print(" Z: ");
  Serial.print(euler.z());
  Serial.println("");
  delay(100);
}

Does the code below work? I have no compiler at hand, so I can not test it.
If you have to explain what you have done, you'll get into trouble. I don't know your teacher, but ... ;-). Seriously, that was very basic stuff. Try to find some documentation, how to program with the Arduino IDE and learn the basics. A good startpoint is https://www.arduino.cc/en/Tutorial/HomePage .
Then go on with SENSORs and Vector Maths.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Orientation Sensor Test"); Serial.println("");

  /* Initialise the sensor */
  if (!bno.begin())
  {
    /* There was a problem detecting the BNO055 ... check your connections */
    Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
    while (1);
  }

  delay(1000);

  bno.setExtCrystalUse(true);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  /* Display the current temperature */
  int8_t temp = bno.getTemp();

  Serial.print("Current Temperature: ");
  Serial.print(temp);
  Serial.println(" Celsius");
  Serial.print("");

  imu::Vector<3> gyroscope = bno.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(gyroscope.x());
  Serial.print(" Y: ");
  Serial.print(gyroscope.y());
  Serial.print(" Z: ");
  Serial.print(gyroscope.z());
  Serial.println("");
  delay(100);

  imu::Vector<3> accelerometer = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(accelerometer.x());
  Serial.print(" Y: ");
  Serial.print(accelerometer.y());
  Serial.print(" Z: ");
  Serial.print(accelerometer.z());
  Serial.println("");
  delay(100);

  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(euler.x());
  Serial.print(" Y: ");
  Serial.print(euler.y());
  Serial.print(" Z: ");
  Serial.print(euler.z());
  Serial.println("");
  delay(100);
}


Splitting String from Serial I am currently working on a program for an Arduino uno and want to, in the program, when it receives a 16 digit number from a serial transmition, it will split the 16 digit number into 4 separate 4 digit numbers.

For Example:
The computer sends the Arduino the number 1100115011001150 and I want the Arduino to break the number so that "Avalue" would equal 1100, "Bvalue" would equal 1150, "Cvalue" would equal 1100 and so on...

Thanks for any help you can provide!

char ArrayBuffer[][4] = {};         // holds four characters, must be

declared as global to loop()

in

loop()
{
byte Index = 0;                    // initialize array index
if(Serial.available())             // have data in Serial buffer
{
byte Count = Serial.readBytes(ArrayBuffer[Index],4); // read       //4             //characters     into array buffer , returns actual number //of        characters //read and times out if less than 4 characters are //currently in Serial buffer
 Serial.println(ArrayBuffer[Index]); // print buffer to monitor
}while(++Index != 4);              // read 4 by 4 characters from incoming stream
}

...
continue with loop - process ArrayBuffer as required
}

This is one way to get the incoming stream from Serial buffer into for individual buffers, however, it is better, less chance of misdirecting the data into wrong buffer (index)  to read the entire buffer at once instead of using he readBytes four times.
Just my opinion, your mileage will vary.

PS what is the trick to format the code and text correctly ?
This is a mess.
I cannot get the code block to indent, I can get only the first ( four spaces line.


Attaching Microcontroller to DAC evaluation board For an independent undergraduate research project I'm trying to construct a digital feedback loop. I have never used an Arduino, or done much electrical/computer engineering, so I'm just taking things one thing at a time.
I've been given this
microcontroller
and this DAC eval board, and now I'm just trying to put them together.

From reading, I need to  attach jumper cables from #16 here to

the pins on the Eval Board here,

but I don't know where to find information on them, so I don't know which to plug into what. Any advice?

Your DAC uses the SPI protocol.  For that you want to connect it to the SPI header. That's the 6-pin (3x2) header numbered 11 on the uC32.

Connect:

The uC32's SCK pin to the DAC's SCLK
The uC32's SDO pin (MOSI) to the DAC's SDIN pin.
The uC32's SDI pin (MISO) to the DAC's SDO pin.

The other pins (I am not sure what they all do off hand, but the datasheet details them) can connect to any GPIO pins you like (except pins 11-13 which duplicate the SPI header - so you could use those instead if you prefer - 11=MOSI, 12=MISO, 13=SCK).


Connect a button to bluetooth board and comunicate with Android I want to create a small device, just a button that sends its status to an Android application through Bluetooth.

I bought a Bluno Beetle, but the information it exposes to Bluetooth cannot be modified from Arduino code, so I have no way to send the button status to the Android App, rookie mistake I guess.

Could you please tell me which model of arduino+bluetooth should I purchase to do this ?

For your project you can buy cheap Arduino Nano, or even Mini(programmer needed). For BT module buy HM10. It's cheap and it supports Bluetooth Low Energy.


Will a 12 VDC 1A Power Supply Adapter supply too much power and damage an Arduino Mega 2560? The specs shown here:

show that it has 54 digital pins with each outputting a DC current of 20mA which makes it 54 * 20 = 1080 mA

Plus the DC current of the 3.3V Pin of 30mA we get a total of 1110mA.

Is this how one should go about doing the computations?

If the adapter is insufficient will a 12 VDC 2A Power Supply Adapter be appropriate or excessive?

Any links to read up on will be greatly appreciated as well.

Links for this question:

https://store.arduino.cc/mega-2560-r3

https://store.nerokas.co.ke/index.php?route=product/product&product_id=567

PS: All I'm planning to connect to the board is: 'a PIR sensor (the first version not Rev B)', a '5V relay' and possibly a 'ESP8266 ESP-01S Relay Module'

No. You have everything wrong there.

First off, a power supply does not provide power. It provides voltage. The device attached to it then draws current. As much current as it needs at any particular moment in time.  The current rating of a power supply is the maximum that the power supply can give.

The same goes for Arduino IO and power pins: The current ratings are the maximum current you can draw from the pin.

Exactly what current it will draw from the power supply depends completely on what is connected to what pins, and even what calculations the Arduino is doing at the time.  To get a ball-park figure of current requirements you need to know the current requirements of whatever is attached. If a device has its own power input that is the current you need to worry about. If a device is powered directly from an IO pin (such as an LED) then that forms part of the Arduino's current (which starts at about 40mA or so for the board itself).

There are many other factors to take into consideration:

The 5V regulator on the Arduino can't give more than 1A maximum, and considerably less than that when powered from a high voltage like 12V.
The DC jack on the Arduino is limited to 1A due to a polarity protection diode.

It is usually recommended to use a separate 3.3V regulator for an ESP8266 module (or 5V if your module has a built-in 3.3V regulator) due to the lack of power capacity in the Arduino's on-board regulators.

As a rough guestimate:

Arduino: 40-60mA
ESP8266: 200mA (when transmitting)
PIR: Negligible
Relay: 50mA when active

So you'd be looking at 300mA as a minimum. More is better. 1A should be more than sufficient. 2A would be overkill but give a big margin of error.

For everything you have there, it would be better to use a 5V power supply, not a 12V power supply.


Possibility of getting a UID on Arduino Im working on a project where I will be using multiple Arduino (pro mini)'s which emit sensordata through LoRa.

The problem I am currently facing is, when I have multiple sensors, how do I know what data is coming from which Arduino (given they all have exactly the same source-code)?

Does the arduino have a UID like some sort of MAC code?
What could be a solution to give the Arduino a UID?
Do you guys have any other solutions for my issue?

In order to answer #2, I could add a random number calculator to create, but this doesn't feel right to me.

You could use a small silicon serial chip like the Maxim DS2401 (http://pdfserv.maximintegrated.com/en/ds/DS2401.pdf)

An other method is to use good old dipswitches. That way you set each of your 'transmitter' to different address using the dipswitch. On boot the Arduino reads the switches to know it's address and uses that.


Change operational mode of CAN transceiver I have two MCP2515 stand-alone CAN controllers with SPI interface, two TJA1042 CAN transceivers and two Arduino Uno boards. As you may know TJA1042 have two operational modes:

Sleep mode
Normal mode.

If I want to change the mode of operation of one transceiver from sleep mode to normal mode(wake it up), I should send a wake up pattern waves from the other transceiver which is in normal mode. for example one of the wake up patterns is: 5.5 µS low, 5.5 µS high and again 5.5 µS low. Now I don't know how to send these patterns with Arduino because MCP2515 is SPI interface.

I use this library: MCP_CAN

Transmitting this "wake signal" does not "wake" the transceiver.  What it's actually doing is the transceiver, when in "standby" mode, only allows through signals that have a dominant or recessive state that is longer than the filter time (5.5µs). Any transitions in the bus after a stable period of 5.5µs or more will get passed through.

The transceiver does not enter "normal" mode at that point. It is down to the CAN device to activate the transceiver through setting the STB pin LOW.

  When pin RXD goes LOW to signal a wake-up request, a transition to Normal mode will not be triggered until STB is forced LOW.

Exactly what you send is of no consequence to the transceiver - only whether it has D and R states that are longer than 5.5µS.  It's up to the CAN device to interpret them and know if it should wake up the transceiver and place it in NORMAL mode.

And the MCP2515 also doesn't care what it receives.  When the WAKEIE bit is set it will cause the MCP2515 itself to wake from its sleep mode when anything is received - at which point it signals to the Arduino through its INT pin that it's woken up.

However your chosen library has no ability included in it to control the WAKEIE bit of MCP_CANINTF - only the TXxIF bits are supported.  So you will have to expand the library to provide that facility.

The general idea of operation is:

The transceiver lets through a "slow" signal (like transmitting 0b00110011)
The MCP2515 receives "something"
INT pin goes LOW and the Arduino reacts to it
The Arduino drives STB LOW and reception can proceed normally.

Note that it is the Arduino that will be controlling STB, not the MCP2515.


USB FT232 driver on M1 mini I've scored a couple Nanos with FT232RL chips but can't see them on my brand new M1 mini. Can someone point me at how to determine whether v11.1 supports this USB chip?
It appears that the device is being instantiated but the Arduino IDE gets no response to the Get Board Info.
FT232R USB UART:

  Product ID:   0x6001
  Vendor ID:    0x0403  (Future Technology Devices International Limited)
  Version:  6.00
  Serial Number:    AR0JT9YB
  Speed:    Up to 12 Mb/s
  Manufacturer: FTDI
  Location ID:  0x02214000 / 20
  Current Available (mA):   500
  Current Required (mA):    90
  Extra Operating Current (mA): 0

Executing the ioreg mentioned by @st2000 gives;
+-o Root  <class IORegistryEntry, id 0x100000100, retain 31>
  +-o AppleT8103USBXHCI@00000000  <class AppleT8103USBXHCI, id 0x100000291, registered, matched, active, busy 0 (1676 ms), retain 328>
  | +-o Extreme SSD@00200000  <class IOUSBHostDevice, id 0x10000081d, registered, matched, active, busy 0 (219 ms), retain 132>
  +-o AppleT8103USBXHCI@01000000  <class AppleT8103USBXHCI, id 0x100000295, registered, matched, active, busy 0 (4 ms), retain 39>
  +-o AppleT8103USBXHCIFL1100@02000000  <class AppleT8103USBXHCIFL1100, id 0x1000006eb, registered, matched, active, busy 0 (1220 ms), retain 494>
    +-o Keyboard Hub@02100000  <class IOUSBHostDevice, id 0x10000071c, registered, matched, active, busy 0 (164 ms), retain 30>
    | +-o Apple Keyboard@02120000  <class IOUSBHostDevice, id 0x100000805, registered, matched, active, busy 0 (162 ms), retain 32>
    +-o 4-Port USB 2.0 Hub@02200000  <class IOUSBHostDevice, id 0x100000730, registered, matched, active, busy 0 (826 ms), retain 46>
    | +-o 4-Port USB 2.0 Hub@02230000  <class IOUSBHostDevice, id 0x100000785, registered, matched, active, busy 0 (11 ms), retain 42>
    | +-o 4-Port USB 2.0 Hub@02220000  <class IOUSBHostDevice, id 0x100000791, registered, matched, active, busy 0 (16 ms), retain 43>
    | | +-o Backup+ Hub@02223000  <class IOUSBHostDevice, id 0x1000007dc, registered, matched, active, busy 0 (6 ms), retain 41>
    | +-o 4-Port USB 2.0 Hub@02210000  <class IOUSBHostDevice, id 0x10000079d, registered, matched, active, busy 0 (776 ms), retain 43>
    | | +-o FT232R USB UART@02214000  <class IOUSBHostDevice, id 0x100007622, registered, matched, active, busy 0 (75 ms), retain 23>
    | +-o 4-Port USB 2.0 Hub@02240000  <class IOUSBHostDevice, id 0x1000007b6, registered, matched, active, busy 0 (12 ms), retain 42>
    +-o 4-Port USB 3.0 Hub@02600000  <class IOUSBHostDevice, id 0x100000749, registered, matched, active, busy 0 (231 ms), retain 46>
      +-o 4-Port USB 3.0 Hub@02620000  <class IOUSBHostDevice, id 0x10000075e, registered, matched, active, busy 0 (170 ms), retain 43>
      | +-o Backup+ Hub@02623000  <class IOUSBHostDevice, id 0x1000007c3, registered, matched, active, busy 0 (155 ms), retain 41>
      |   +-o Backup+ Hub BK@02623100  <class IOUSBHostDevice, id 0x1000007ee, registered, matched, active, busy 0 (147 ms), retain 131>
      +-o 4-Port USB 3.0 Hub@02640000  <class IOUSBHostDevice, id 0x100000763, registered, matched, active, busy 0 (15 ms), retain 42>
      +-o 4-Port USB 3.0 Hub@02630000  <class IOUSBHostDevice, id 0x100000775, registered, matched, active, busy 0 (15 ms), retain 42>
      +-o 4-Port USB 3.0 Hub@02610000  <class IOUSBHostDevice, id 0x1000007a9, registered, matched, active, busy 0 (16 ms), retain 42>

Which does not appear to contain the device afai can see. Any know if this means a new device for Big Sur is indicated as per Majenko♦ ?

A MAC is usually (unless it is really old) running a derivative of Unix. I would open a console install and use "lsusb" to list out all the USB connected devices.
A (Linux) example of lsusb:
$ lsusb
Bus 001 Device 004: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port

I would do this with and with out the Arduino FTDI chip connected and look for the difference. This stackexchange question/answer contains how to do this on a MAC or use other MAC commands to do the same.  As pointed out in the comments the more native MAC command is:
ioreg -p IOUSB

Note, if you have fake FTDI chips there was a time when the FTDI driver that Windows ran would brick the fake FTDI chip. I think it would assign the vendor and device IDs both to zero. You should be able to see this with the "lsusb" command.


SPI Overflow in 328 slave with i2c sensor I am working on creating sensor poller that is going to be polling multiple sensors and then, on request, provides its data to the master.

The master polls the slave (SPI) at 50hz and the slave is polling it's sensor (BNO055) (I2C) at 100hz.

The transaction works most of the time but every once in a while it returns an overflow.

Any ideas why this might occur?

Slave code:

/*************************************************************************
 *
 * objeeAirlines
 * __________________
 *
 *  Written by Julian Blanco
 *
 *  Spi slave code written by
    Nick Gammon
    February 2011
 */

#include "Adafruit_BNO055.h"

float yawInput=0;
float yawOffset=0;
float pitchInput=0;
float rollInput=0;

int calibration=0;

volatile byte command = 0;
Adafruit_BNO055 bno = Adafruit_BNO055();

void setup (void)
{

  if(!bno.begin())while(1){};
  bno.setExtCrystalUse(true);
  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  // turn on SPI in slave mode
  SPCR |= _BV(SPE);
  // turn on interrupts
  SPCR |= _BV(SPIE);
}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  union first_union{
    float f;
    byte b[4];}
  data;

  byte c = SPDR;

  data.f = yawInput;

  command = c;

  switch (command)
  {
  // no command? then this is the command
  case 0:

    SPDR = 0;
    break;

  // incoming byte, return byte result
  case 'a':

    SPDR = data.b[0];
    break;

  // incoming byte, return byte result
  case 'b':

    SPDR = data.b[1];
    break;

  // incoming byte, return byte result
  case 'c':

    SPDR = data.b[2];
    break;

  // incoming byte, return byte result
  case 'd':

    SPDR = data.b[3];
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect
float tiempo=millis();
void loop (void)
{

  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH) command = 0;

    if(millis()>(tiempo+10))
    {
      tiempo=millis();
      SampleGyro(bno);
    }

}  // end of loop

void SampleGyro(Adafruit_BNO055 &gyroIMU){
    /* Display the floating  point data */
    imu::Vector<3> euler = gyroIMU.getVector(Adafruit_BNO055::VECTOR_EULER);
    yawInput=euler.x()-yawOffset;

    if (yawInput >= 360)
    {
          yawInput -= 360;
        }
    else
    {if (yawInput < 0)yawInput += 360;
    }
    pitchInput=euler.y();
    //rollInput=fmod((euler.z()+(360+90)), 360)-180;
    rollInput=euler.z();
    uint8_t system, gyro, accel, mag = 0;
    gyroIMU.getCalibration(&system, &gyro, &accel, &mag);
    calibration=system;
}

Master Code:

#include <SPI.h>

#define SS 10
void setup (void)
{
    pinMode(MOSI, OUTPUT);
    pinMode(MISO, INPUT);
    pinMode(SCK, OUTPUT);
    pinMode(SS, OUTPUT);

  Serial.begin (115200);
  Serial.println ();

  digitalWrite(SS, HIGH);

  SPI.begin ();

  SPI.setClockDivider(SPI_CLOCK_DIV8);
}

  byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (10);
  return a;
}

  union first_union{
    float f;
    byte b[4];}
  data;

void loop (void)
{

  digitalWrite(SS, LOW);

  transferAndWait ('a');

  data.b[0] = transferAndWait ('b');
  data.b[1] = transferAndWait ('c');
  data.b[2] = transferAndWait ('d');
  data.b[3] = transferAndWait (0);

  digitalWrite(SS, HIGH);

  Serial.print("data.f = ");Serial.println(data.f);

  //Serial.print("data.b[0] = ");Serial.println(data.b[0]);
  //Serial.print("data.b[1] = ");Serial.println(data.b[1]);
  //Serial.print("data.b[2] = ");Serial.println(data.b[2]);
  //Serial.print("data.b[3] = ");Serial.println(data.b[3]);

  delay(10);
}

It is likely that your SPI interrupt on the slave is firing in the middle of updating your global yawInput variable. This would cause the value to be partially updated when you send it back to the master. You might even be sending part of the old value and part of the new value back to the master. It depends on when the interrupts fire.

You need to lock your SampleGyro function somehow. The easiest way would be to disable interrupts when modifying any interrupt accessible variables (i.e. yawInput).

Something like this should tell you if the interrupt timing is the issue:

void SampleGyro(Adafruit_BNO055 &gyroIMU){
    /* Display the floating  point data */
    imu::Vector<3> euler = gyroIMU.getVector(Adafruit_BNO055::VECTOR_EULER);
    uint8_t system, gyro, accel, mag = 0;
    gyroIMU.getCalibration(&system, &gyro, &accel, &mag);

    // Disable interrupts while modifying the global variable
    noInterrupts()
    yawInput=euler.x()-yawOffset;
    if (yawInput >= 360) {
          yawInput -= 360;
    } else if (yawInput < 0) {
          yawInput += 360;
    }
    pitchInput=euler.y();
    //rollInput=fmod((euler.z()+(360+90)), 360)-180;
    rollInput=euler.z();
    calibration=system;
    // re-enable interrupts once your global variable
    // modification is done.
    interrupts();
}

It's also worth noting that you want to put as little code between the noInterrupts() and interrupts() calls as possible. Things like I2C and SPI and basically any other communication will likely not work inside of that block. I rearranged your SampleGyro function to put all calls to the gyro outside of the lock. This is to prevent the sensor reading from failing.


Create a Li-Polymer Battery Charger I want to Create a battery Charger with the Arduino with real time battery status. I don't have any idea how to do that same time as the charging.

  I know to use a serial monitor to get battery status but not to charge.

I would like to know how to do that simultaneously so that I don't over charge the battery.

This is the battery for Lumia 822
Nokia BP-4W 1800mAh 3.7v 6.7Wh

(1) A simple method
BEST method is to use a proper charger - they are not high cost if you look around and doing it properly extends precious battery life.
Next best in this context is my "better" method in 2. below.
BUT, given the system you say you are using now, the following very simple method will greatly improve your result and ave your battery from an early death.
You need a 1 Ohm resistor and a voltmeter that you can trust to read a 4.1V votage accurately. Without these the simple method risks battery damage or destruction - just as your present method does.
Warning: Straight connection to a USB port is very unwise but may be viable if the port current-limits.

If the current is ever higher than the rated maximum then battery destruction may occur.

If the battery voltage ever exceeds 4.2V at room temperature battery damage WILL occur and battery destruction may occur.

Worst case a badly treated battery can turn into a flaming inferno in seconds.
A usably OK result can be gained by:
(1) Calculate Imax = same mA as battery mAh capacity.
LOWER is OK. Higher is not.
eg 1200 mAh battery = 1200 mA max and say 1000 or 500 or lower mA is OK.
(2) Connect a ONE OHM resistor in USB to battery line.
(3) Connect discharged LiPo battery to USB port via 1 Ohm.
(4) Measure voltage across the resistor.  The voltage will be 0.001 Volt for every mA that flows. eg
1000 mA gives 1.000 Volt
789 mA gives 0.789 V.
1234 mA gives 1.234 V. etc.
If the measured mA is LESS THAN Imax in (1) above then this is OK to charge with.
(5) Use Arduino analogRead() function WHILE CHARGING to measure battery voltage.
BE SURE that the voltage that you read with the Arduino matches what a quality meter says.
When Vbattery (measured from Bat + to Bat- AT the battery) measures 4.1 V STOP CHARGING, remove voltage.
Battery will be perhaps 70% charged and will have a long cycle life (if not already damaged).
For 10 bit ADC = 1024 counts total (0-1023) then
for 5V reference 4.1V count = 4.1/5 x 1023
= 838 counts.
Using 830 counts to start with is safer.
When battery is at the upper charge limit,  and before removing Vcharge, measure voltage at battery with calibrated quality meter. Result should be 4.1V using above system.
Even with a quality calibrated meter NEVER exceed 4.2V - and 4.1V is better.
The BEST method is to use a proper charger - they are not high cost if you look around and they extend precious battery life.
._______________________________
(2) A better method:
LiIon (Lithium Ion)and LiPo (Lithium Polymer) batteries are functionally the same for charging purposes. I'll use the term "LiPO" from here on. I'll assume single cell batteries as most in cellphones and similar are. If the terminal voltage is between about 2.5V (should really be higher) and 4.3V they are single cell,
LiPo batteries have 4 main charge areas.

Under about 2V = dangerously dead. Discard

2V to about 3V = under voltage - charge very slowly

3V to 4.2V = charge at CC  = Constant Current.

On reaching 4.2V charge at CV = Constant Voltage until current reduces "automatically" (under battery chemistry control)  to about 1/4 x max rate.

Max charge rate is set by the manufacturer but is almost always the numerical mAh rating in mA. eg for a 1000 mAh battery max rate is 1000 mA. For a 3300 mAh battery it's 3300 mA etc. In a very few cases it is lower - maybe =half standard values and for a very small number of cells its higher - assume you do not have those.
Max voltage MUST NOT exceed 4.2V at room temperature. Lower, say 4.1V, does no harm and increases battery cycle life while slightly reducing capacity per charge.
The battery mAh rating is known as "C".
If C = 1200 then a cahrage rate of 1200 mA = C/1,
a charge rate of 300 mA = C/4,
a charge rate of 12 mA = C/100 etc
An easy charging method that gives long cycle life and about 70% to 80% of max possible capacity and a fast charge is

Determine max charge rate = C  = Imax = same mA as battery has mAh capacity.

If Vbattery is < 3V, charge at C/20 or less until Vbattery reaches 3V.
If Vbattery never reaches 3V it is dead.

When V_battery = >= 3V, charge at C/1 until Vbattery = 4.2V ( or 4.1V)

Finished!.

Remove applied voltage. DO NOT EVER leave 4.2V applied to a charged battery.

A more usual method that is only slightly harder is.

Monitor charge current.

Charge as above until Vbat = 4.2V.

While holding Vbat at 4.2V monitor charge current. This will fall as the battery absorbs additional charge.

When  Icharge falls to C/2 or C/4, stop charge. C/4 adds slightly more charge than C/2 but shortens cycle life.

Again - DO NOT leave 4.2V applied to battery once charged. Doing so will destroy the battery rapidly. Remove all voltage once charged.

.______________________________
Battery University:
Charging Lithium Ion & LiPo
Increasing lifetime
Index
.______________________
Q&A

Q: This is a 3.7v battery by giving 4.2v will it destroy it or are you referring 4.2v to explain the concept.

Read the above material and the battery university pages.
4.1 V ABSOLUTE MAXIMUM is what I recommended.

Most LiPo single cell batteries are labelled as 3.6 V or 3.7 V as that is approximately the average voltage across the discharge cycle.

When fully charged they are at about 4.2 V (or 4.1 V if you take my advice - which you should :-).

As they discharge the voltage falls and by the time they get to just above 3 V they are essentially fully discharged. They should never be discharged below 3 V as it damages them and there is only a tiny amount of energy left.

So 4.1 V ABSOLUTE MAXIMUM is good
MEASURED WHILE CHARGING and
AT the battery terminals or very close to them.
ie no long leads or resistors or connectors.
If using an Arduino to measure battery voltage,  connect an Arduino ground lead to battery negative with as short a wire as practical and the ADC +ve input to the battery +ve at the battery connection point.
So once more: A LiPo battery labelled as 3.6V or 3.7V can and should be charged to 4.1V maximum and never discharged to below 3V.


Waveshare 1.54 inch ePaper display requires 5Vs from Arduino Uno I have an Arduino Uno and I would like to attach a Waveshare 1.54“ display (red, black & white) to it.

All the specs tell me that it consumes 3.3 V which I have readily available on the Arduino Uno.

I could not get the display to work until I attached the Power pin to 5V instead of 3.3V.

I did try this with two different ePaper displays and the situation was the same.

I also tried to power the display with a Raspberry Pi‘s 3.3V (with the GNDs connected). But this did not work either.

So I am wondering what I am missing here, is it simply a power issue and my Arduino can‘t deliver the necessary current?

The answer lies in the FAQ for that display:

  Why the e-Paper cant work with Arduino?

  Answer:

  The I/O level of Arduino is 5V, and the e-Paper should be driven with 3V3. If your Arduino cant drive the e-Paper successfully, please try to convert the level to 3.3V

  You can also try to connect the Vcc pin to the 5V of Arduino to see whether the e-Paper works, but we recommend you not to use 5V for a long time.

So while you can run it from 5V, you really shouldn't, since you run the risk of breaking it.

Instead, you should employ proper logic level shifting to reduce the Arduino's outgoing signals to 3.3V and, more importantly, boost the incoming signals from the display to 5V.


In the AnalogRead example, would the thing work if I remove or short the A0 and the ground pin? What I want to know is that how exactly does analogRead work because I have want to use it with a flex sensor and it has only two pins.I tried to find other examples on the internet, but this is the only example I find.If the middle pin of the 10k potentiometer and a0 pin are shorted or the gnd  pin is removed altogether,then would this thing work?

I think you are confused because the ADC input measures voltage, not resistance.

To convert from resistance to voltage you need to pull in the opposite direction on the variable resistance with a fixed resistor.  As in the following image from this tutorial.


project not working when switching to battery power I have a project which involves a photocell, an led, a push button, and a small hobby servo (tower pro sg5010) - the project works as expected when the arduino is powered by usb, but when I switch to battery power (4 AA batteries) - it doesn't work.

When powered by batteries, the servo actually starts right up and moves to the correct angle, so I feel like it should be getting enough power, but when I push the push button, it doesn't move to the new angle. I can hear a clicking noise of the servo on a regular interval, like a clock, and my LED flickers on and off at about the same interval.

If I'm doing something wrong, can anyone point it out? If it's just that the servo is not getting enough power, is there a way to add a transistor or something so that I don't have to add a separate power supply for the servo (I'm not sure there's room in my project's enclosure).

I've attached a fritzing diagram as well as my project code.

CODE:

#include <Servo.h>

const int buttonPin = 2;     // the number of the pushbutton pin
boolean buttonPushed = false;

const int ledPin =  13;      // the number of the LED pin

const int servoPin = 9;
Servo servo;
int angle = 0;
int servoStartAngle = 90;
int servoEndAngle = 10;

boolean servoActivated = false;

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

int photoCellPin = 2;
int photoCellThreshold = 500;
int photoCellActivated = false;

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

  servo.attach(servoPin);
  servo.write(servoStartAngle);

}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  int photoCellVal = analogRead(photoCellPin);

  if (photoCellVal > photoCellThreshold){
   photoCellActivated = true;
  } else {
   photoCellActivated = false;
  }

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW && buttonPushed == false) {
    // turn LED on:
    buttonPushed = true;
    Serial.println("button pushed");
  } else if (buttonState == LOW && buttonPushed == true){
   buttonPushed = false;
   Serial.println('deactivate');
  }

  if (buttonPushed == true){
   digitalWrite(ledPin, HIGH);
  } else {
   digitalWrite(ledPin, LOW);
  }

  if (buttonPushed && servoActivated == false && photoCellActivated == true){
    servoActivated = true;
    Serial.println("activate motor");

    for(angle = servoStartAngle; angle > servoEndAngle; angle--){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
  } else if (buttonPushed == false && servoActivated == true){ //deactivate
    for(angle = servoEndAngle; angle < servoStartAngle; angle++){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
    delay(200);
    servoActivated = false;

  }

  delay(200);
}

You may find that, with a high load on batteries, it's depleting the battery quickly; batteries often recover after a while, which may be confusing things further. Try using a multimeter to measure the voltage on the battery, when your program is running.

The Arduino (actually, the chip that runs the Arduino) has brown-out detection - if the voltage drops below a certain level, the Arduino will shut down; if the power comes back up, the Arduino will start up again - but reset. The chip has settings for 1.8v, 2.7v, and 4.3v brownout detection (or none at all!); something I read on the interweb (if you can trust that) said the default was 4.3v. It may be worth flashing an led on startup, so you can tell when the chip is reset.

Also, if you are powering the Arduino through the voltage regulator (using the power socket on the Arduino), then you need about 6-7 volt in just to get 5 volt at the Arduino - this causes further power loss. If using 4 AA batteries through the voltage regulator, you will get 6 volts (probably a little more when the batteries are fresh) going into the regulator - barely or not quite enough! - and the voltage on the Arduino is likely to be below the 5v it needs. Any load (in one of my projects, two large 7-segment displays) can cause the voltage to drop enough to trigger a reset. If you are using the voltage regulator, check the voltage between the 5V and GND pins.


Getting wrong value from Serial.read() I have an RGB LED, connected to my UNO R3 and would like to turn on the written color in the serial by following a table (1 for red, 2 for blue, 3 for green...) and I also want to make that if this LED is already turnt ON, I want it to turn OFF. The problem I have is that when I use Serial.read() it always returns a -1 value. Why is that?
I leave you the code here and in case you see something wrong please tell me. Thank you very much.

#define RED 7
#define GREEN 4
#define BLUE 2
  String ledcolour[] = {"RED", "BLUE", "GREEN", "YELLOW", "PURPLE", "WHITE"}; //array to match the number typed to the LED colour
  char ledstatus[] = {0, 0, 0, 0, 0, 0}; //0 if the LED is OFF and 1 if it's ON
  String ledvaluefix[] = {"HIGH", "LOW"}; //if the ledstatus[] value is 0 it will write HIGH and if it's already ON it will write LOW
  char ledstatusfix[] = {1,0}; //to update in ledstatus[] if the LED is ON or OFF
  int led = Serial.read();
void setup() {
  pinMode(RED,OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE,OUTPUT);
  Serial.begin(9600);
  Serial.println("Type the LED's colour you want to turn on following this table:");
  Serial.println("RED=1");
  Serial.println("BLUE=2");
  Serial.println("GREEN=3");
  Serial.println("YELLOW=4");
  Serial.println("PURPLE=5");
  Serial.println("WHITE=6");
}

void loop() {
  if (Serial.available()){
    Serial.println(led);
    loop();
   if (led <= 6 && led >=1){ //Checks if value is within 0-6
    if (led <=3){ //Classifies in primary or mixed colours (understand primary as just having to turn ON one single LED)
      if (ledstatus[led-1] == 0){//checks if the LED was OFF
        digitalWrite(led-1,HIGH);//turns the typed LED to HIGH
        char ledstatus[led-1] = {1};//updates the array to set the LED is now ON
        confirmer();//sends a serial confirmation message
      }else{//if it was already ON
        digitalWrite(led-1,LOW);//turns the typed LED to LOW
        char ledstatus[led-1] = {0};//updates the array to set the LED is now OFF
      }
    }else{//if it's not a primary colour
      Serial.println("YOU CHOSE " + ledcolour[led-1] + ", WHICH IS A MIXED COLOUR");
    }
    }else{//if the value is not valid (not between 0 and 6)
      Serial.println("SORRY, THE INTRODUCED VALUE IS NOT VALID");
      Serial.println("PLEASE, TRY AGAIN");
    }
  }
}
 int confirmer(){
    Serial.println("YOU CHOSE THE " + ledcolour[led-1] + " LED");//sends the serial message confirming it's been turned ON
   }

This

 int led = Serial.read();

is execute before setup() and loop(), just one time. All initializations outside any function are execute before the start of the program. You have not execute Serial.begin yet.

You probably want to read inside the loop ...

Edit:

Second problem: you are calling loop recursively

void loop()
{
    if(Serial.available()) {
        Serial.println(led);
        loop();

When a byte in available in the serial port, you will call loop. As you never read the serial port, Serial.available will still return > 0, and you will enter in a never ending recursion.


Send data from one NodeMCU to another NodeMCU using Serial Communication i am using NodeMCU (ESP8266) to communicate with another NodeMCU (ESP8266) using Serial Communication. Because i am using ESP-NOW to communicate and ESP-NOW and WiFi can not work together very well so trying with this serial communication option.
Here is how i connected the pins:
   Slave ->   Master
    D1    ->   D2
    D2    ->   D1
    GND   ->   GND

Here is how my sketch looks like:
Sender.ino
#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(D1, D2); /* join i2c bus with SDA=D1 and SCL=D2 of NodeMCU */
}

void loop() {
  // put your main code here, to run repeatedly:
   Wire.beginTransmission(5); /* begin with device address 8 */
   Wire.write("Hello ESP 2");  /* sends hello string */
   Wire.endTransmission();    /* stop transmitting */

   Wire.requestFrom(5, 4); /* request & read data of size 13 from slave */
   while(Wire.available()){
      char c = Wire.read();
    Serial.print(c);
   }
   Serial.println();
   delay(1000);
}

Receiver.ino
#include <Wire.h>

void setup() {
 Wire.begin(5);
 Wire.onReceive(receiveEvent); /* register receive event */
 Serial.begin(115200);           /* start serial for debug */
}

void loop() {
 delay(100);
}

// function that executes whenever data is received from master
void receiveEvent(int howMany) {
 while (0 <Wire.available()) {
    char c = Wire.read();      /* receive byte as a character */
    Serial.print(c);           /* print the character */
  }
 Serial.println();             /* to newline */
}

But the communication is not working at all, not sure where i am wrong. It can code wise or may be via connection wise or it might be possible that NodeMCU to NodeMCU connection is not possible at all!
Thank you!

As already stated, your code uses the I2C interface (via the Wire library) and not the Serial interface (which is an Arduino term for UART). They work fundamentally different.
As you only communicate between 2 devices, which you both can program yourself. I would ditch the I2C interface. It doesn't give you any advantage here, but some disadvantages (for example, that you can't have real bidirectional communication, as the slave cannot do anything by its own, only, if the master asks for it).
Instead you should use a Serial (UART) interface. As the NodeMCU only has 1 full hardware Serial interface, which you already use for debugging, you could use the ESPSoftwareSerial library to create an extra Serial interface via software. It has limitations (in how many interfaces can listen at a time and how fast the communication can go), but most likely this will solve your problem. Also Serial is easier for beginners, than I2C.


Servo motor (HSR-1425R) not running continuously I'm trying to programme a servo motor to reach certain positions. I have a 360 degrees servo motor, so I can not use the Servo library and I can only control the speed. Therefore I want to regulate the time for the pulse. The setup is simple, 5 V, GND and pin 9 from the Arduino to the motor.

int servo1 = 9;

void setup{
    Serial.begin(9600);
    pinMode(servo1, OUTPUT);
}
void loop{
    digitalWrite(servo1, HIGH);
    delay(5000);
    Serial.println(digitalRead(servo1));
    digitalWrite(servo1, LOW);
    delay(5000);
    Serial.println(digitalRead(servo1));
}

Expected:
I expect the code to run the servo motor at full speed for 5 seconds.

Actual:
The motor runs at the first impulse and pauses for 10 seconds.

How can I improve the code to do what I expect?

Look at how servo motors are typically controlled. As far as I know there are no servos that can just be "enabled to rotate" like you seem to expect.
Usually a servo's position is set by applying a pulse of a specific length. This means you can apply a PWM signal with proper frequency. Then the duty cycle should be proportional to the servos position. From my experience timing is quite critical when controlling a servo, so going the way you do (timing a gpio's output state with delay()s) will not work well. You have to use the atmega's hardware modules (which already is the case when using the arduinos digital write) to achieve adequate timing.


Programmed device causes issues between computer and ISP I'm using a Digispark, which is basically an attiny85 packaged with a few other things, as an ISP to program attiny85's. The Digispark is loaded with Littlewire and recognized as an USBtinySPI device on the computer. The target attiny85 to be programmed is stacked on top of the Digispark. All pins are connected 1-to-1, 2-to-2, etc. Programming is done from the Arduino IDE. The tutorial I followed can be found here...

http://digistump.com/wiki/digispark/tutorials/programming

The Digispark uses port 3 (USB-) and port 4 (USB+) to communicate with the computer. There are series resistors and shunt zener diodes on both USB connections. The Digispark schematic can be seen here...

https://s3.amazonaws.com/digispark/DigisparkSchematicFinal.pdf

I have been happily programming attiny85's with this setup, but recently hit a snag. On the target chip, if port 3 or 4 produce an output, the computer will no longer recognize the programmer. The computer will immediately connect to the programmer once the target chip is removed from it's socket. The target chip must be messing up communication between the computer and the programmer.

Curious if I was missing something, I compared my setup with Sparkfun's Tiny AVR Programmer. It seems like a more robust programmer. I thought it might have extra components or something, but it's almost identical. It uses an attiny84 with pins directly connected to an attiny85.

After lots of random guesses, I added series 2.2kohm resistors on ports 3 and 4 between the target attiny85 and the programmer. This solves the problem, but seems like a workaround.

Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?

With  the Tiny AVR programmer, the D+ and D- lines are connected to there own input pins on the ATtiny84, see below:

This means that the pins from the target chip do not interfere with the function of these.

Whereas the digistump board has the outputs of the USB connected to pin 3 and 4, these pins are also connected to pin 3 and 4 of the target, as you know,

This means that as soon as you have your outputs active on 3 and 4 these interrupt the function of the USB lines.

By adding the 2.2k you are increasing the resistance before the Zener regulator circuit(thus decreasing the effect of the voltage from the target on these lines) and allowing the main tiny to have 'control' over the bus lines.

This is actual done on the SPI buses as well when a ISP is programming a target, while the target has other SPI chips on the bus, you add series resistors on the SPI bus, as seen below:

The R is usually between 1k - 4k7ohm. So you method is not a workaround, but normal procedure.

Another method to use instead of the resistor would be to cut the traces on the target board for pins 3 and 4, thus preventing it from going back onto the USB line. This is as I see no need to have control over the USB lines from the target.

  Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?

The programmer only toggles reset when programming, and once the target is flashed with your firmware that uses the same lines as USB and the PC then does not recognize the programmer because of this, the programmer won't be able to issue a RESET to the target, as

the PC can't issue it,
the programmer won't know to do that on its own.


Accessing a C++ static variable from gcc inline asm For some reason I want to mix a bit of assembly with C++ (not C).
To allow the code to be compilable using the standard Arduino IDE, I don't want to use direct assembly source.
I don't want to use a wrapper C file either.
My problem is as follows:
I have a class with a single instance (implementing some kind of driver) that looks like this:
class cDriver {
public:
    char ISR_param;
    // ...
};

cDriver Driver;

If I want to access the ISR_param of this single instance from within an ISR, I can do something like:
ISR (TIMER2_COMPA_Vect) {
    do_something_with (Driver.ISR_param);
}

This works like a charm: the address of Driver.ISR_param beign a constant, the compiler simply generates an lds r24, &Driver.ISR_param instruction to load the proper byte as a parameter for do_something_with.
Now when I try to replicate the same mechanism with inline assembler, things get a lot more complicated.
The address of Driver.ISR_param is only known to the C++ compiler as an mangled label, and I can't find a way to pass it to the inline assembler to generate the equivalent lds r24, <&Driver.ISR_param>.
trying to remane the variable
The renaming of variables for assembly like so:
char global_var asm("my_var");

and an attempt to use it like so:
asm ("lds r24, my_var\n");

will compile, but produce a linker error (my_var is undefined).
Looking at the object symbol table, the only label for global_var is a C++-like mangled name.
However hard I tried this renaming trick, I could not bring the compiler to generate a my_var label.
trying to use asm constraints
A constraint like
asm (lds r24, %0\n" : : "I"(&global_var));

will simply not compile. I scoured the possible parameter types and could not find a way to let the assembler know about this bloody address.
a terribly awkward workaround
The only way I found to make the compiler generate this dreaded lds r24,... instruction is to perform an actual function call.
So you can do something like:
__attribute__((always_inline)) give_me_my_friggin_variable(char data)
{
    asm volatile ("cmp  %0,%0\n"::"r"(data));
}

ISR (TIMER2_COMPA_Vect, ISR_NAKED) {

    <some prologue to save SREG and all needed registers>

    //...

    give_me_my_friggin_variable(Driver.ISR_param);

    // continue assembly code with r24 properly initialized
}

That will generate:
    lds r24, <the proper address> // added by the compiler...
    cmp r24,r24                   // ...because of the register constraint here

Well, that sort of works, but at the cost of generating a totally useless instruction.
so my question is...
Is there a simpler way to let the assembler know about addresses of C++ static variables?

Try this:

asm volatile("lds r24, %0" : : "i" (&Driver.ISR_param));

The "i" constraint means you provide an integer constant. It can be
any integer, unlike the uppercase "I" constraint which is limited to
6-bit positive integers.

Addendum:
The constraints supported by gcc are listed in the gcc documentation,
section Constraints for asm Operands:

The "i" constraint is listed in the subsection “Simple Constraints”
and is described as:

  An immediate integer operand (one with constant value) is allowed.
  This includes symbolic constants whose values will be known only at
  assembly time or later.

The "I" constraint is in the subsection “Machine Constraints” and,
for the AVR architecture, is defined as

  Constant greater than -1, less than 64.


Modbus RTU controller monitoring with arduino and RS485 module I'm a medium user in Arduino. I baught a pHmeter controller with RS485 output (MODBUS RTU protocol).
I want to get pH value read by the controller over RS485 module and Arduino.
According the controller's manufacturer, we should operate as bellow:
Sent by computer : 00 03 00 00 00 01 85 DB
Return from controller : 00 03 02 02 AE 05 58.

#include SoftwareSerial.h

#define SSerialRX        10  //Serial Receive pin
#define SSerialTX        11  //Serial Transmit pin
#define SSerialTxControl 3   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW
#define Pin13LED         13

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;

void setup()
{
  // Start the built-in serial port, probably to Serial Monitor
  Serial.begin(9600);
  Serial.println("SerialRemote");  // Can be ignored

  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);

  digitalWrite(SSerialTxControl, RS485Receive);  // Init Transceiver

  RS485Serial.begin(9600);
  delay(2000);
  digitalWrite(SSerialTxControl, RS485Transmit);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x03);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x01);
   RS485Serial.write((byte)0x85);
   RS485Serial.write((byte)0xDB);
   Serial.println(" ");

   digitalWrite(Pin13LED, LOW);
   delay(10);
   digitalWrite(SSerialTxControl, RS485Receive);

}
void loop()
{

  if (RS485Serial.available())
  {
    byteSend = RS485Serial.read();   // Read the byte
    Serial.print(byteSend, HEX);
    Serial.print(" ");
  }
}

I tried this following sketch who does not work.
I would like to know if it is the good way to send request to the controller?

To send series of bytes over Serial or any other Stream (Print) implementation use the "write buffer" method size_t write(const uint8_t *buffer, size_t size)

For the case in question:

byte request[] = {0, 0x03, 0, 0, 0, 0x01, 0x85, 0xDB};
RS485Serial.write(request, sizeof(request));

If someone is curios about the Modbus RTU request bytes. They are:

station address
function - 0x03 Read Multiple Holding Registers
register address - 2 bytes
number of registers to read - 2 bytes
checksum - 2 bytes

The response:

station address return
function or error code
data length
data - length bytes
checksum - 2 bytes


8 digit 7 segment display issues I've been trying to follow a few tutorials on how to get the 7 segment to display simple output but none seem to work 100%.

It starts out fine. It increments the number across the screen and then writes 8s to all of them and then reverses. After a few loops however it starts to act weird. Here's a video link where it acts a bit weird (a few digits don't write correctly and fix themselves) and then at the end, it only displays half of the 8 digit display before it goes to 8s and crashes. https://youtu.be/LD_C7I_bGyc

Here's the code:

//We always have to include the library
#include "LedControl.h"

// pin 4 is connected to the DIN pin
// pin 2 is connected to the CLK pin
// pin 3 is connected to the CS pin
// 1 as we are only using 1 MAX7219
LedControl lc = LedControl(4, 2, 3, 1);

void setup(){
    // the zero refers to the MAX7219 number, it is zero for 1 chip
    lc.shutdown(0, false);// turn off power saving, enables display
    lc.setIntensity(0, 0);// sets brightness (0~15 possible values)
    lc.clearDisplay(0);// clear screen
}

void loop(){
    // numbers 7 to 0
    for (int a = 0; a < 8; a++){
        lc.setDigit(0, a, a, false);
        delay(100);
    }
    delay(1000);
    // display number 8 on all segments
    for (int a = 0; a < 8; a++){
        lc.setDigit(0, a, 8, false);
        delay(100);
    }
    delay(1000);

    for (int a = 8; a >= 0; a--){
        lc.setDigit(0, a, a, false);
        delay(100);
    }
}

Hardware:
   Arduino Uno: https://www.jaycar.com.au/duinotech-uno-r3-development-board/p/XC4410
   8 digit display: https://www.jaycar.com.au/8-digit-7-segment-display-module/p/XC3714

At this stage it's hard to tell if it's a hardware issue or if it's setup related. If someone could please give me some insight or maybe run it if they have the same hardware that would be fantastic.

Thanks!

The last loop exceeds the limits of 8 Digits. You iterate 9 times (0-8).

   for (int a = 7; a >= 0; a--){
        lc.setDigit(0, a, a, false);
        delay(100);
    }


SoftwareSerial Struggles Just trying to understand and use the SoftwareSerial

I want to connect a WiFi Module (ESP8266)
If I send an AT command to the module I would like to print a response on my pc screen in the serial monitor

Some example code it tried

   SoftwareSerial dbgSerial(10, 11); // RX, TX
   void setup()
   {
     // Open serial communications and wait for port to open:
     Serial.begin(57600);
     Serial.setTimeout(5000);
     dbgSerial.begin(9600); //can't be faster than 19200 for softserial
     dbgSerial.println("ESP8266 Demo");
     //test if the module is ready
     Serial.println("AT+RST");
     delay(1000);
     if(Serial.find("ready"))
     {
       dbgSerial.println("Module is ready");

I would like to receive ready in the serial

Looks like you are swapping the use of Serial and dbgSerial. I think you mean to use Serial to print to the computer and dbgSerial to communicate with your module. Serial.println should display the message in the terminal on your computer.


Alternative to UART/I2C LCD displays? I'm building a MIDI synthesizer on Arduino Uno, and am considering user interface options.

I see on Adafruit and Sparkfun there are 16x2 LCD panels available that interface via I2C serial or by UART, but I think neither of those will work in my application:

The UART is clocked at 31250 baud to receive MIDI, and that's not a supported baud rate for these LCD devices;
I'm producing audio by driving an external DAC (MCP4725) over full-speed I2C; any transmission to another device would audibly jitter the DAC output;
SoftwareSerial would get around the UART clocking problem, but I believe it would stall the main loop while driving the output.

One option might be to roll my own software serial routine, carefully clocking it on the main loop, which (I believe) reliably runs at either 14.8KHz or 22.2KHz depending on the DAC protocol in use. I could set a SparkFun SerLCD into a slow data rate (2400 baud) and count passes through the main loop to time the data output.

Another option would be to use a secondary MCU -- I have a surplus Trinket M0 on hand -- and define a custom synchronous serial protocol between the two MCUs, and have the secondary relay commands to the LCD but that's getting into Rube Goldberg territory.

Any obvious options I'm overlooking?

One obvious option would be to get a display with SPI interface, since you have it available. Another option is to get a DAC running on SPI, and use the I2C for the display.

If you insist on using one of these 16x2 LCDs, there are SPI adapters for them as well. Example