body:
Is it possible to turn on the SIM808 module from code? There is a button in the SIM808 board to activate the module, but I need to turn it on from the code automatically. This is because my device will be stored hidden inside a vehicle so I do not have to keep turn on and off by hand.

[This][1] is the model.

  [1]: https://www.banggood.com/SIM808-Module-GSM-GPRS-GPS-SMS-Development-Board-IPX-SMA-with-Antenna-p-1062818.html

title: Mega + SIM808 GPRS GSM GPS IPX-SMA module power on from code

Answers: 1

body:
Looking at the pictures it looks like it should be possible to take the two exposed connections of the switch and add flying leads to them and run them back to the microprocessor to allow it to turn them on and off.  The possible problem is the current that has to run through the switch.

You will need to investigate, but it looks like it could be done like that if you can't find a better solution.


body:
I've been trying to implement this old code that randomly transitions to RGB color into my Arduino board that uses FastLED.

    Static Col1, Col2, Col3 As Integer
    Static C1, C2, C3 As Integer
    If (Col1 = 0 Or Col1 = 250) And (Col2 = 0 Or Col2 = 250) And (Col3 = 0 Or Col3 = 250) Then
      C1 = Int(Rnd * 3)
      C2 = Int(Rnd * 3)
      C3 = Int(Rnd * 3)
    End If
    If C1 = 1 And Col1 <> 0 Then Col1 = Col1 - 10
    If C2 = 1 And Col2 <> 0 Then Col2 = Col2 - 10
    If C3 = 1 And Col3 <> 0 Then Col3 = Col3 - 10
    If C1 = 2 And Col1 <> 250 Then Col1 = Col1 + 10
    If C2 = 2 And Col2 <> 250 Then Col2 = Col2 + 10
    If C3 = 2 And Col3 <> 250 Then Col3 = Col3 + 10
    leds[x] = RGB(Col1, Col2, Col3)

Here is my Arduino setup:

    #include <FastLED.h>

    #define LED_COUNT 60
    #define LED_OUT       13
    #define BUTTON_IN     10
    #define ANALOG_INPUT  A9
    #define EXTRA_PIN_A    7
    #define EXTRA_PIN_B   11

    struct CRGB leds[LED_COUNT];

    void setup() {
      Serial.begin(57600);
      LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
      LEDS.show();
    }

    void loop() {
      //where to implement
    }

title: How to add this old BASIC code snippet to work in Arduino C++ for FastLED?

Answers: 2

body:
Fairly simple. Understand what the basic code is trying to do and recreate that functionality in c.

In this case, it is looking for a set of conditions to trigger the generation of three random numbers which are then combined into a code for the run array.

body:
I think this should work fine:

    #include <FastLED.h>

    #define LED_COUNT     96
    #define LED_OUT       13
    #define BUTTON_IN     10
    #define ANALOG_INPUT  A9
    #define EXTRA_PIN_A    7
    #define EXTRA_PIN_B   11

    struct CRGB leds[LED_COUNT];

    void setup() {
      Serial.begin(57600);
      LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
      LEDS.show();
    }

    void colorLoop() {

      static int Col1;
      static int Col2;
      static int Col3;

      static int C1;
      static int C2;
      static int C3;

    if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

    // select a random number from 1 to 2 for the array
    C1 = random(1, 3);
    C2 = random(1, 3);
    C3 = random(1, 3);
    }

    if (((C1 == 1) && (Col1 != 0))) {
        Col1 = (Col1 - 10);
    }
    if (((C2 == 1) && (Col2 != 0))) {
        Col2 = (Col2 - 10);
    }
    if (((C3 == 1) && (Col3 != 0))) {
        Col3 = (Col3 - 10);
    }

    if (((C1 == 2) && (Col1 != 250))) {
        Col1 = (Col1 + 10);
    }
    if (((C2 == 2) && (Col2 != 250))) {
        Col2 = (Col2 + 10);
    }
    if (((C3 == 2) && (Col3 != 250))) {
        Col3 = (Col3 + 10);
    }

    for (uint8_t i = 0; i < LED_COUNT; i++) {
       leds[i] = CRGB(Col1, Col2, Col3);
      }
    delay(100);
    LEDS.show();
    }

    void loop() {
      colorLoop();
    }


body:
so I have an arduino micro, and it was working fine until the latest security update for OSX 10.11.6 now the port won't show up in the arduino IDE. This doesn't seem to be a problem with the Uno / Huzzah / Mega or Makey Makey, but the port shows up when the micro is booting up, then disappears when the boot is done.

Anyone else having this issue? I've googled and found something about signed ktels. I've also installed some extra FTDI drivers, but no dice. Cord is fine, and works w/ other devices.

Suggestions?

Thanks!

title: Arduino Micro disappears on osX 10.11.6

Answers: 1

body: Found it. It was a weird timing thing, and I had to hit reset as the sketch was uploading. Seems to be fine now.


body:
This may be a very simple problem but it has had me going round and round in circles, it is VERY similar to this [ <https://arduino.stackexchange.com/questions/28328/problem-with-wrapping-adafruit-motor-controller-function-calls-in-a-class>] question but try as I might I couldn't resolve the issue using this example. So I will include my code and hope that someone with more experience takes pity on me.
This code compiles with no errors but the motors don't start Like the linked question it all worked before it was separated into the individual files.

robot.ino:

    #include "E:\chhs2017\LegoRobotics\SketchesThatNeedToWork\RobotBase\RobotBase.h"

    RobotBase *base;

    void setup(){
  base = new RobotBase();
    }

    void loop(){
  base->moveRobotForward(base->HALF_SPEED);
    //  base->stopRobotAfter(1500);
    }

RobotBase.h:

    #ifndef ROBOTBASE_H
    #define ROBOTBASE_H

    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_MS_PWMServoDriver.h"

 class RobotBase{

  public:
   const int MAX_SPEED = 255;
   const int THREE_QUARTER_SPEED = 190;
   const int HALF_SPEED = 127;
   const int QUARTER_SPEED = 90;
   const int MIN_SPEED = 30;

   RobotBase();

   void moveRobotForward(int inSpeed);
   void moveRobotBackward(int inSpeed);
   void moveRobotLeft(int inSpeed);
   void moveRobotRight(int inSpeed);
   void rotateRobotRight(int inSpeed);
   void rotateRobotLeft(int inSpeed);
   void stopRobotAfter(int time);

  protected:
   Adafruit_MotorShield AFMS;
   Adafruit_DCMotor *myMotorM1;
   Adafruit_DCMotor *myMotorM2;
   Adafruit_DCMotor *myMotorM3;
   Adafruit_DCMotor *myMotorM4;
 };
    #endif

RobotBase.ino:

    /*************************************************************
    * this is the robot base control class which is designed for a
    * four wheel robot construction using an Adafruit_DCMotor controller
    * and and arduino Uno
    **************************************************************/

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_MS_PWMServoDriver.h"
    #include "E:/chhs2017/LegoRobotics/SketchesThatNeedToWork/RobotBase/RobotBase.h"

    RobotBase::RobotBase()  {
     AFMS = Adafruit_MotorShield();
     myMotorM1 = AFMS.getMotor(1);
     myMotorM2 = AFMS.getMotor(2);
     myMotorM3 = AFMS.getMotor(3);
     myMotorM4 = AFMS.getMotor(4);
    }

    void RobotBase::stopRobotAfter(int time){
    delay(time);
    myMotorM1->run(RELEASE);
    myMotorM2->run(RELEASE);
    myMotorM3->run(RELEASE);
    myMotorM4->run(RELEASE);
 }

  void RobotBase::moveRobotForward(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(FORWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(FORWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(FORWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(FORWARD);
 }

 void RobotBase::moveRobotBackward(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(BACKWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(BACKWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(BACKWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(BACKWARD);
 }

 void RobotBase::moveRobotLeft(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(FORWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(BACKWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(FORWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(BACKWARD);
 }

 void RobotBase::moveRobotRight(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(BACKWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(FORWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(BACKWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(FORWARD);
 }

    void RobotBase::rotateRobotRight(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(FORWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(FORWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(BACKWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(BACKWARD);
    }

    void RobotBase::rotateRobotLeft(int inSpeed){
  myMotorM1->setSpeed(inSpeed);
  myMotorM1->run(BACKWARD);
  myMotorM2->setSpeed(inSpeed);
  myMotorM2->run(BACKWARD);
  myMotorM3->setSpeed(inSpeed);
  myMotorM3->run(FORWARD);
  myMotorM4->setSpeed(inSpeed);
  myMotorM4->run(FORWARD);
 }

Thanks in Advance!

title: Pointer problems using Adafruit MotorController

Answers: 2

body:
It may be the way you are initializing the motor shield object.
Try doing:

    RobotBase::RobotBase() : AFMS() {
         myMotorM1 = AFMS.getMotor(1);
         myMotorM2 = AFMS.getMotor(2);
         myMotorM3 = AFMS.getMotor(3);
         myMotorM4 = AFMS.getMotor(4);
    }

body:
Hey Guy's As I suspected it was actually an easy fix after leaving it alone for a couple of days came back with fresh eyes and saw the problem straight away. I had failed to start the MotorController board. So all that was needed was the begin function call `base->AFMS.begin();` in the setup of robot.ino, all working fine now.
Thanks again for your help.


body:
The following code works. I get an output in the console every second of "Hello" and then the `analogValue` of the photoresistor.

    int greenLedPin = D1;
    int yellowLedPin = D2;
    int redLedPin = D3;

    int lightSensorPin = A0;
    int analogValue = 0;

    void setup() {
      Serial.begin(9600);
    //  pinMode(greenLedPin, OUTPUT);
    //  pinMode(yellowLedPin, OUTPUT);
    //  pinMode(redLedPin, OUTPUT);
    }

    void loop() {
      analogValue = analogRead(lightSensorPin);
      Serial.println("Hello.");
      Serial.println(analogValue);
      delay(1000);
    //  digitalWrite(greenLedPin, HIGH);
    //  digitalWrite(yellowLedPin, HIGH);
    //  digitalWrite(redLedPin, HIGH);
    }

Now as soon as I uncomment the `pinMode` commands nothing shows up on the console.

    int greenLedPin = D1;
    int yellowLedPin = D2;
    int redLedPin = D3;

    int lightSensorPin = A0;
    int analogValue = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(greenLedPin, OUTPUT);
      pinMode(yellowLedPin, OUTPUT);
      pinMode(redLedPin, OUTPUT);
    }

    void loop() {
      analogValue = analogRead(lightSensorPin);
      Serial.println("Hello.");
      Serial.println(analogValue);
      delay(1000);
    //  digitalWrite(greenLedPin, HIGH);
    //  digitalWrite(yellowLedPin, HIGH);
    //  digitalWrite(redLedPin, HIGH);
    }

Any idea what might be going on?

title: LinkNode D1 Serial stops working when using pinMode

Answers: 1

body:
Move **int greenLedPin = D1;** and **int redLedPin = D3;** to another pin, because D1 and D3 is Tx and Rx.

[![enter image description here][1]][1]

http://esp8266.github.io/Arduino/versions/2.0.0/doc/reference.html

  [1]: https://i.stack.imgur.com/HXn0i.png


body:
I am trying to control an actuator carrying a carriage made from stepper motor. My problem is that after the carriage reach certain height, I want it to delay for several minutes and change direction to move the other way around.

Any suggestion on what sensor to use? I tried to use EndStop switch like the one in 3D printer but I haven't found any luck as it simply cuts the electronic connections once the carriage hits it.

title: Sensor for turning rail direction

Answers: 1

body:
If you are using a microprocessor, specifically an Arduino, then what you need to do is send the signal from the 'switch' (as defined by Mark Smith) into a digital input port and then let the Arduino make the electronics pause before reversing.  From you post it sounds like (and I am probably wrong) you have put the switch in between the power source and the actuator.

[![enter image description here][1]][1]

(Diagram by Majenko)

  [1]: https://i.stack.imgur.com/gSZxq.png


body:
there is something wrong with this code logic and i can't put my hand on it so if any one can fix i would really appreciate it
Basically the code is used to receive couple of char from Bluetooth or serial monitor combine them together in an array then print this array then search for ":" in this array and atoi them into two different integer
IE (50:90) will be (50) and (90) in two different integer that are then used to control the direction and the speed of a motor

    //motor a
    int enA = 9;
    int in1 = 8;
    int in2 = 7;

    //motor b
    int in3 = 5;
    int in4 = 4;
    int enB = 3;
    char data[32]; // Allocate some space for the string
    char inChar; // Where to store the character read
    byte index = 0; // Index into array; where to store the character

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(enA , OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);
      pinMode(enB, OUTPUT);
      Serial.println("\n String conversion testing");
    }

    void loop() {

    if(index < 31) // One less than the size of the array
          {for( int i = 0; i < sizeof(data);  ++i )
              data[i] = (char)0;

              inChar = Serial.read(); // Read a character

              data[index] = inChar; // Store it
              index++; // Increment where to write next
              for( int i = 0; i < sizeof(data);  ++i )
              Serial.println (data);

          }
        char* command = strchr (data, ":");
        if (command !=0)
        {
          *command = 0;
          int direc = atoi (data);
          ++command;
          int speeds = atoi (command);
          Serial.println(speeds);
          Serial.println(direc);
         int s;
         s = map(speeds, 0, 100, 0, 255);
        if (direc >= 85 &&direc <=100 ){//odam
            digitalWrite(in1,HIGH);
            digitalWrite(in2,LOW);
            analogWrite(enA,s);
            digitalWrite(in3,HIGH);
            digitalWrite(in4,LOW);
            analogWrite(enB,s);
        }

          else if (direc >=260 && direc <=280){  //reverse
            digitalWrite(in1,LOW);
            digitalWrite(in2,HIGH);
            analogWrite(enA,s);
            digitalWrite(in3,LOW);
            digitalWrite(in4,HIGH);
            analogWrite(enB,s);
          }

         else if (direc >=350 && direc <=360 | direc <=10 && direc >=0){ // RIGHT
            digitalWrite(in1,HIGH);
            digitalWrite(in2,LOW);
            analogWrite(enA,s);
            digitalWrite(in3,LOW);
            digitalWrite(in4,HIGH);
            analogWrite(enB,s);
         }

          else if (direc >=170 && direc <=190){ // LEFT
            digitalWrite(in1,LOW);
            digitalWrite(in2,HIGH);
            analogWrite(enA,s);
            digitalWrite(in3,HIGH);
            digitalWrite(in4,LOW);
            analogWrite(enB,s);
          }

          else if (direc >=120 && direc <=150){ //FORWARD LEFT
            digitalWrite(in1,LOW);
            digitalWrite(in2,HIGH);
            analogWrite(enA,s);
            digitalWrite(in3,LOW);
            digitalWrite(in4,LOW);
            analogWrite(enB,s);
          }

          else if (direc >=30 && direc <=60){ // FORWARD RIGHT
            digitalWrite(in1,LOW);
            digitalWrite(in2,LOW);
            analogWrite(enA,s);
            digitalWrite(in3,LOW);
            digitalWrite(in4,HIGH);
            analogWrite(enB,s);
          }

         else if (direc >=210 && direc <=259){ // BACKWARD LEFT
            digitalWrite(in1,HIGH);
            digitalWrite(in2,LOW);
            analogWrite(enA,s);
            digitalWrite(in3,LOW);
            digitalWrite(in4,LOW);
            analogWrite(enB,s);
         }

         else if (direc >=300 && direc <=340){ // BACKWARD RIGHT
            digitalWrite(in1,LOW);
            digitalWrite(in2,LOW);
            analogWrite(enA,s);
            digitalWrite(in3,HIGH);
            digitalWrite(in4,LOW);
            analogWrite(enB,s);
         }

          else{ //If bluetooth module receives any value not listed above, both motors turn off
            digitalWrite(in1,LOW);
            digitalWrite(in2,LOW);
            analogWrite(enA,0);
            digitalWrite(in3,LOW);
            digitalWrite(in4,LOW);
            analogWrite(enB,0);
          }
        }
      }

title: can someone please fix this code

Answers: 1

body:
          inChar = Serial.read(); // Read a character

          data[index] = inChar; // Store it

The above is almost certainly not going to work as expected. You need to check if there is serial data available before reading it. (ie. call `Serial.available()`).

I have a [page about reading from serial](http://gammon.com.au/serial) that might help you with that.

For example, your loop might look like this:

    void loop()
      {
      // if serial data available, process it
      while (Serial.available () > 0)
        processIncomingByte (Serial.read ());

      // do other stuff here like testing digital input (button presses) ...

      }  // end of loop

Notice that the `Serial.read` is only done if `Serial.available` is true?


body:
[![enter image description here][1]][1]My son just did the Love-o-meter project in the Arduino Start Kit. However, the sensor readings of the LM35 temperature control vary widely. Below is a sample. What could be wrong?

    Sensor Value: 217, Volts: 1.06, degrees C: 105.96
    Sensor Value: 587, Volts: 2.87, degrees C: 286.62
    Sensor Value: 125, Volts: 0.61, degrees C: 61.04
    Sensor Value: 320, Volts: 1.56, degrees C: 156.25
    Sensor Value: 445, Volts: 2.17, degrees C: 217.29
    Sensor Value: 141, Volts: 0.69, degrees C: 68.85
    Sensor Value: 510, Volts: 2.49, degrees C: 249.02
    Sensor Value: 247, Volts: 1.21, degrees C: 120.61
    Sensor Value: 168, Volts: 0.82, degrees C: 82.03
    Sensor Value: 595, Volts: 2.91, degrees C: 290.53
    Sensor Value: 125, Volts: 0.61, degrees C: 61.04
    Sensor Value: 206, Volts: 1.01, degrees C: 100.59
    Sensor Value: 606, Volts: 2.96, degrees C: 295.90
    Sensor Value: 125, Volts: 0.61, degrees C: 61.04
    Sensor Value: 290, Volts: 1.42, degrees C: 141.60
    Sensor Value: 487, Volts: 2.38, degrees C: 237.79

Here's the code:

    const int sensorPin = A0;
    const float baselineTemp = 25.0;

    void setup(){
      Serial.begin(9600); // open a serial port
      for(int pinNumber = 2; pinNumber<5; pinNumber++){
        pinMode(pinNumber,OUTPUT);
        digitalWrite(pinNumber, LOW);
      }
    }

    void loop(){
      int sensorVal = analogRead(sensorPin);
      Serial.print("Sensor Value: ");
      Serial.print(sensorVal);
      // convert the ADC reading to voltage
      float voltage = (sensorVal/1024.0) * 5.0;
      Serial.print(", Volts: ");
      Serial.print(voltage);
      Serial.print(", degrees C: ");
      // convert the voltage to temperature in degrees
      float temperature = (voltage) * 100;
      Serial.println(temperature);

      if(temperature < baselineTemp){
        digitalWrite(1, LOW);
        digitalWrite(2, LOW);
        digitalWrite(3, LOW);
      }else if(temperature >= baselineTemp+2 &&
        temperature < baselineTemp+4){
        digitalWrite(1, HIGH);
        digitalWrite(2, LOW);
        digitalWrite(3, LOW);
      }else if(temperature >= baselineTemp+4 &&
        temperature < baselineTemp+6){
        digitalWrite(1, HIGH);
        digitalWrite(2, HIGH);
        digitalWrite(3, LOW);
      }else if(temperature >= baselineTemp+6){
        digitalWrite(1, HIGH);
        digitalWrite(2, HIGH);
        digitalWrite(3, HIGH);
      }
      delay(1);
    }

The GND is connected to the left most connector in the LM35, the A0 to the middle, and the power to the right most connector.

  [1]: https://i.stack.imgur.com/983n4.jpg

title: LM35 readings are erratic

Answers: 1

body:
I've had a look round and spotted this:

https://electronics.stackexchange.com/questions/117970/why-is-my-analog-temp-sensors-signal-so-unstable

In summary it says that the fault maybe that the Arduino's 5V isn't stable enough, so you need to decouple it.  For once it seems that running from batteries may have been a better idea.

I've also seen posts saying there should be a 500Ohm resistor between the Ground of the LM35 and Ground.  Apparently it says 499Ohm on the datasheet.

And as a final resort I saw said that the 'Data Direction Register' influenced the analog pins.  If it was set to digital output this could lead to unstable readings for the ADC.  Basically it implied you needed to set the analog pin's to `pinMode (A0, output)`. **But I really don't think this will work**


body:
I've a little problem, I'm trying to create a library with processor variables for tune it.

So in `.ino` I declared my preprocessor var, but preprocessor variables appear not defined in my library. (Notice that I've create a folder `test/test.h` in `libraries` directory of Arduino IDE)

Some code to reproduce the problem :

**test.ino** :

    #define TEST

    #include "test.h"

    void setup() {}
    void loop() {}

**test.h** (edited, reverse error message, this is solution)

    #if defined(TEST)
      #error "DEFINED"
    #else
      #error "NOT DEFINED"
    #endif

If I compile it, I fall on `#error "NOT DEFINED"`.

Somebody with an idea ?

Have a good day

title: Preprocessing problem

Answers: 2

body:
Please, start by reading the [Writing a Library for Arduino Tutorial][1]. That will solve your question.

  [1]: https://www.arduino.cc/en/Hacking/LibraryTutorial

body:
The code is working properly. You have mixed up your error messages. The code should be:
<!-- language: lang-cpp -->

    #if defined(TEST)
      #error "DEFINED"
    #else
      #error "NOT DEFINED"
    #endif

UPDATE: The question was edited after the time of this answer to correct the mixed up error messages.


body:
In Arduino Pro Mini (3.3V) [specs][1] indicated the maximal and recommended current per pin, 40mA and 20mA respectively. Does these values means *input* current (i.e. safe input current Arduino can handle) or *output* current?

  [1]: https://cdn.sparkfun.com/r/600-600/assets/learn_tutorials/1/0/4/graphicalDatasheet.png

title: Arduino Pro Mini maximal and recommended current per pin

Answers: 3

body:
In [datasheet][2], paragraph 32.1 is stated:

    DC Current per I/O Pin 40.0mA

See comments below about the implication. (I will not delete this questions because of the useful comments below from Majenko and Milliways, unless downvoted).

See:

[![fragment][1]][1]

  [1]: https://i.stack.imgur.com/iiBnR.png
  [2]: http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_datasheet.pdf

body:
It is the amount of current the pin can *source* or *sink* when in OUTPUT mode.

That is, the amount of current that can flow from the pin to ground, or can flow from VCC into the pin.

You can understand it better if you [learn how a GPIO pin works](https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/).

body:
> Does these values means input current (i.e. safe input current Arduino can handle) or output current?

Depending on your definition of input.

The numbers are the max current that an output pin can provide , either flowing in or out of the pin.

The max current you can force into or out of an input pin is mostly determined by the clamp diodes. Typical a few ma.


body: i want to upload sketch into arduino uno using usb/ttl adapter.i tried searching for it, but found about programming arduino using another. can anyone help me.

title: is it possible to program an arduino with usb/ttl adapter

Answers: 2

body:
The Uno is normally programmed by its on-board USB adapter.

The Pro Mini does not have an on-board adapter, and is normally programmed with an external USB/serial adapter. This should also be possible with Uno.

body:
The Arduino onboard USB to serial is connected to D0 (Rx) and D1 (Tx).

And without a USB connected to the Arduino you can use a USB/TTL adapter connected to D0 and D1 like this;

    Arduino  - USB/TTL
    Tx       - Rx
    Rx       - Tx

And to get the Arduino inte "programming" mode:

 - Automatic way, if the USB/TTL have CTS, connect it to Arduinos reset pin.
 - Manual way, press the reset button when the Arduino IDE starts to upload the code.


body:
I am using a [Wemos Pro ESP32 development board][1] and would like to be able to use all ten of the available capacitive touch inputs. I am able to get readings from nine of them but not T1. Here is the pin diagram for the board I have.

[![Wemos Pro ESP32 pins][2]][2]

*Running this code on my board produces no difference in reading for T1...*

    #define numTouchPins 10
    byte touchPins[] = { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9 };
    byte touch[10] = {};

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

    void loop() {
        for( byte pin = 0; pin < numTouchPins; ++ pin ) {
            touch[pin] = touchRead( touchPins[pin] );
        }
        for( byte i = 0; i < 10; ++i ) {
            Serial.print( touch[i] );
            Serial.print( "\t" );
        }
        Serial.println();
    }

So the reason for this is that T1 is on GPIO0 which is also connected to a button labeled 0 on the board. Now I realise this is needed in order to select between the ROM serial bootloader mode and the normal execution mode... But, **is there a way to change the pinmode from digital-in to touch-in once normal boot has completed?** Is there something I can write in the Arduino setup() method that would make this pin behave like the other touch pins?

  [1]: https://www.aliexpress.com/item/Wemos-pro-ESP32-WIFI-bluetooth-4MB-Flash/32810333729.html
  [2]: https://i.stack.imgur.com/tGI2F.jpg

title: Using all ten capacitive touch inputs on the ESP32

Answers: 1

body:
> is there a way to change the pinmode from digital-in to touch-in once normal boot has completed?

You already are. However it will make no difference since that pin is connected to external hardware - namely the button and a pullup resistor.

You cannot have touch inputs connected to anything else.  The only way to get the touch to work on that input is to physically remove the pullup resistor and even maybe the button. Touch inputs are "touchy" about what else is connected since even a button that's not connected to anything else can effect the capacitance on the pin.


body:
How do I burn the UNO bootloader onto ATMEGA328P-PU without using an Arduino Uno board. That is burn directly from my PC or Android device??

I've tried nothing, I don't know a thing about microcontrollers ☺

title: How to burn the bootloader onto a bare chip without using an Arduino board

Answers: 1

body:
The short answer is, you need a **AVR programmer**

It is a tutorial on the Arduino website:

https://www.arduino.cc/en/Main/Standalone

And the section *Bootloading your chips OPTIONAL* will answer the question.


body:
I have just added the ESP32 toolchain to the Arduino IDE (v1.8.0) on Windows 10.  To get the IDE to allow me to select ESP32 chips I had to place the Espressif folder in "D:\Program Files(x86)\Arduino\hardware" (Yes my C drive is called D, its a long story)

I managed to compile and run Blink and after several minutes of celebration I tried the ESP32 Example Wifi->WifiScan.  It failed to compile because

    WARNING: Category '' in library OneWire is not valid. Setting to 'Uncategorized'
    In file included from D:\Program Files (x86)\Arduino\libraries\WiFi\src\utility\spi_drv.cpp:21:0:

    D:\Program Files (x86)\Arduino\libraries\SPI/SPI.h:16:26: fatal error: avr/pgmspace.h: No such file or directory

    compilation terminated.

    Multiple libraries were found for "WiFi.h"
     Used: D:\Program Files (x86)\Arduino\libraries\WiFi
     Not used: D:\Program Files (x86)\Arduino\hardware\espressif\ESP32\libraries\WiFi
    Multiple libraries were found for "SPI.h"
     Used: D:\Program Files (x86)\Arduino\libraries\SPI
     Not used: D:\Program Files (x86)\Arduino\hardware\espressif\ESP32\libraries\SPI
    exit status 1
    Error compiling for board ESP32 Dev Module.

If I am reading this correctly, there are a couple of duplicate libraries, Arduino versions and ESP32 versions and the IDE picked the Arduino versions.

Is there a way of telling the IDE to prefer the ESP32 libraries rather than Arduino ones?  I suspect all I need to do is change the order of the -I and -L commands, but I don't have a clue how, or if that's the right thing to do.

title: Duplicate libraries while compiling for ESP32 in the Arduino IDE

Answers: 2

body:
`#include "filename.h"` will look in the sketch folder

`#include <filename.h>` will look in the path, defined in *File* | *Preferences*, edit **preferences.txt**, search for sketchbook.path

body:
The problem is that you have incorrectly installed the ESP32 hardware package. If you look at the official installation instructions:

https://github.com/espressif/arduino-esp32/blob/master/README.md#installation-instructions

you'll see that the architecture folder should be named **esp32**, not **ESP32** as you have named your folder.

When multiple libraries contain a header file of the same name, one of the factors the Arduino IDE uses to decide which gets precedence is architecture matching. The architecture of the selected board is determined by the name of the architecture folder of the hardware package of that board. So because you named your architecture folder **ESP32**, that's the architecture value of the selected board. The architecture of the library is determined by the `architectures` property value found in the library.properties file of the library. In this case that value is [set to](https://github.com/espressif/arduino-esp32/blob/41e36a72f309fbfa5e2bdeebdca93661728bddb3/libraries/SPI/library.properties#L9) `esp32`:

    architectures=esp32

So because the architecture value of the library in the ESP32 hardware package doesn't match the architecture of the selected board, the SPI library found in the Arduino IDE installation folder is used instead.

If you rename the architecture folder to **esp32** the correct library will be used.

A few other notes:

For some reason you have put a copy of the SPI library at D:\Program Files (x86)\Arduino\libraries\SPI. This makes no sense because that library is architecture specific. Each hardware package has its own version of the SPI library bundled.

In addition to using the incorrect architecture folder name in your installation of the ESP32 hardware package, you installed it to the Arduino IDE installation folder instead of the sketchbook folder, as recommended in the instructions.

You seem to have a bad habit of messing with your Arduino IDE installation folder. You should never modify or add files to the Arduino IDE installation folder. The reason is that all changes you make to that location will be lost anytime you upgrade to a new version of the Arduino IDE and it also makes troubleshooting more difficult since you are working with a non-standard installation. Instead you should always install libraries and hardware packages to the sketchbook folder where they will persist through IDE updates. I recommend you to move any customized files out of the Arduino IDE installation folder and then reinstall the IDE to make sure you are working with a stock installation.


body:
I've got an Arduino Uno and Ethernet shield, trying to test it out with a simple on off switch for the on-board LED.

My Code is this

    // FILENAME = LED2.ino
    // SOURCE= http://www.instructables.com/id/Control-an-LED-over-the-internet-using-the-Arduino/
    // Control an LED over the internet using the Arduino Ethernet Shield and Transistor
    // http://www.instructables.com/id/Control-an-LED-over-the-internet-using-the-Arduino/
    // code SOURCE= http://pastebin.com/CZ6J62qJ

    #include <SPI.h>
    #include <Ethernet.h>

    #include <Servo.h>
    Servo myservo; // create servo object to control a servo

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
    byte ip[] = { 192, 168, 1, 177 }; // fixed IP addr in LAN
    byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
    byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
    EthernetServer server(80); //server port

    String readString;
    //////////////////////
    void setup()
    {
        pinMode(6, OUTPUT); //pin selected to control LED
        pinMode(13, OUTPUT);
        //start Ethernet
        Ethernet.begin(mac, ip, gateway, subnet);
        server.begin();
        //the pin for the servo co
        //enable serial data print
        Serial.begin(9600);
        Serial.println("server LED test 1.0 ---- FILENAME = LED2.ino "); // so I can keep track
    }

    void loop()
    {
        // Create a client connection
        EthernetClient client = server.available();
        if (client) {
            while (client.connected()) {
                if (client.available()) {
                    char c = client.read();

                    //read char by char HTTP request
                    if (readString.length() < 100) {

                        //store characters to string
                        readString += c;
                        //Serial.print(c);
                    }

                    //if HTTP request has ended
                    if (c == '\n') {

                        ///////////////
                        Serial.println(readString); //print to serial monitor for debuging
                        client.println("HTTP/1.1 200 OK"); //send new page
                        client.println("Content-Type: text/html");
                        client.println();
                        client.println("");
                        client.println("");
                        client.println("<TITLE>Home Automation</TITLE>");
                        client.println("");
                        client.println("");
                        client.println("
Home Automation
");
                        client.println("
");
                        client.println("
");

                        client.println("Turn On Light");
                        client.println("Turn Off Light
");

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

                        delay(1);
                        //stopping client
                        client.stop();

                        ///////////////////// control arduino pin
                        if (readString.indexOf("?lighton") > 0) //checks for on
                        {
                            digitalWrite(13, HIGH); // set pin 6 high
                            Serial.println("LED On");
                        }
                        else {
                            if (readString.indexOf("?lightoff") > 0) //checks for off
                            {
                                digitalWrite(13, LOW); // set pin 6 low
                                Serial.println("LED Off");
                            }
                        }
                        readString = ""; //clearing string for next read
                    }
                }
            }
        }
    }

The problem is that when I click a button (either on or off)  the LED will blink twice, and then remain off.

My serial monitor also shows 2 HTTP requests, I'm not sure if this is usual or not?

    server LED test 1.0 ---- FILENAME = LED2.ino
    GET /?lighton HTTP/1.1

    LED On
    GET /favicon.ico HTTP/1.1

    GET /?lighton HTTP/1.1

    LED On
    GET /?lighton HTTP/1.1

    LED On
    GET /favicon.ico HTTP/1.1

    GET /?lighton HTTP/1.1

    LED On
    GET /favicon.ico HTTP/1.1

    GET /?lightoff HTTP/1.1

    LED Off
    GET /favicon.ico HTTP/1.1

Would appreciate any help!

title: LED Webserver control not working

Answers: 0


body:
I'm having trouble explaining my issue. What I'm doing is creating a library to work easily with the RFID reader/writer RC522 module. I need to create an object of the library MFRC522 in my .cpp file to be able to communticate with the module itself. I want my constructor end up like this:`UltimateRFID rfid(53, 5);`, the parameters being the slave select and the reset pins, respectively.
The problem is that I don't know how to make my constructor so that it is within the scope of the functions that require the MFRC522 object to be called. Below's my code.

    #include "Arduino.h"
    #include "UltimateRFID.h"
    #include <MFRC522.h>

    MFRC522::MIFARE_Key key;

    UltimateRFID::UltimateRFID(int ss, int rst)
    {
       MFRC522 mfrc522(ss, rst); //this would be ideal, but how can my functions access the instance?
    }

    void UltimateRFID::initialize() //sample of a function that uses the MFRC522 object
    {
      //digitalWrite(49, HIGH);
      digitalWrite(2, LOW);
      for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
      }
      mfrc522.PCD_Init();
      if ( ! mfrc522.PICC_IsNewCardPresent())
      {
        return;
      }
      if ( ! mfrc522.PICC_ReadCardSerial())
      {
        return;
      }

    }

Now comes my header file, although I'm not sure it matters much.

    #ifndef UltimateRFID_h
    #define UltimateRFID_h

    #include "Arduino.h"
    #include <MFRC522.h>

    class UltimateRFID
    {
      public:
        UltimateRFID(int ss, int rst);
        void initialize();
      private:
        MFRC522::MIFARE_Key key;
    };

    #endif
Please be patient, it's my first library.

title: How can my library source code instantiate an object from another library?

Answers: 3

body:
    UltimateRFID::UltimateRFID(int ss, int rst)
    {
       MFRC522 mfrc522(ss, rst); //this would be ideal, but how can my functions access the instance?
    }

As you note, that instance would go out of scope immediately. The simplest thing would be to put a **pointer** to the other class in your class definition. Then in your `init` function do a `new` to create the instance of the class, passing the appropriate parameters.

body:
Why not have your class just extend the MFRC522 class?

    #include <MFRC522.h>

    class UltimateRFID : public MFRC522 {
        private:
            MIFARE_Key key;

        public:
            UltimateRFID(uint8_t ss, uint8_t rst) : MFRC522(ss, rst) {}
            // your other methods
            void initialize();
    };

    void UltimateRFID::initialize() {
        //digitalWrite(49, HIGH);
        digitalWrite(2, LOW);
        for (byte i = 0; i < 6; i++) {
            key.keyByte[i] = 0xFF;
        }
        PCD_Init();
        if ( ! PICC_IsNewCardPresent()) {
            return;
        }
        if ( ! PICC_ReadCardSerial()) {
            return;
        }
    }

    UltimateRFID rfid(53, 5);

    void setup() {
        rfid.initialize();
    }

    void loop() {}

Your class then becomes a "flavour" of MFRC522 with additional functionality. It can access all the public functions of the MFRC522 class, since they are now a part of your class.

Anything you can do with an MFRC522 object you can now do with your object. As well as your extra functions.

body:
While @Majenko's answer is probably best (I +1'd it), for completeness, here's how to construct a member variable with parameters:

    class UltimateRFID {
        public:
        UltimateRFID(int ss, int rst) : mfrc522(ss, rst) {}

        protected:
        MFRC522 mfrc522;
    };

"placement new" is another option:

    class UltimateRFID {
        public:
        UltimateRFID(int ss, int rst) {
            new (&mfrc522) MFRC522(ss, rst)
        }

        protected:
        MFRC522 mfrc522;
    };

However, this method calls the default ctor - which may or may not be an issue. This is usually reserved for re-initializing an existing object.

There's also assignment:

    class UltimateRFID {
        public:
        UltimateRFID(int ss, int rst) {
            mfrc522 = MFRC522(ss, rst)
        }

        protected:
        MFRC522 mfrc522;
    };

This also calls the default ctor and works best if the class provides `operator=`.


body:
I removed the DVD-RW from my laptop and want to use the new area as an IO port instead. There is an Arduino Nano with me which can fit into the emptied out drive space and there are some easy to connect IO headers with me.

The only (major) problem is how can i connect the Arduino to the slimline SATA port of the DVD drive. There are some SATA to USB converters available in the market, but will they work? (as i am trying to connect it the other way around)

Is there any possible way to connect the Arduino to the SATA port, and even if i would be able to connect it, would i be able to use it as a regular Arduino as if it were connected to a USB port?

title: Connecting Arduino to PC through Slimline SATA instead of USB?

Answers: 1

body: No, there is no way of connecting an Arduino to a SATA port. You require USB or UART. SATA is a specific dedicated port, whereas USB is, as the name suggests, *Universal*. So USB can become SATA but SATA can never become USB.


body:
I did a project with a fingerprint sensor. You can do the fingerprinting process by typing down 4 on the serial port, but in the same time i want to do this process with pressing another button.Can someone help me?

[![Fingerprint command][1]][1]

  [1]: https://i.stack.imgur.com/4nC8u.png

code  http://www.heypasteit.com/clip/0IIQ6G

    > #define  VB

    #include <Adafruit_Fingerprint.h>
    #include <SoftwareSerial.h>
    #include <EEPROM.h>

    SoftwareSerial mySerial(10, 11);
    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    char data;
    unsigned int p;
    uint8_t id;

    void setup()
    {
      Serial.begin(9600);
      finger.begin(57600);
      Serial.println("Sensore baglaniyor!");
      if(finger.verifyPassword())
      {
        Serial.println("Baglanti basarili!");
      }
      else
      {
        Serial.println("Sensor bulunamadi ");
        while (1);
      }
    }

    void loop()
    {
      delay(100);

      if(Serial.available()>0)
      {
        data=Serial.read();

        if(data=='1')
        {
          Serial.println("Delete all ID records");
          finger.emptyDatabase();
          delay(50);
          EEPROM.write(0,-1);    //reset ID counter
        }
        else if(data=='3')
        {
          id = EEPROM.read(0) + 1;    //get next available ID
          Serial.print("Enrolling ID #");
          Serial.println(id);
          getFingerprintEnroll(id);
          delay(50);
          EEPROM.write(0, id);        //save current ID
        }

        while (data=='4')
        {
          getFingerprintID();
          delay(50);

        }
      }
    }

    uint8_t getFingerprintEnroll(uint8_t id)
    {
      uint8_t p = -1;
      Serial.println("Waiting for valid finger to enroll");
      while (p != FINGERPRINT_OK)
      {
        p = finger.getImage();
        switch (p)
        {
        case FINGERPRINT_OK:
    #if !defined (VB)
          Serial.println();
    #endif
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
    #if !defined (VB)
          Serial.print(".");
    #endif
          break;
        default:
    #if !defined (VB)
          Serial.println();
    #endif
          Serial.println("Unknown error");
          break;
        }
      }

      p = finger.image2Tz(1);
      switch (p)
      {
      case FINGERPRINT_OK:
        Serial.println("Image converted");
        break;
      }

      Serial.println("Remove finger");
      delay(1000);
      p = 0;
      while (p != FINGERPRINT_NOFINGER)
      {
        p = finger.getImage();
      }

      p = -1;
      Serial.println("Place same finger again");
      while (p != FINGERPRINT_OK)
      {
        p = finger.getImage();
        switch (p)
        {
        case FINGERPRINT_OK:
    #if !defined (VB)
          Serial.println();
    #endif
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
    #if !defined (VB)
          Serial.print(".");
    #endif
          break;
        default:
    #if !defined (VB)
          Serial.println();
    #endif
          Serial.println("Unknown error");
          break;
        }
      }

      p = finger.image2Tz(2);
      switch (p)
      {
      case FINGERPRINT_OK:
        Serial.println("Image converted");
        break;
      default:
        Serial.println("Unknown error");
        return p;
      }

      p = finger.createModel();
      switch (p)
      {
      case FINGERPRINT_OK:
        Serial.println("Prints matched!");
        break;
      case FINGERPRINT_ENROLLMISMATCH:
        Serial.println("Fingerprints did not match");
        return -1;
        break;
      default:
        Serial.println("Unknown error");
        return -1;
        break;
      }

      p = finger.storeModel(id);
      switch (p)
      {
      case FINGERPRINT_OK:
        Serial.println("Stored!");
        break;
      default:
        Serial.println("Unknown error");
        return p;
        break;

      }
    }

    int getFingerprintID()
    {
      p = -1;
      Serial.println("Waiting for registered ID");
      while (p != FINGERPRINT_OK)
      {
        p = finger.getImage();
        switch (p)
        {
        case FINGERPRINT_OK:
    #if !defined (VB)
          Serial.println();
    #endif
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
    #if !defined (VB)
          Serial.print(".");
    #endif
          break;
        default:
    #if !defined (VB)
          Serial.println();
    #endif
          Serial.println("Unknown error");
          break;
        }
      }

      p = finger.image2Tz();
      switch (p)
      {
      case FINGERPRINT_OK:
        Serial.println("Image converted");
        break;
      default:
        Serial.println("Unknown error");
        return -1;
      }

      p = finger.fingerFastSearch();
      switch (p)
      {
      case FINGERPRINT_OK:
        Serial.println("Found a print match!");
        break;
      case FINGERPRINT_NOTFOUND:
        Serial.println("Did not find a match");
        return -1;
        break;
      default:
        Serial.println("Unknown error");
        return -1;
        break;
      }

      digitalWrite(A1, HIGH);
      delay(500);
      digitalWrite(A1, LOW);
      delay(2000);

      Serial.print("Found ID #");
      Serial.print(finger.fingerID);
      Serial.print(" with accuracy value of ");
      Serial.println(finger.confidence);
      return finger.fingerID;
    }

title: Arduıno button problem

Answers: 1

body:
Take a look at the `Button` sketch in the examples menu in the Arduino IDE. That is the simplest example of how to use a button in Arduino.

**Circuit**

This is the test circuit. When you press the button, the built LED turns on/off.  The circuit is applicable to any Arduino Uno, Mini, etc. The two wires at right are not really needed, but it doesn't hurt if you put them in the breadboard).

Note: What follows is an excerpt from https://www.arduino.cc/en/Tutorial/Button.

[![Button example][1]][1]

Connect three wires to the board. The first two, red and black, connect to the two long vertical rows on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pull-down resistor (here 10K ohm) to ground. The other leg of the button connects to the 5 volt supply.

When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected to ground (through the pull-down resistor) and we read a LOW. When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts, so that we read a HIGH.

You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH, and going LOW when the button is pressed. If so, the behavior of the sketch will be reversed, with the LED normally on and turning off when you press the button.

If you disconnect the digital I/O pin from everything, the LED may blink erratically. This is because the input is "floating" - that is, it will randomly return either HIGH or LOW. That's why you need a pull-up or pull-down resistor in the circuit.

**Code**

    // constants won't change. They're used here to set pin numbers:
    const int buttonPin = 2;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin

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

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

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

      // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
      if (buttonState == HIGH) {
        // turn LED on:
        digitalWrite(ledPin, HIGH);
      } else {
        // turn LED off:
        digitalWrite(ledPin, LOW);
      }
    }

  [1]: https://i.stack.imgur.com/frA4Y.png


body:
I am sending a polymorphic object over serial between two Arduinos. The transmission should be fine, indeed if on the receiver side I `static_cast` the pointer to the `Derived` class it works properly. On the other hand if I try to call virtual functions on the `Base` pointer, Arduino resets. What is causing this behaviour?

Some samples of the code follows.

Sender:

    RS485_Serial bus;
    void loop ()
    {
      Random r(1); //targeting device 1 in the bus
      if (r.request(bus)) { blink(r.val); } //make a request for a random number
                                            //blink the led the given number of times

      delay(1000);
    }

Receiver:

    RS485_Serial bus;
    bus.set_address(1);
    void loop ()
    {
      listen(bus);
    }

Selected common parts:

    struct Action {
      byte target_address;

      Action(byte addr): target_address(addr) {}
      virtual ~Action() {}

      virtual size_t size() const { return sizeof(*this); }
      virtual int  vrequest(RS485_Serial &) = 0;
      virtual void vrespond(RS485_Serial &) = 0;

      int request(RS485_Serial & bus) {
        bus.write(reinterpret_cast<byte*>(this), size());
        return vrequest(bus);
      }
      void respond(RS485_Serial & bus) {
        vrespond(bus); // <--- This virtual call makes the sender reset
      }
    };

    struct Random: Action {
      size_t size() const override { return sizeof(*this); }
      int val;
      Random(byte address): Action(address) {}

      int vrequest(RS485_Serial & bus) override {
        return bus.read(val);
      }
      void vrespond(RS485_Serial & bus) override {
        bus.write(static_cast<decltype(val)>(random(2,5)));
      }
    };

    void listen(RS485_Serial & bus) {
      byte * data = nullptr;
      byte length = 0;
      if ( bus.read(data, length) ){
        Action & a = *(reinterpret_cast<Action*>(data));
        if (a.size() == length) blink(3);
        if (a.target_address == bus.address) {
          a.respond(bus);
          //static_cast<Random*>(&a)->vrespond(); works but it has no point
        }
      }
    }

My doubt is that if the vtable is stored in different positions, than the vtable pointer in the object obtained by the receiver will be off, causing the crash.

title: Send a polymorphic object over serial

Answers: 2

body:
I think http://stackoverflow.com is the correct forum for your question. Your problem is how to serialize/deserialize correctly an object in C++.

An easy way to do it is simply send the values (not the object) and recreate the object at the other side. So, now your problem is reduced to send and receive a bunch of int's, float's, string's, whatever.

Why you want/need to do that?

body:
I suspect then that the object contains a pointer to the code for `vrespond`, which is at a specific (and differing from program to program) location in flash memory. An object in C++ isn't a single atomic item, it is a collection of data and pointers to functions. On a Harvard architecture system the data is in RAM and the code is in Flash (you cannot typically execute code from RAM). The compiler chooses where to place the code in Flash when it compiles (well, the linker does). That won't be the same address in different programs. All you are doing is sending over the addresses in flash that the code resides at - and those addresses are incorrect. By specifically casting it to a type that has code available you are also telling it where that code resides. Without that manual cast you are having to rely on the (incorrect) function pointers.

It is a bad idea to transfer objects like that from one system to another. It is better to transfer just the data and feed that data into an existing object created on the receiver. How you send and receive that data and feed it into the object is up to you.


body: The usb to serial converter i found was $4 .maybe i could use something less expensive,like jus a port.I need serious help ,the serial port was about $1

title: What to use instead of a USB to serial converter

Answers: 2

body:
May I suggest RS232 connection? It is an ancient tech but it might work for you. I am adding a [tutorial][1]. Also a [component][2] from eBay, which is 0.99 US dolar.

  [1]: http://www.arcelect.com/rs232.htm
  [2]: http://www.ebay.com/itm/MAX232CSE-Transfer-Chip-RS232-To-TTL-Converter-Module-COM-Serial-Board-AD-/112071858489?epid=1586990854&hash=item1a1800d939:g:GrcAAOSwOtdYTeid

body:
> The usb to serial converter i found was $4 .

you can find old Nokia data cable (a form of usb/ttl converter) for less than a dollar, or free if you happen to have one.

alternaively, usbasp programmers are very simple / inexpensive.

diy is possible but you need to count your time. tools need to be reliable so i tend to rule that out.


body:
I've been reading a lot on the ESP8266, but still my understanding is shaky. I have the Arduino IDE running on a PC, which uses wires to connect to the ESP8266 via a USB device (Device Manager > Ports (COM & LPT) > Silicon Labs CP210x USB to UART Bridge). This is how I uploaded a simple sketch to the ESP8266.

It works and has been installed in the wall. I'm happy and relieved to complete the project... except for one small thing: I noticed that it shows up on WiFi. I can connect to it without a password, with a "Limited" connection. After that I'm lost, but I wonder if someone who knows what they are doing can use this unsecured connection to hack my install. I'd like to disable the WiFi, if possible, since I'm not using it.

The worst part is my learning curve now starts over. I thought that when my sketch gets uploaded, it replaces the original firmware. Now "firmware" is an elusive concept. I keep thinking that it shows up on WiFi because of something running in firmware. My sketch hasn't any code for WiFi. What am I missing/do I have wrong?

title: Can the WiFi on ESP8266 be disabled?

Answers: 4

body:
 1. To turn of the WiFi add the WiFi library and use WiFi.forceSleepBegin();

 2. Firmware is the program/sketch that controls a MicroController Unit aka MCU (and in this case a Arduino).

    Best explanation I know is here: https://en.wikipedia.org/wiki/Firmware

body:
You control WiFi using `wifi.setmode()`.

ESP8266's WiFi is very versatil. You can be a client and/or an access point. You can get your IP from DHCP or static.

Per default, ESP8266 start in STATIONAP mode (as client and access point).

This is the pertinent part from the official [page][1]

**wifi.setmode()**

Configures the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

 - Station mode, where the NodeMCU device joins an existing network

 - Access point (AP) mode, where it creates its own network that others can join

 - Station + AP mode, where it both creates its own network while at the same time being joined to another existing network

 - **WiFi off**

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.

**Note**

WiFi configuration will be retained until changed even if device is turned off.

**Syntax**

    wifi.setmode(mode[, save])

**Parameters**

    mode value should be one of
        wifi.STATION for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
        wifi.SOFTAP for when the device is acting only as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
        wifi.STATIONAP is the combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local WiFi connection and connect to another WiFi router.
        wifi.NULLMODE changing WiFi mode to NULL_MODE will put wifi into a low power state similar to MODEM_SLEEP, provided wifi.nullmodesleep(false) has not been called.

    save choose whether or not to save wifi mode to flash
        true WiFi mode configuration will be retained through power cycle. (Default)
        false WiFi mode configuration will not be retained through power cycle.

**Returns**

current mode after setup

**Example**

    wifi.setmode(wifi.STATION);

**See also**

wifi.getmode() wifi.getdefaultmode()

  [1]: https://nodemcu.readthedocs.io/en/master/en/modules/wifi/#wifisetmode

body:
This is the best solution I have found so far (source: GitHub [gist](https://gist.github.com/chaeplin/be4d9ca41a991aa327bb))

The two functions below are all you need to toggle your WiFi chip. The huge advantage of using these is that they work without having to invoke an `ESP.deepsleep()` call.

Mind you, if you have already done an `ESP.deepsleep(time, WAKE_RF_DISABLED)` that means that your WiFi chip has been disabled altogether, and calling `WiFiOn()` will NOT be able to toggle it back ON. In this case you MUST do `ESP.deepsleep(time, WAKE_RF_DEFAULT)`. But once you WiFi chip has been re-enabled, you can call `WiFiOn()` and `WiFiOff()` as many times as you please, they will work fine.

 extern "C" {
  #include "user_interface.h"  // Required for wifi_station_connect() to work
 }

 #include <Arduino.h>
 #include <ESP8266WiFi.h>

 #define FPM_SLEEP_MAX_TIME 0xFFFFFFF

 void WiFiOn();
 void WiFiOff();

 //------------------------------------------------------------------------------

 void setup() {

  WiFiOn();
  delay(5000);
  WiFiOff();
  delay(5000);
  ESP.deepSleep(1e6 * 10, WAKE_RF_DEFAULT); // sleep 10 seconds

 }

 void loop() {
  ;
 }
 //------------------------------------------------------------------------------

 void WiFiOn() {

  wifi_fpm_do_wakeup();
  wifi_fpm_close();

  //Serial.println("Reconnecting");
  wifi_set_opmode(STATION_MODE);
  wifi_station_connect();
 }

 void WiFiOff() {

  //Serial.println("diconnecting client and wifi");
  //client.disconnect();
  wifi_station_disconnect();
  wifi_set_opmode(NULL_MODE);
  wifi_set_sleep_type(MODEM_SLEEP_T);
  wifi_fpm_open();
  wifi_fpm_do_sleep(FPM_SLEEP_MAX_TIME);

 }

body:
Many esp8266 devices by default start in (WIFI_AP) SoftAP mode, and will appear as a wifi network access point, waiting for stations to connect.

User code in any sketch, should explicitly set wifi to the appropriate mode. If you do not need wifi, set the wifi mode off. To do this with the Arduino IDE, an esp8266 must run a sketch at least once that includes the wifi class to use its .mode() method.

    #include <ESP8266WiFi.h>

    void setup() {
       Serial.begin(115200);
       WiFi.mode(WIFI_OFF);
       if (WiFi.getMode() == WIFI_OFF)
          Serial.println(F("\nWifi mode is WIFI_OFF, until it is explicitly changed"));
    }

The mode setting persists across power on and restart/reset cycles, until user code specifies a different mode. So once run on the esp8266, the all the lines above (except setup()) could optionally be removed from subsequent sketches uploaded to the esp8266, and the wifi will remain off.

Firmware is lower-level software that runs between the hardware and your higher-level sketch. Many esp8266 came with [Espressif firmware][1] and a sketch installed.

If you are concerned about energy consumption, investigate waking up the esp8266 with the radio disabled, eg.

    ESP.deepSleepInstant (microseconds, WAKE_RF_DISABLED);

  [1]: https://github.com/espressif/ESP8266_NONOS_SDK


body:
I am trying to run a sensor from my switch using POE. I have created a temp/humidity sensor using the MySensors directions https://www.mysensors.org/about/arduino.  I decided to use a nano due to the USB connector. I have connected this to my switch via a TP-Link POE splitter set to 5 volt output.

When connected, the switch provides power for a second or two then turns off for 10 seconds or so before coming on again. I believe the Switch is testing the circuit not detecting enough power being drawn and shuts down. It then goes through the cycle again. Note: both the power LED on the switch and the nano LEDS light up while power is supplied. I believe the nano itself only uses about 20mA

I have tested with another device that requires 9volts (hand held phone) via the splitter and it works fine with power provided consistently.

I was wondering if there is some circuitry I can add before the Arduino that will draw a little more current but still provide a constant 5V to the nano.

Additional information. The switch is a Linksys LGS124P. I have tried to find more detail regarding the required power but can only find this datasheet that does not provide that level of detail
http://downloads.linksys.com/downloads/datasheet/1224699456700/25685_LINKSYS_unmanaged_POE_switches_PROD_Revised.pdf

title: Arduino nano does not draw enough power

Answers: 1

body: A resistor or a light bulb in parallel with the Arduino will increase the power consumption.


body:
I'm trying to make a Arduino Leonardo as a Keyboard for an iPad. I was [successful][1] with an Arduino UNO. However I'm hoping to use an ATmega 32U4 because of the better HID functionalities and smaller boards like the Beetle.

The problem I'm having is that when I connect the Leonardo to my iPad, the iPad shows an alert saying that the Leonardo is using too much power.

[![iPad too much power alert][2]][2]

Tried running the board with an external power source. Then I get a different alert: Device not Supported.

[![enter image description here][3]][3]

At this point I believe that the problem is not necessarily power, but the fact that the Leonardo is announcing itself to the iPad and the iPad does not like it. In the UNO project, through re-flashing, the board acts only as a HID.

Is there a way to make the Leonardo (or other ATmega 32U4 based board) to not advertise itself on the USB port while allowing the HID functionality to operate?

  [1]: https://medium.com/@fsaint/setup-the-wifi-password-for-a-many-ipads-with-keyboarduino-503dccf92686
  [2]: https://i.stack.imgur.com/gbjjv.png
  [3]: https://i.stack.imgur.com/bSLp1.png

title: Arduino Leonardo as keyboard for an iPad

Answers: 3

body:
If indeed the descriptor is the problem then yes you can change it.

In the core file `USBCore.h` is the line:

    #define D_CONFIG(_totalLength,_interfaces) \
        { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED | USB_CONFIG_REMOTE_WAKEUP, USB_CONFIG_POWER_MA(500) }

Just change the 500 to something smaller (it has to be an even number).

However it may be that the Leonardo isn't programmed to support the Boot Protocol for HID. In which case that would require bigger changes to the USB and HID stacks in the core.

body:
i will stress now that i haven't tested this, and if it doesn't work you may have to reflash the bootloader in order to program the arduino again.
in the arduino install directory we are looking for the following file:

    Arduino\hardware\arduino\avr\cores\arduino\main.cpp

at line 40 (i'm using 1.6.9) we have:

    #if defined(USBCON)
        USBDevice.attach();
    #endif

in theory if you comment this out the serial port may not be ennumerated, however i don't know if the keyboard functions will still work.

if it does work you should wrap it in an if block so that the serial port shows if a certain pin is pulled high/low whatever your preference. this would enable you to program it as normal.

body:
I have found the solution - your USB > Lightning adapter must has the option for charging.

For example i use Arduino Leonardo connected to IPhone 6 by USB to adapter who has USB nest and charging nest. IPhone shows me info that "This device is not supported.", but all works fine and I can control IPhone by Arduino Leonardo.


body:
In the documentation of the nRF24L01 library I use ([library][1]), the CRC state (on/off) and length can be set or get. It seems to be used for auto ack, but when I switch auto ack off, what is the use of CRC? Can I somehow read the CRC value or use it somehow in a useful way?

The reason is, I get sometimes wrong values and would like the CRC for that, but otherwise I need to implement my own CRC byte(s) in the payload.

(also, when I put my finger against the PCB side on the side where the PCB antenna is placed, but not touching the antenna, I get many more messages).

  [1]: http://tmrh20.github.io/RF24/classRF24.html

title: CRC usage when ack disabled in nRF24L01

Answers: 0


body:
I'm working on a robotics project right now and my limited DIYer knowledge of electrical circuits is failing me. I need to power 7 Rage Standard Metal Gear Servos (RGRS104-16-6vm) and 4 RadioShack Micro Servos using a Tenergy 6V 3300mAh NiMH Battery Pack. I've made a diagram of the circuit I'd like to make, but I feel like there's more to this type of circuit than I've planned for. There are only 9 servo connections because two pairs of Rage Servos will be wired together to share the same battery and signal connection. I'm also open to using a different battery if that's what it takes to make the robot run smoothly (It has to use a rechargeable battery though; It's meant to be portable.) Also, the Arduino has it's own battery, so no worries there.

**Would you please point out what I need to add to my circuit to make sure it works properly?**

Thanks in advance!

[![Servo Power Board Diagram][1]][1]

**More Info:**

**Rage Standard Metal Gear Servo RGRS104-16-6vm**
Dimensions: 40.8 × 20.1 × 38 mm
Weight: 56 g
Operating Speed: 0.18sec/60degree (4.8V), 0.16sec/60degree (6V)
Stall Torque: 9kg.cm/125.2oz.in(4.8V), 10.2kg.cm/141.9oz.in(6V)
Operating Voltage: 4.8V~6V
Control System: Analog
Direction: CCW
Operating Angle: 180degree
Required Pulse: 500us-2500us
Bearing Type: 2BB
Gear Type: Metal
Motor Type: Carbon
Connector Wire Length: 30 cm.

**RadioShack Micro Servo**
Voltage: 4.8~6.0V
Torque: 1.5kg/cm at 4.8V; 1.8kg/cm at 6.0V
Speed: 0.12/60ТА at 4.8V; 0.10/60ТА at 6.0V
Size: 23x11.5x24mm
Weight: 8.6 g
Use Angle: <=160ТА

**Tenergy 6V 3300mAh NiMH Battery Pack**
Chemistry: Ni-MH
Cell Size: Sub-C
Nominal Voltage (V): 6
Capacity (mAh): 3300
Max Continuous Discharge Current: 6A
Battery Charging Current:
Standard: 1A
Weight: 10oz.
Dimensions: 112 x 46 x 23mm (LxWxT)
Connector: Hitech

**Link to Diagram:** https://i.stack.imgur.com/L4GtP.jpg

  [1]: https://i.stack.imgur.com/DS00N.png

title: Powering Multiple Servos From One Battery- What is my circuit missing?

Answers: 1

body:
One thing to ask, it is not clear if you are going to run the Arduino Uno off the same battery, or off a different battery?

If the same battery, then you are likely going to need to create an V+ output for the Uno, but will need to ensure that any drain from multiple servo's running are not going to impact on the voltage supplied to the arduino, and also that the voltage supplied is compatiable with the Uno (e.g. don't run 6V+ into the 3V outlet)

Just to note as well, the Arduino Uno has (to my knowledge) only has about 6 PWM pins which is what you will need to drive the servo's through the signal pin. You can add I2C PWM expanders which give you more pins (e.g. https://www.adafruit.com/product/815) but YMMV


body:
I have a ultrasonic sensor and in order to get the distance I use the pulseIn() function included in the arduino library, and then change it to distance. As the ultrasounds does not work equally in different materials as i have seen in [Performance comparison of Infrared and Ultrasonic sensors for
obstacles of different materials in vehicle/ robot navigation
applications][1]. My question is if there is a way of changing the pulseIn() to have different materials, function:

    unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
    {
     // cache the port and bit of the pin in order to speed up the
     // pulse width measuring loop and achieve finer resolution.  calling
     // digitalRead() instead yields much coarser resolution.
     uint8_t bit = digitalPinToBitMask(pin);
     uint8_t port = digitalPinToPort(pin);
     uint8_t stateMask = (state ? bit : 0);

     // convert the timeout from microseconds to a number of times through
     // the initial loop; it takes approximately 16 clock cycles per iteration
     unsigned long maxloops = microsecondsToClockCycles(timeout)/16;

     unsigned long width = countPulseASM(portInputRegister(port), bit, stateMask, maxloops);

     // prevent clockCyclesToMicroseconds to return bogus values if countPulseASM timed out
     if (width)
      return clockCyclesToMicroseconds(width * 16 + 16);
     else
      return 0;
    }
or the countPulseASM, which I translate from the asembled code, which can have some errors) as:

    // wait for any previous pulse to end
    while ((*port & bit) == stateMask)
    {
      if (--maxloops == 0)
      {
            return 0;
      }
    }

    // wait for the pulse to start
     while ((*port & bit) != stateMask)
    {
     if (--maxloops == 0)
     {
           return 0;
     }
    }

    // wait for the pulse to stop
     while ((*port & bit) == stateMask)
     {
     if (++width == maxloops)
     {
      return 0;
     }
     }
    return width;

Another way of doing that is having a correction factor while changing the time into the distance, but for that I shold have the differences of all the materials.

  [1]: http://iopscience.iop.org/article/10.1088/1757-899X/149/1/012141/pdf

title: Changing parameters of pulseIn() to sense different materials

Answers: 1

body:
`pulseIn` just returns the length of a pulse on a pin. That has nothing to do with materials and can have no concept of materials. It is just time. You cannot change time just to suit different materials.

Instead if you want to calculate the distance depending on different materials you need the actual time of the pulse to then calculate the distance in different ways.

That is down to your sketch to do that calculation using the time provided by `pulseIn` and your own adjustment values.


body:
I am trying to connect the MMA8452Q with AtTiny85 using the TinyWireM library.
I made the proper hardware setup with  pull-ups on  SCL and SDA pins - tested it on Arduino
Uno and it works, however when i connect the Tiny I cannot even get the handshake.
The following code produces output `13` instead of `42` (0x2A)

**HARDWARE SETUP**

 MMA8452 Breakout ------------AtTiny85

 3.3V -------voltage regulator------ 5V

 SDA -----------^^(330)^^----------- PB0 (on attiny programmer marked as 5)

 SCL -----------^^(330)^^----------- PB3 (on attiny programmer marked as 2)

 GND --------------------------------- GND

(I also tried different pins with no luck)

**CODE**

    //---bluetooth console communication stuff---//
    #include <SoftwareSerial.h>
    #define rxPin 1 //not important - needed for initialization
    #define txPin A2
    SoftwareSerial blueTooth(rxPin, txPin);
    //      ---     //

    #include "TinyWireM.h" // Used for I2C

    // The SparkFun breakout board defaults to 1, set to 0 if SA0 jumper on the bottom of the board is set
    #define MMA8452_ADDRESS 0x1D  // 0x1D if SA0 is high, 0x1C if low

    #define WHO_AM_I   0x0D

    void setup() {

      blueTooth.begin(9600);
      delay(1000);
      TinyWireM.begin(); //Join the bus as a master
      delay(1000);
     }

    void loop() {
       byte c =0;
       c = readRegister(WHO_AM_I);
       blueTooth.println(c);
       delay(1000);
      }

     // Read a single byte from addressToRead and return it as a byte
    byte readRegister(byte addressToRead) {
      TinyWireM.beginTransmission(MMA8452_ADDRESS);
      TinyWireM.send(addressToRead);
      TinyWireM.endTransmission(); //endTransmission but keep the connection active

      TinyWireM.requestFrom(MMA8452_ADDRESS, 1); //Ask for 1 byte, once done, bus is released by default

      while(!TinyWireM.available()) ; //Wait for the data to come back
      return TinyWireM.receive(); //Return this one byte
    }

Would anyone know how to get it right?

title: AtTiny85 and MMA8452Q accelerometer cannot connect using i2c

Answers: 2

body:
> using the TinyWireM library.

Make sure the i2c actually works. Arduino libraries are generally of poor quality and just because someone wrote it doesn't mean it actually works. Get a logic analyzer or scope on the bus and see what's going on.

Once you can confirm that, get a datasheet for the 8452 and see how it works and code to it.

body:
On an ATtiny85 pin 5 (PB0) is SDA and pin 7 (PB2) is SCL for the I2C interface.  You're using the wrong pin for SCL.

Additionally, your pull-up resistors are too strong.  Somewhere between 4.7K Ohm and 10K Ohm are recommended for pull-up's on the SDA and SCL lines.


body:
I'm using an Arduino Mega to send serial commands to a device that supports RS485 or RS422 half-duplex. To do this, I'm using the following code:

    bool foo(int A, int B)
    //...
    //Const global int to byte 1&2
    //Math on int A and int B to make bytes 3-8
    //...
      unsigned char cmd[8]={[byte1],[byte2],[byte3],[byte4],[byte5],[byte6],[byte7],[byte8]};
      while(rep)
      {
        for (int i=0; i< 8; i++)
        {
          Serial2.write(cmd[i]);   // Send C string
        }
        if(Serial2.available())
        {
          //device echoed == command recieved
          rep=false;
        }
      }

The odd thing is that sometimes the loop gets it right on the first try, other times it takes 50+ tries to receive a command. This makes me think that there is something in my code that is making the data transmission unreliable. I believe it could be one of the following three things.

----------

 1. I still need an RS485 module

In a previous version of my software, I was using the software serial library and used an RS485 module similar to the one shown here:

[![Arduino Uno to RS485][1]][1]

As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?

----------

2. Looping the `Serial2.write()`

Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the `for (int i=0; i< 8; i++)` loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?

----------

3. I'm Not supporting a tri-state the transmit buffer

I was rereading the device's manual and found this line:

>The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.

Honestly, I have no idea what this means. Does Arduino do this? If not, how can I make this happen?

----------

Additional things of note:

 - I'd much rather use something like [Majenko's pointer way](https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/) to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be `\0` (or any other termchar) which would stop the loop prematurely. Is there a way to avoid this?
 - I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?

  [1]: https://i.stack.imgur.com/l94lE.jpg

title: Unreliable serial communication from Arduino Mega

Answers: 1

body:
> As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?

You still need the module. RS-485 and RS-422 are electrically incompatible with CMOS.

> Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the for (int i=0; i< 8; i++) loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?

Absolutely. Also you need to flush the serial after transmitting and switching back to receiving:

    digitalWrite(DE_PIN, HIGH);
    Serial2.write(cmd, 8);
    Serial2.flush();
    digitalWrite(DE_PIN, LOW);

Flushing the serial pauses your program until the entire command has been transmitted. That means not only sent from the TX buffer to the TX FIFO in the UART hardware, but also the last byte from the FIFO has been shifted out onto the wire. If you don't do that your command will get truncated by the transceiver module as you switch back to receive mode prematurely.

Note: I forget which is which for the DE pin - HIGH/LOW or LOW/HIGH. Change it appropriately. Also note that you don't need to manually loop - the Serial code already has that facility for you.

> The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.

That is what the DE/RE pins do - switch the module between active drive (transmit) and high-impedance (receive).

> I'd much rather use something like Majenko's pointer way to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be \0 (or any other termchar) which would stop the loop prematurely. Is there a way to avoid this?

That is only applicable with strings. With binary data you always have to know the length (though that doesn't have to be hard coded). All you need is a *maximum* length for any buffers you have.

> I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?

Besides my notes above, this method:

    while(rep)
    {
      for (int i=0; i< 8; i++)
      {
        Serial2.write(cmd[i]);   // Send C string
      }
      if(Serial2.available())
      {
        //device echoed == command recieved
        rep=false;
      }
    }

is completely wrong. You are sending a command and then *immediately* looking for a response. You haven't given that response time to either be generated by the remote end or be received by the Mega.

Instead it should be:

1. Send the command.
2. Look for some response data
3. If some data has arrived then add it to the response buffer
4. If the whole response has not yet arrived go back to 2

You can also add 2.5: if it's been checking too long then abort with a "timeout".


body:
So I'm trying to connect the chip with an 8-bit data bus. All works good, but...

Arduino Uno uses D0 and D1 for serial TX/RX (USB connection with PC). When I try to open a serial connection (on serial.begin stage) ports D0 and D1 blocks and the chip stops working. This is a problem.

I think I should relocate pins D0 and D1 to another port. But the chip uses 8 pins (8bit chip). So I need to relocate the first pin (D0) and the second pin (D1) to port b. Maybe I can use B4 and B3?

But I don't know how to use PORTD[PD2, PD3, PD4, PD5, PD6, PD7] and PORTB[PB4, PB3] in one time like:

    var portX = PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];
    portX = data;

My code:

    #include <avr/io.h>     // For I/O and other AVR registers
    #include <util/delay.h> // For timing

    /* Pinmap (Arduino UNO compatible) */
    #define YM_IC (5) // PC5 (= pin A5 for Arduino UNO)
    #define YM_CS (4) // PC4 (= pin A4 for Arduino UNO)
    #define YM_WR (3) // PC3 (= pin A3 for Arduino UNO)
    #define YM_RD (2) // PC2 (= pin A2 for Arduino UNO)
    #define YM_A0 (1) // PC1 (= pin A1 for Arduino UNO)
    #define YM_A1 (0) // PC0 (= pin A0 for Arduino UNO)
    #define YM_CTRL_DDR DDRC
    #define YM_CTRL_PORT PORTC
    #define YM_DATA_DDR DDRD

    #define YD0 (0)(= pin D0 for Arduino UNO)
    #define YD1 (1)(= pin D1 for Arduino UNO)
    #define YD2 (2)(= pin D2 for Arduino UNO)
    #define YD3 (3)(= pin D3 for Arduino UNO)
    #define YD4 (4)(= pin D4 for Arduino UNO)
    #define YD5 (5)(= pin D5 for Arduino UNO)
    #define YD6 (6)(= pin D6 for Arduino UNO)
    #define YD7 (7)(= pin D7 for Arduino UNO)

    #define YM_DATA_PORT PORTD // Whole PORT D for data bus (= pins D0 to D7 for Arduino UNO)
    #define YM_MCLOCK (1) // PB1 = OC1A (= pin D9 for Arduino UNO)
    #define YM_MCLOCK_DDR DDRB

    extern uint8_t chflash[6];
    uint8_t dacflash;
    #define NOTEONFLASH 4
    #define VGMWAIT 15

    static void write_ym(uint8_t data) {
      YM_CTRL_PORT &= ~_BV(YM_CS); // CS LOW
      YM_DATA_PORT = data;
      _delay_us(1);
      YM_CTRL_PORT &= ~_BV(YM_WR); // Write data
      _delay_us(5);
      YM_CTRL_PORT |= _BV(YM_WR);
      _delay_us(5);
      YM_CTRL_PORT |= _BV(YM_CS); // CS HIGH
    }

    /**
     * Write data into a specific register of the YM2612
     *
     * @author Furrtek
     * @param reg Destination register address
     * @param data Data to write
     */
    static void setreg(uint8_t reg, uint8_t data) {
      YM_CTRL_PORT &= ~_BV(YM_A0); // A0 low (select register)
      write_ym(reg);
      YM_CTRL_PORT |= _BV(YM_A0);  // A0 high (write register)
      write_ym(data);
    }

    void call() {
      setreg(0x28, 0xF0); // Key on
      _delay_ms(1000);
      setreg(0x28, 0x00); // Key off
    }

    uint8_t getfilebyte() {
      return Serial.read();
    }

    int main() {
      init();

      //Serial.begin(9600);
      /* Pins setup */
      YM_CTRL_DDR |= _BV(YM_IC) | _BV(YM_CS) | _BV(YM_WR) | _BV(YM_RD) | _BV(YM_A0) | _BV(YM_A1);
      YM_DATA_DDR |= _BV(YD0) | _BV(YD1) | _BV(YD2) | _BV(YD3) | _BV(YD4) | _BV(YD5) | _BV(YD6) | _BV(YD7);
      YM_MCLOCK_DDR |= _BV(YM_MCLOCK);
      YM_CTRL_PORT |= _BV(YM_IC) | _BV(YM_CS) | _BV(YM_WR) | _BV(YM_RD); /* IC, CS, WR and RD HIGH by default */
      YM_CTRL_PORT &= ~(_BV(YM_A0) | _BV(YM_A1)); /* A0 and A1 LOW by default */

      /* F_CPU / 2 clock generation */
      TCCR1A = _BV(COM1A0);            /* Toggle OCA1 on compare match */
      TCCR1B = _BV(WGM12) | _BV(CS10); /* CTC mode with prescaler /1 */
      TCCR1C = 0;                      /* Flag reset */
      TCNT1 = 0;                       /* Counter reset */
      OCR1A = 0;                       /* Divide base clock by two */

      /* Reset YM2612 */
      YM_CTRL_PORT &= ~_BV(YM_IC);
      _delay_ms(10);
      YM_CTRL_PORT |= _BV(YM_IC);
      _delay_ms(10);

      /* YM2612 Test code */
      setreg(0x22, 0x00); // LFO off
      setreg(0x27, 0x00); // Note off (channel 0)
      setreg(0x28, 0x01); // Note off (channel 1)
      setreg(0x28, 0x02); // Note off (channel 2)
      setreg(0x28, 0x04); // Note off (channel 3)
      setreg(0x28, 0x05); // Note off (channel 4)
      setreg(0x28, 0x06); // Note off (channel 5)
      setreg(0x2B, 0x00); // DAC off
      setreg(0x30, 0x71); //
      setreg(0x34, 0x0D); //
      setreg(0x38, 0x33); //
      setreg(0x3C, 0x01); // DT1/MUL
      setreg(0x40, 0x23); //
      setreg(0x44, 0x2D); //
      setreg(0x48, 0x26); //
      setreg(0x4C, 0x00); // Total level
      setreg(0x50, 0x5F); //
      setreg(0x54, 0x99); //
      setreg(0x58, 0x5F); //
      setreg(0x5C, 0x94); // RS/AR
      setreg(0x60, 0x05); //
      setreg(0x64, 0x05); //
      setreg(0x68, 0x05); //
      setreg(0x6C, 0x07); // AM/D1R
      setreg(0x70, 0x02); //
      setreg(0x74, 0x02); //
      setreg(0x78, 0x02); //
      setreg(0x7C, 0x02); // D2R
      setreg(0x80, 0x11); //
      setreg(0x84, 0x11); //
      setreg(0x88, 0x11); //
      setreg(0x8C, 0xA6); // D1L/RR
      setreg(0x90, 0x00); //
      setreg(0x94, 0x00); //
      setreg(0x98, 0x00); //
      setreg(0x9C, 0x00); // Proprietary
      setreg(0xB0, 0x32); // Feedback/algorithm
      setreg(0xB4, 0xC0); // Both speakers on
      setreg(0x28, 0x00); // Key off
      setreg(0xA4, 0x22); //
      setreg(0xA0, 0x69); // Set frequency

      call();

      while(1000) {
        if (Serial.available() > 0) {
          _delay_ms(1000);
          call();
          _delay_ms(1000);
          char var = getfilebyte();
          Serial.print("Yeah: ");
          Serial.println(var);
        } else {
          Serial.print("Nooo: ");
          Serial.println(Serial.available());
          call();
        }
      }
      while(1);
    }

title: Arduino port relocation (PORTD to PORTB)

Answers: 3

body:
You cannot set pin states in multiple ports simultaneously, if that's what you're asking.

At the instruction set level, setting pin states is a single that writes to an 8-bit register which corresponds to the 8 pins in a port. There is no way to write to two different registers in the same instruction, so if you need all eight bits to change exactly at the same time you're out of luck. However, if you can tolerate a little bit of time between 6 bits in one port changing state and 2 bits in another port changing state, then you can simply write a wrapper function.

    PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];
    void set_ym_ctrl_port(uint8_t data) {
        PORTD &= ~(0x3f<<2);
        PORTB &= ~(0x3<<3);
        PORTD |= (data & (0x3f<<2));
        PORTB |= (data & 0x3)<<3;
    }

Or something like that. If you need even less delay and you think you can do better than the compiler, inline assembly can be helpful.

As an aside, syntax like

    var portX = PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];

is not valid for a number of reasons.

body:
Adding to what @uint128_t said, if you really need to change the state of many pins at the same time, you can add some external latched shift registers as a SIPO (serial-in/parallel-out) interface towards the outer world.

The price you pay is that you have to load the entire register with the data you want to send before you can update the output pin states. This requires a clock cycle for each loaded bit (here I'm speaking of the clock of the external register, not Arduino's) and thus may add too much latency in your system, depending on what you are trying to do.

The 74HC595 is a classic (8-bit shift register with output latches), and can be cascaded to obtain a register of the desired width.

Here is an excerpt from [the datasheet of TI's 74HC595](http://www.ti.com/lit/ds/symlink/sn74hc595.pdf) (yellow emphasis mine):

>
>[![enter image description here][1]][1]
>

It's also sold in 16-pin DIP package, very convenient for breadboarding, in case you need it (common need for people that play with Arduinos).

The internal logic diagram is the following (from the same datasheet):

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

It is so common in the Arduino world that there are also open libraries do drive it, for example [this](https://playground.arduino.cc/Code/ShiftRegister595). But even without pre-written libraries, it is not difficult to drive it from an Arduino, if you have a little experience in digital logic and can understand the timing requirements stated in its datasheet (the table in section 7.6 is fairly easy to understand, once you know what setup and hold times are).

  [1]: https://i.stack.imgur.com/FXZuH.png
  [2]: https://i.stack.imgur.com/VymKA.png

body:
This is intended as a complement to uint128\_t's answer. I would like to
point out that the code in that answer changes the outputs in four
steps:

1. set to `LOW` the pins of `PORTD` that need to be `LOW`
2. set to `LOW` the pins of `PORTB` that need to be `LOW`
3. set to `HIGH` the pins of `PORTD` that need to be `HIGH`
4. set to `HIGH` the pins of `PORTB` that need to be `HIGH`

I compiled it on my system (with gcc 5.4.0): the generated assembly
shows that the whole process takes 18 CPU cycles. I.e. during
1.125 µs the outputs can be in an inconsistent state.

I then tried this alternative version:

    void set_ym_ctrl_port(uint8_t data) {
        uint8_t new_portd = PORTD & ~(0x3f<<2) | (data & (0x3f<<2)),
                new_portb = PORTB & ~(0x03<<3) | (data & 0x03)<<3;
        cli();
        PORTD = new_portd;
        PORTB = new_portb;
        sei();
    }

This changes the outputs on two steps:

1. update `PORTD`
2. update `PORTB`

The generated assembly showed that the updates are only one CPU cycle
apart. I.e. the outputs are inconsistent during only 62.5 ns.

Your mileage may vary. In case of doubt check the generated assembly.


body:
I have a little problem. I have a motor driver (L298N). When I engage in electricity, my 2 motors start and after 5 second stop. Then they stop for about 2 seconds, and then start and in a moment (0.5 second) turn off. This make still around (go about 0.5 s, stop for 2 seconds...). And my motor driver is very hot after 1 minute.

Is it possible that it is because of weak voltage? (The motor driver is for 6-35 V, and I have a 6 V battery).

[![enter image description here][1]][1]

L298n:
[enter image description here][2]

There is my code on Arduino:

<!-- language: lang-cpp -->

    const int motorPin1  = 9;
    const int motorPin2  = 10;
    const int motorPin3  = 6;
    const int motorPin4  = 5;

    void setup() {
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);
      pinMode(motorPin3, OUTPUT);
      pinMode(motorPin4, OUTPUT);
    }

    void loop() {
      forw(3000);
      back(3000);
    }

    int fast = 255;

    void forw(int timer) {
      analogWrite(motorPin1, 0);
      analogWrite(motorPin2, fast);
      analogWrite(motorPin3, 0);
      analogWrite(motorPin4, fast);
      delay(timer);
    }

    void back(int timer) {
      analogWrite(motorPin1, fast);
      analogWrite(motorPin2, 0);
      analogWrite(motorPin3, fast);
      analogWrite(motorPin4, 0);
      delay(timer);
    }

  [1]: https://i.stack.imgur.com/T5Fe9.png
  [2]: https://i.stack.imgur.com/N2Bzy.jpg

title: Arduino motor and motor driver

Answers: 2

body:
The L298 is a very old, obsolete design based on bipolar transistors, which means it has a lot of internal losses.

The energy consumed in those losses shows up as heat.

It also has some degree of overload or overtemperature protection, so what you are observing is an automatic shutdown.  Or perhaps, your motor is causing the battery voltage to sag and resetting your Arduino at which point the sketch resumes after a bootloader delay.  6v is really too low an input voltage to the Arduino's regulator, but too high for direct input without the regulator.

You need to make sure that the current draw of your motors is reasonable, and you likely want to replace the terrible L298 with a more modern, low less FET driver.  You will need to select one rated for the actual current draw of your motor: you should consider not only free rotation of the motor, but the increased current draw if it is mechanically stalled.

body:
I ran the code on my arduino(kinda old), when I checked with my multimeter I noticed that the 5th PWM pin didnt osciallate every 3 seconds, could you please try the below code where I changed the 5th pin to 3rd PWM pin, also please change the connections on the l298 board.

    const int motorPin1  = 9;
    const int motorPin2  = 10;
    const int motorPin3  = 6;
    const int motorPin4  = 3;

    void setup() {
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);
      pinMode(motorPin3, OUTPUT);
      pinMode(motorPin4, OUTPUT);
    }

    void loop() {
      forw(3000);
      back(3000);
    }

    int fast = 255;

    void forw(int timer) {
      analogWrite(motorPin1, 0);
      analogWrite(motorPin2, fast);
      analogWrite(motorPin3, 0);
      analogWrite(motorPin4, fast);
      delay(timer);
    }

    void back(int timer) {
      analogWrite(motorPin1, fast);
      analogWrite(motorPin2, 0);
      analogWrite(motorPin3, fast);
      analogWrite(motorPin4, 0);
      delay(timer);
    }


body:
Good Day. I am currently following a project where I can send data to my firebase database using an ESP8266-ESP01 wifi module and DHT11 temp/hum sensor.
I am using this adapter to enter the boot mode already with a program. Everything seems fine.
[![Guide][1]][1]

  [1]: https://i.stack.imgur.com/Fntdn.jpg

When I need to upload a program I am just tweaking the adapter using jumper cables to put the GPIO0 to GND and It works fine. My problem now is I have to use the DHT11 Sensor which is supposed to be connected to GPIO2. I tried to go to bootmode so  I connected DHT11(data) directly to the ESP8266(GPIO2) leaving the slot in the adapter empty in which I cant enter the boot mode for some reason.

But when I plug ESP8266(GPIO2) to the adapter slot, I can enter bootmode. Currently confused on how to tweak the adapter to be able to use the GPI02 to the DHT11. Any tips would really help. thanks!

title: Using ESP8266 Adapter with Temperature/Humidity Sensor

Answers: 1

body:
Thank you everyone for the tips. I have found a way to use the esp8266 adapter with the DHT11 sensor. First of all it was on boot mode all along, I had some code mistakes where my target url includes an 'https' tag on it thus not functioning as expected.

For those who would like to use this specific adapter with DHT11 attached in boot mode.

-Connect all female jumper wires end to the Esp8266 and the male jumper ends to the adapter except for the GPI02.

-The GPI02 slot on the adapter will be empty but the ESP8266 GPI02 end must be connected to the data pin of the DHT11.

Make sure that the ESP8266 and DHT11 sensor have enough power for both devices.


body:
I have fair experience with C/C++ so I decided to have a go at writing my first simple Arduino library. I wrote the code which seems to be fine to me except that it keeps complaining about the header file not found during compilation:

    /home/me/sketchbook/libraries/SegDisplay/SegDisplay.cpp:1:24: fatal error: SegDispaly.h: No such file or directory
     #include "SegDispaly.h"
                            ^
    compilation terminated.

I have the library located in my sketch folder under the name "SegDisplay":

    /home/me/sketchbook/libraries/
    └── SegDisplay
        ├── examples
        ├── keywords.txt
        ├── README.md
        ├── SegDisplay.cpp
        └── SegDisplay.h

and here's the code:

### SegDisplay.h:

    #ifndef _SEVEN_SEG_H_
    #define _SEVEN_SEG_H_

    #include <math.h>

    #if defined(ARDUINO) && (ARDUINO >= 100)
    #include <Arduino.h>
    #else
    #include <WProgram.h>
    #endif

    class SegDisplay
    {
    public:
     SegDisplay (int clockPin, int latchPin, int dataPin, int digitPins[4]);
     void display (double value);

    private:
     const int digitPins[4];
     const int clockPin;
     const int latchPin;
     const int dataPin;
     const byte digit[10] = //seven segment digits in bits
     {
      B00111111, //0
      B00000110, //1
      B01011011, //2
      B01001111, //3
      B01100110, //4
      B01101101, //5
      B01111101, //6
      B00000111, //7
      B01111111, //8
      B01101111  //9
     };
     int digitBuffer[4];

     void setRegisterData (byte data);
     void clearRegister();
     void clearDisplay();
     void updateDisplay();
    };

    #endif

###SegDisplay.cpp:

    #include "SegDispaly.h"

    SegDisplay::SegDisplay (int a, int b, int c, int d[4]):
     clockPin (a), latchPin (b), dataPin (c), digitPins (d), digitBuffer ({0})
    {
     for (int i = 0; i < 4; i++)
     {
      pinMode (digitPins[i], OUTPUT);
      digitalWrite (digitPins[i], HIGH);
     }
     pinMode (latchPin, OUTPUT);
     pinMode (clockPin, OUTPUT);
     pinMode (dataPin, OUTPUT);
    }

    void SegDispaly::setRegisterData (byte data)
    {
     digitalWrite (latchPin, LOW);
     shiftOut (dataPin, clockPin, MSBFIRST, data);
     digitalWrite (latchPin, HIGH);
    }

    void SegDispaly::clearRegister()
    {
     setRegisterData (B00000000);
    }

    void SegDispaly::clearDisplay()
    {
     // deactivate transistors
     for (int n = 0; n < 4; n++) digitalWrite (digitPins[n], HIGH);
    }

    //writes the temperature on display
    void SegDispaly::updateDisplay()
    {
     byte outByte;
     // dispaly digits
     for (int i = 0; i < 4; i++)
     {
      clearDisplay();
      clearRegister();

      // enable nth cell cathode (transistor)
      digitalWrite (digitPins[i], LOW);

      // output nth digit on display
      if (i == 1)
      {
       //print the decimal point on the 2nd digit
       outByte = digit[digitBuffer[i]] | B10000000;
      }
      else outByte = digit[digitBuffer[i]];
      setRegisterData (outByte);

      //delayMicroseconds (500);
      delay (5);

      //Serial.print (outByte, BIN);
      //if (i == 3)
      //{
      // Serial.println (".");
      //}
      //else Serial.print (", ");
     }
    }

    void SegDispaly::display (double value)
    {
     int n = int (value * 100);
     digitBuffer[0] = n / 1000;
     digitBuffer[1] = (n % 1000) / 100;
     digitBuffer[2] = (n % 100) / 10;
     digitBuffer[3] = (n % 100) % 10;
     updateDisplay();
    }

My target AVR is Arduino Uno R3, the code used to work fine in a sketch before I decided to create a library out of it. Any help would be greatly appreciated. thanks in advance.

title: Arduino library not working, can't find header

Answers: 1

body:
You spelled the header filename wrong:

    #include "SegDispaly.h"

should be:

    #include "SegDisplay.h"

You have also made the same mistake in the class name multiple places in SegDisplay.cpp.