body:
I created a setup in which a potentiometer controls a dc motor, with current flow through the dc motor controlled by an H-bridge.
The principle is as follows:
With the potentiometer dial set to the mid-point, the motor is off. Rotating the potentiometer clockwise would cause the motor to rotate in one direction, with speed dictated by the displacement of the potentiometer from the mid-point: the greater the displacement from mid-point, the greater the speed of rotation of the motor. If the potentiometer is rotated anti-clockwise, away from mid-point, the motor would rotate in the opposite direction from before; again, with speed dictated by the extent of displacement of the potentiometer from mid-point.

The loop has three functions, where HB_12EN is to enable the drivers, HB_1A is the first driver input, and HB_2A is the second driver input (H-Bridge pins 1, 2 and 7, respectively) as per this datasheet:
http://www.ti.com/lit/ds/symlink/sn754410.pdf

To summarise their functions: HB_12EN allows voltage to be applied to the the device controlled by the H-Bridge (in this case a motor), and is pulse-wave-modulated. HB_1A and HB_2A control the flow of current through the motor, setting its angular velocity. HB_1A set HIGH and HB_2A set LOW directs current one way through the motor, and HB1A set LOW and HB_2A set HIGH directs current the other way through the motor.

The loop is:

<!-- language-all: lang-c++ -->

    //OUTPUTS
    int const HB_12EN = 9; //pwm pin
    int const HB_1A = 2;
    int const HB_2A = 3;

    //INPUTS
    int const POT_MOT = 0; //A0, analog 0

    //GLOBAL VARIABLES
    unsigned int pot_val = 0; //ADC value from potentiometer
    unsigned int grp_num = 1;

    pot_val = analogRead(POT_MOT);
    grp_num = setMotSwitch(HB_12EN, HB_1A, HB_2A, pot_val, grp_num);
    setMotSpeed(HB_12EN, pot_val, grp_num);

The two (non-library) functions are:

    unsigned int setMotSwitch(int const motor_reg, int const first_motor, int const sec_motor, unsigned int pot_value, unsigned int group_num) //grp 0: 0-383; grp 1: 384-639; grp 2: 640-1023
    {
      if (pot_value >= 0 && pot_value < 384)
      {
        if (group_num != 0)
        {
           digitalWrite(motor_reg, LOW);
           digitalWrite(first_motor, HIGH);
           digitalWrite(sec_motor, LOW);
           group_num = 0;
        }
      }
      else if (pot_value > 383 && pot_value < 640)
      {
        if (group_num != 1)
        {
          digitalWrite(motor_reg, LOW);
          digitalWrite(first_motor, LOW);
          digitalWrite(sec_motor, LOW);
          group_num = 1;
        }
      }
      else if (pot_value > 639 && pot_value <= 1023)
      {
        if (group_num != 2)
        {
          digitalWrite(motor_reg, LOW);
          digitalWrite(first_motor, LOW);
          digitalWrite(sec_motor, HIGH);
          group_num = 2;
        }
      }
      else
      {
          digitalWrite(motor_reg, LOW);
          digitalWrite(first_motor, LOW);
          digitalWrite(sec_motor, LOW);
          group_num = 0;
      }
      return group_num;
    }

    void setMotSpeed(int const motor_reg, unsigned int pot_value, unsigned int group_num)
    {
      unsigned int mot_speed = 0;
      if (group_num == 0)
      {
        mot_speed = map(pot_value, 0, 383, 255, 0);
        mot_speed = constrain(mot_speed, 0, 255);
        analogWrite(motor_reg, mot_speed);
      }
      else if (group_num == 1)
      {
        if (pot_value > 500 && pot_value < 523)
        {
          digitalWrite(motor_reg, HIGH); //braking
        }
        else
        {
          digitalWrite(motor_reg, LOW);
        }
      }
      else if (group_num == 2)
      {
        mot_speed = map(pot_value, 640, 1023, 0, 255);
        mot_speed = constrain(mot_speed, 0, 255);
        analogWrite(motor_reg, mot_speed);
      }
    }

I tried to proceed as follows:
As the potentiometer would produce an ADC input with 1024 states, I divided those 1024 states in to 8 groups, the first three groups, covering the first 384 states (0-383) correspond to a dc motor direction (let's say anticlockwise), representing different speeds of rotation (ignoring issues of many-to-one mapping). The middle 2 groups, 256 states (384-639), correspond to a stationary motor. The last three groups, 384 states (640-1023), correspond to motor rotation in the other direction (in this example, clockwise). The ADC inputs have to be translated in to analog outputs with 256 possible states (0-255), so I map each range as appropriate; for 0-383, the mapping has to be reversed, so an input of 383 corresponds to an input of 0. The middle range (384-639) is stationary, but I tried to make a small "sub"-range in the middle a "braking range", I believed this is achieved by setting both H-bridge inputs to LOW. The 640-1023 range mapping is 640 to 0 and 1023 to 255.

Hopefully that makes sense. It seems to work, the issue I am having is that the motor seems to achieve a greater speed in one direction compared to the other: the maximum rotation speed produced in the motor is greater when the potentiometer is at its maximum in one direction compared to the other. I am pretty sure the code above gives an "even" mapping from the potentiometer to the motor for both directions. Is this, then, something to do with hardware?, and is it something to be anticipated in these kinds of setups?

Any help would be appreciated. If anyone has any advice on the best way to combine a potentiometer -or similar- input with a motor output let me know. The "braking" functionality is also a little confusing.

title: Angular velocity of a dc motor controlled by a potentiometer

Answers: 2

body:
Personally I wouldn't bother with "groups". Just do simple maths:

    int velocity = analogRead(POT_MOT) - 512;

`velocity` now gives you a value from -512 to +511.

    bool dir = (velocity >= 0);

`dir` is now `true` for a positive value (0 is considered positive) or `false` for negative.

    velocity = abs(velocity);

`velocity` is now made positive if it is negative.

So you now have two variables: `dir` which sets the direction, and `velocity` which sets the speed.

Now you can "offset" it:

    velocity = map(velocity, 0, 512, -128, 255);

`velocity` is now changed to fit into the range -128 to 255. Anything above 0 is a valid speed, anything below is the "dead zone" and stops the motor.

    if (velocity <= 0) {
        // If it's negative or zero stop
        digitalWrite(motor_reg, LOW);
        digitalWrite(first_motor, LOW);
        digitalWrite(sec_motor, LOW);
    } else {
        if (dir) { // Pot was positive
            analogWrite(motor_reg, velocity);
            digitalWrite(first_motor, LOW);
            digitalWrite(sec_motor, HIGH);
        } else { // Pot was negative
            analogWrite(motor_reg, velocity);
            digitalWrite(first_motor, HIGH);
            digitalWrite(sec_motor, LOW);
        }
    }

Adjust the negative value in the map to change the size of the "dead zone".

body:
i would break out this into three or at least two parts:

1) a call to change the speed of the motor;
2) a call to read the potential meter setting;
3) a call to convert the potential meter setting into motor speed, optional.

the code would look like this:

      pot_setting = potsetting_read(); //read pot setting
      speed_setting = pot2spd(pot_setting); //convert pot setting to motor speed
      motor_setspeed(speed_setting); //set motor speed

it is not difficult to figure out each of the three functions.

the  more challenging of the three, to a newbie, is the one that sets the motor speed. there are many ways to do it, and I personally prefer to use timer interrupts.

the basic construct is to sequentially go through a set of pin states, where the duration of each state transition is controlled by a timer interrupt. by changing how fast that timer interrupt takes place, you change the speed in which the pins transition their states, thus motor speed.


body:
I wrote code in Arduino to read SMS. I have a problem with receiving it from serial.

    String str;

    void setup() {
      Serial.begin(9600);
      Serial.println("AT+CMGF=1");
      delay(1000);
    }

    void loop() {
      Serial.println("AT+CMGF=1");
      delay(2000);
      Serial.println("AT+CMGR=1");
      delay(5000);
      while (Serial.available()>0) {
        str = char(Serial.read());
        Serial.print(str);
      }
      Serial.println();
    }

I have an A6 GSM modem. When I read the serial I just get:

    +CMGR: "REC READ

Nothing more!

I should get something like this:

    +CMGL: 1,"REC READ","+989207201219",,"2017/08/26,21:54:56+05"
    test 20

I changed my code to:

    int readline(int readch, char *buffer, int len) {
      static int pos = 0;
      int rpos;
      if (readch > 0) {
        switch (readch) {
          case '\n': // Ignore new-lines
            break;
          case '\r': // Return on CR
            rpos = pos;
            pos = 0;  // Reset position index ready for next time
            return rpos;
          default:
            if (pos < len-1) {
              buffer[pos++] = readch;
              buffer[pos] = 0;
            }
        }
      }
      // No end of line has been found, so return -1.
      return -1;
    }

    void setup() {
      Serial.begin(9600);
      Serial.println("AT+CMGF=1");
      Serial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
    }

    void loop() {
      Serial.println("AT+CMGF=1");
      Serial.println("AT+CMGR=1");
      static char buffer[80];
      if (readline(Serial.read(), buffer, 80) > 0) {
        Serial.print("You entered: >");
        Serial.print(buffer);
        Serial.println("<");
      }
      delay(3000);
    }

But I get nothing.

title: Problem receiving full serial event+SMS

Answers: 2

body:
The arduino is a "small memory" device. So it probably does not have a big serial buffer. On say "linux on a PC" you get a 4096 byte buffer, but on an arduino, probably only say 16. Now as luck will have it "+CMGR: "REC READ" is precisely 16 characters....

From the code that I see, you seem to be sending commands to the modem and then reading/echoing them. I would have liked to use two different serial ports or something like that.

In any case, if it sort of works for those first 16 characters, remove all the delays and put one of them near the end of the loop() function. Remove the initial print to the modem in the setup function.

body:
I changed the code. so It works fine

    String inputString = "";         // a String to hold incoming data
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      Serial.println("AT+CMGF=1");
      Serial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
    }

    void loop() {

      Serial.println("AT+CMGR=1");

    }

    void serialEvent() {
        inputString = Serial.readString();
        Serial.println(inputString);
        delay(5000);
      }


body:
On Arduino forums, [there's a post][1] where someone improved the USB communication and made it super-fast. I don't understand how he did this, and I'm trying to recreate this, but failing.

## My test code

I made a simple program on Python for testing; here it's:

    import serial
    import sys
    import datetime

    ser = serial.Serial(
       port = 'COM9',
       baudrate = 26*115200, #biggest number acceptable by python
       parity = serial.PARITY_NONE,
       stopbits = serial.STOPBITS_ONE,
       bytesize = serial.EIGHTBITS
    )

    if ser.isOpen() == False :
       ser.open()
       if ser.isOpen() == False :
          print("Can't open serial port")
          sys.exit(1)

    start = datetime.datetime.now()
    s = b'abc'*10000
    ser.write(s)
    total_len = len(s)
    end = datetime.datetime.now()
    speed = total_len/(end - start).total_seconds()/1e6
    print("Speed: " + str(speed) + " MB/s")

And I made a simple Arduino program to read:

    char buf[500];

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

    void loop() {
      if (Serial.available() > 0) {
         Serial.readBytes(buf, 500);
      }
    }

With this, my best result was `0.2 MB/s` with my Arduino mega. However, on [that post][1], they reached 12 Mbit/s = 1.5 MB/s!!!!! This is insane!

## Atemmpting to achieve their result:

Apparently Arduino libraries are different than before, so just taking their code and putting it in my `arduino\avr\cores\arduino` directory doesn't work. So I started trying to edit the code myself. I'm a C++ dev, so supposedly this should be doable... but...

## The problem I faced

So eventually, the problem I faced was that there are two Serial communication modes (apparently) UART and CDC. The code from the forum uses CDC, while my Arduino IDE uses UART. I tried enabling CDC using:

    #define USBCON

but this lead to the error:

    error: #error "Targets with both UART0 and CDC serial not supported"

At this point I don't know how to continue, as I'm not a hardware expert. But I'd like your opinion on this whole thing:

1. Is it possible to get these speeds? How?
2. If it's, why is it not in the default Arduino library?
3. In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

  [1]: https://forum.arduino.cc/index.php?topic=391757.15

title: Super-fast USB communication; how is it possible?

Answers: 1

body:
> Is it possible to get these speeds? How?

Not without a 32-bit Arduino with a USB interface.

> If it's, why is it not in the default Arduino library?

Because you can't use it on an 8-bit Arduino without a USB interface.

> In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

Yes, get a 32-bit Arduino with a USB interface such as the Arduino Due that the poster of that thread used.


body:
As part of a larger project, I would like to be able to control a set of 8-10 PWM signals remotely, from a smartphone at a distance of 10 meters or more.  I will probably convert the PWM signals to analog voltages, and reduce their voltage swings to more like 0-1v, using a resistor divider and RC filter; they will drive high impedance loads in the remainder of the project.  I’d write an app for the smartphone allowing user control over the duty-cycle of each PWM signal (and thus the analog signal levels).

It seems to me that the way to go is Arduino, interfaced to the phone with Bluetooth.  I'd need one of the higher end Arduinos to get enough PWM signals (the basic ones like Uno only have 6 PWM outputs).  Software-generated PWMs are probably not high-frequency enough, as I’d like the filtered analog signals to be as ripple-free as possible. There seem to be several ways to interface Bluetooth to Arduino, such as the HC-05.

If people here concur with this approach, I shall move this question to the Arduino forum.

`

title: Simplest/best way to control a set of 8-10 PWM signals from a smartphone

Answers: 1

body:
HC-05 is rated to about 9m so it wouldn't necessarily meet your requirement. The ESP8266 (example of one implementation called the [Node MCU][1]) can output PWM on any of the 0-16 pins. It can easily implement a web server which would let you control your outputs via 8026.11 (wifi). It also means you don't need to build anything for the phone/ tablet/ PC just use a web browser. The duty cycle could be set through the web server on the ESP. The ESPs are around the same price as an Arduino.

I've used the HC-05 with an arduino. It works very well, though not very far. For the Android side I used [app inventor][2] which is extremely easily to use for bluetooth.

  [1]: https://en.wikipedia.org/wiki/NodeMCU
  [2]: http://appinventor.mit.edu/explore/


body:
#Solution:#

Majenko properly pointed out that I was trying to write across page boundaries and either overwriting or skipping blocks of the EEPROM when I did. This updated write function checks for a page boundary and splits the write into two writes if it is going to write over one.

    void writeEEPROMPage(long eeAddress) {
   int writes = incr;
   bool overflow = false;

      //check for page overrun, adjust writes to fill page and set flag if overrun
   if((eeAddress % 128 + incr) > 127) {
     writes = 128 - eeAddress % 128;
     overflow = true;
   }
   Wire.beginTransmission(EEPROM_ADR);

   Wire.write((int)(eeAddress >> 8)); // MSB
   Wire.write((int)(eeAddress & 0xFF)); // LSB
   //Write bytes to EEPROM
   Wire.write(rwBuffer, writes); //Write the data
   Wire.endTransmission(); //Send stop condition
   eeAddress += writes;

   if(overflow) {
     delay(5);
     Wire.beginTransmission(EEPROM_ADR);

     Wire.write((int)(eeAddress >> 8)); // MSB
     Wire.write((int)(eeAddress & 0xFF)); // LSB

     //Write remaining data to new page
     Wire.write(rwBuffer + writes, incr - writes);

     Wire.endTransmission();
     eeAddress += incr - writes;
   }
 }

#Problem:#

I am currently working on a project to record sensor readings to a 24FC512 512kb I2C EEPROM and have been teaching myself to read and write properly to this chip using an Arduino Uno. I am having a problem: when I write too many bytes in one I2C cycle, some bytes of data are skipped and not written.

In theory, I believe I should be able to write up to a 128-byte page to the EEPROM and the buffer in the Arduino Wire library should allow me to write up to 32 bytes (including address) in one transmission without modification. However, when I write more than a certain number of bytes, typically 16, and then read back the data from the EEPROM, I notice that the write commands seem to have skipped part of the write.

For instance, when trying to clear pages of 20 bytes at a time using 0xF0 to fill the space I get this result in the first few lines in blocks of 20:

    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88
    +12 lines of F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  55  66  77  88  99  AA  BB  CC
    +12 lines of F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  99  AA  BB  CC  DD  EE  FF  00
    +5 lines of F0
    F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88

The section that has not been cleared matches the original pattern in that location. When I reduce the page size to 16 bytes, the problem goes away and everything is written correctly. The uncleared pattern is also periodic after the first three lines, running 12 lines, error, 12 lines, error, 5 lines, error for the rest of the data. When tried with 30 bytes per transmission, it's periodic by 3-8-3 when organized in lines of 30. In all cases the errors have been at the end of each page of transmission.

This has become very frustrating because I'd like to get the data written to the EEPROM in as little time as possible so I can get a good sensor sample rate (currently 24 bytes per sample) and have time to run other functions. Ideally I'd be able to write every 5 ms to increase the sampling rate to the maximum supported by the EEPROM, so I need to solve this problem.

Here is the code I am using to clear and read the contents of the EEPROM. The variable incr holds the size of the writes I want to make, and pin 12 decides whether the program will read the EEPROM (high) or clear the EEPROM (low). I write data to the EEPROM with the commented out array to run my tests. It is based on example programs for EEPROM from Sparkfun.

    #include <Wire.h>

    #define EEPROM_ADR 0x54

    const int incr = 30;
    byte rwBuffer[] = {
      0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
      0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
      0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
      0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0
    };

    void setup() {
      pinMode(13, OUTPUT);
      pinMode(12, INPUT);
      Wire.begin();
      Wire.setClock(400000);
      long currentSpot = 0;
      if (digitalRead(12)) {
        dumpEEPROM();
      } else {
        while (currentSpot < 64000) {
          writeEEPROMPage(currentSpot);
          currentSpot += incr;
          delay(7);
        }
      }
    }

    void loop() {
      digitalWrite(13, !digitalRead(13));
      delay(500);
    }

    void writeEEPROMPage(long eeAddress) {
      Wire.beginTransmission(EEPROM_ADR);
      Wire.write((int)(eeAddress >> 8)); // MSB
      Wire.write((int)(eeAddress & 0xFF)); // LSB
      //Write bytes to EEPROM
      Wire.write(rwBuffer, incr); //Write the data
      Wire.endTransmission(); //Send stop condition
    }

    void dumpEEPROM() {
      long i;
      int j, readnum, timer = 0;
      Serial.begin(115200);
      timer = millis();
      for (i = 0 ; i < 64000 ; i += incr) {
        //Read all bytes from EERPOM
        readnum = readToBuffer(i);
        for (j = 0; j < incr; j++) {
          if (rwBuffer[j] < 0x10)
            Serial.print("0");
          Serial.print(rwBuffer[j], HEX);
          Serial.print("  ");
        }
        Serial.println();
      }
      timer = millis() - timer;
      Serial.print("Full data dump took ");
      Serial.print((float)timer / 1000, 3);
      Serial.println(" seconds.");
      Serial.end();
    }

    int readToBuffer(long address) {
      int i = 0;
      Wire.beginTransmission(EEPROM_ADR);
      Wire.write((int)(address >> 8)); // MSB
      Wire.write((int)(address & 0xFF)); // LSB
      Wire.endTransmission();
      Wire.requestFrom(EEPROM_ADR, incr);
      for (i = 0; i < incr && Wire.available(); i++) {
        rwBuffer[i] = Wire.read();
      }
      return i;
    }

title: Problems Writing and Clearing 24FC512 EEPROM using Arduino Uno

Answers: 2

body: Right after each `Wire.endTransmission();` you need to insert a `delay(5);`. The errors you see could be write-related, and/or read related too. You have to let the EEPROM chip process the address request before you start dumping/reading.

body:
You are trying to do a page write across a page boundary.

> The write control byte, word address and the first data
byte are transmitted to the 24XX512 in the same way
as in a byte write. But instead of generating a Stop
condition, the master transmits up to 127 additional
bytes, which are temporarily stored in the on-chip page
buffer and will be written into memory after the master
has transmitted a Stop condition. After receipt of each
word, the seven lower Address Pointer bits are internally
incremented by one. If the master should transmit
more than 128 bytes prior to generating the Stop condition,
the address counter will roll over and the previously
received data will be overwritten. As with the byte
write operation, once the Stop condition is received, an
internal write cycle will begin

You are sending blocks of 30 bytes (`incr = 30`). You have 128 byte pages.

* 128 / 30 = 4.267 writes per page. The 5th write spans pages. But, in a big bold NOTE in the datasheet:

> Page write operations are limited to writing
bytes within a single physical page,
**regardless** of the number of bytes
actually being written. Physical page
boundaries start at addresses that are
integer multiples of the page buffer size (or
‘page size’) and end at addresses that are
integer multiples of [page size – 1]. If a
Page Write command attempts to write
across a physical page boundary, the
result is that the data wraps around to the
beginning of the current page (overwriting
data previously stored there), instead of
being written to the next page as might be
expected. It is therefore necessary for the
application software to prevent page write
operations that would attempt to cross a
page boundary.

So you write 4 blocks to the first page, then the 5th block fills in the end of the first page *then goes back to the start of that page and overwrites what has already been written earlier*. Your next page then starts part way through the next block skipping a chunk that you cannot now get to.

You must either do your writes in blocks of an integer division of 128 (so 16 bytes is the largest you can do) or manually detect a page boundary and split your block write into two separate writes - one to finish filling the first page and the next to start filling the next page.


body:
This is code about a keypad lock. The user can unlock the device by entering the secret code. To lock it again they press "#" or "*".

I want to let the green LED turn on for about 0.5 seconds then return to the first line of the loop: `char key = keypad.getKey();`.

The problem is that this code makes the green LED turn on forever after we enter the correct secret code or until we enter "#" or "*".

    void loop() {
      char key = keypad.getKey();
      if (key=='*'||key=='#') {
        position = 0;
        setLocked(true);
      }
      if (key==secretCode[position]) {
        position ++;
      }
      if (position ==3) {
        setLocked(false);
      }
      delay(100);
    }

    void setLocked(int locked) {
      if (locked) {
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
      } else {
        digitalWrite(redpin, LOW);
        digitalWrite(greenpin, HIGH);
        delay(500);
      }
    }

title: How to "break" a function we made?

Answers: 3

body:
I may be missing something, but couldn't you just modify your `setLocked` function?

    void setLocked(int locked) {
      if (locked) {
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
      } else {
        digitalWrite(redpin, LOW);
        digitalWrite(greenpin, HIGH);
        delay(500);
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
      }
      return;
    }

body:
I was looking at your `loop()` and it have some problems, like not counting how many digits did the user input and locking upon receiving a single "#" a

Here is some better way:

    char secretCode[] = "1234";
    char inputCode[] = "xxxx";
    int position = 0;

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

    void loop() {
      char key = keypad.getKey();

      if (key == '*' || key=='#') {
        int i = 0;
        //  With 4 input digits, now we compare against secret code.
        while (i < sizeof(inputCode) && inputCode[i] == secretCode[i]) {
          i++;
          }
        //  Set locked only if 4 digits are the same.
        setLocked(i == sizeof(inputCode));
        //  Reset input code array.
        position = 0;
      } else {
        //  Key adding digits to the input code.
        inputCode[position++] = key;
        if (position == sizeof(inputCode)) {
          position = 0;
        }
      }
      delay(100);
    }

    void setLocked(int locked) {
      if (locked) {
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
      } else {
        digitalWrite(redpin, LOW);
        digitalWrite(greenpin, HIGH);
        delay(500);
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
      }
      return;
    }

body:
The problem is that when the device is unlocked with the correct code, you turn the green LED on wait for 0.5 seconds and then you don't turn it off again. So the simple answer would be [sempaiscuba's answer][1].

Personally, I like the fact that the red LED indicates that the device is locked and the green LED indicates that it is unlocked.

The problem that I see with your code is that if the user enters an incorrect number, it doesn't reset, allowing any amount of wrong numbers until it sees the right number. This means that I could come along and press the keypay randomly and after a while I would have pressed every digit in the secret code and it would unlock.

Think of the problem as a state machine. You start with 0 digits correct (ie `position==0`). If at any time the user presses an incorrect digit (or the * or #), the state machine will reset back to 0 digits correct state. If the user enters the first digit correctly then it progresses to the 1 digit correct state (ie `position==1`). And so on until all of the digits are correct and the device is unlocked. Due to the simplicity of this state diagram it can be accomplished using a few if statements.

<!-- language-all: lang-C++ -->

    int position = 0;
    char secretCode[] = "7890";
    char inputCode[] = "????";      // This can be any character and just acts as a placeholder
    boolean newKey = false;

    void setup()
    {
        setLocked(true);
    }

    void loop()
    {
        char key = keypad.getKey();

        // Only process when a new key has been pressed
        if ((key != NO_KEY) && newKey)
        {
          newKey = false;  // Don't enter this if statement again if the key is being held down (used for debounce)

          if ((key == secretCode[position]) && (position < 3))
          {
              // The correct key has been pressed
              position ++;
              if (position == 3)
              {
                // Correct code has been entered (all 4 digits)
                setLocked(false);
              }
          }
          else
          {
            // It must be a wrong key (including * & #)
            // Or the device is unlocked and the user is locking it again.
            setLocked(true);
          }
        }
        else
        {
            // Key has been released (used for debounce)
            newKey = true;
        }
    }

    void setLocked(boolean locked)
    {
        if (locked)
        {
            position = 0;
            digitalWrite(redpin, HIGH);
            digitalWrite(greenpin, LOW);
        }
        else
        {
            digitalWrite(redpin, LOW);
            digitalWrite(greenpin, HIGH);
        }
    }

Once unlocked, all you have to do is press any key to lock it again.

Resources:
http://playground.arduino.cc/Code/Keypad

  [1]: https://arduino.stackexchange.com/a/44146/19409


body:
This code below:

    void setup() {
      #if defined(__AVR_ATmega168__)
        // 62.5KHz PWM for the ATMega168 -> only on Arduino pins 9 and 10

        // set prescaler to 1
        // (sbi means "set bit register", cbi means "clear bit register")
        cbi(TCCR1B, CS12);
        cbi(TCCR1B, CS11);
        sbi(TCCR1B, CS10);

        // set fast PWM
        cbi(TCCR1B, WGM13);
        sbi(TCCR1B, WGM12);
        // with fast PWM, the frequency is (CLK/256*prescaler) = 16MHz/256 = 62.5KHz
        // with slow PWM, it is half that speed (31KHz)
      #else
        // 22KHz for the ATMega8 (this is a low frequency)
        TCCR2 = ((TCCR2 & ~0x07) | 0x01); //<ERROR POINTS HERE!
        TCCR1B = ((TCCR1B & ~0x07) | 0x01);
      #endif
    }

when verify, generates an error:

    In function 'void setup()':
    pwm-control-1:185: error: 'TCCR2' was not declared in this scope
    TCCR2 = ((TCCR2 & ~0x07) | 0x01);
    ^
    exit status 1
    'TCCR2' was not declared in this scope

So far i know this code generates pwm at pin 9 or 10, and designed for ATmega168 or ATmega8. The code came with a .pde extension and I opened it on 'Arduino: 1.8.3' and saved as an .ino file.

Can any one please tell me how to convert this code to work with 'ATmega328P-PU' and for the latest Arduino IDE. And also if there anything else to consider running with this code

I'm not an expert in pwm and timer/controls in micros... just started to learn..

Note: I've only shown the necessary part of the code

title: Arduino - Getting error - 'TCCR2' was not declared in this scope

Answers: 3

body:
The problem is because TCCR2 is not declared, as there is no register with that name. Maybe you wanted to configure the timer 2, i.e. you meant TCCR2A or TCCR2B instead of TCCR2.

EDIT: analyzing your code, you should definitely write TCCR2B.

body:
Looks like this code is pretty old. It's assuming that any Arduino that isn't using an ATmega168 is using an ATmega8. In reality, the ATmega8 hasn't been used on any Arduino boards in the last ten years or so -- it's pretty much obsolete.

The easiest fix will be to remove the non-'168 branch (between `#else` and `#endif`), and make the '168 branch default (remove the `#if` line). This will probably still fail on ATmega32U4 boards, but at least it'll now work on ATmega328 hardware.

body: Check the datasheet to see if there is a tccrb. Maybe for your device, it is tccra, tccrb, or teerc, ....


body: I am working on a project with an Arduino Uno. I want to know if the latitudes and longitudes can be input to the Arduino for the Arduino to move to that particular location. If it's possible then which sensors or actuators are to be used? Please also mention some references for me to read and collect the required information.

title: GPS and Arduino

Answers: 2

body:
See this site, for a practical example:

http://www.instructables.com/id/Arduino-Powered-Autonomous-Vehicle/

body:
OK, notwithstanding Majenko's excellent suggestion in the comments above, I played around with Arduino and GPS, so I can probably offer a few pointers.

**First, GPS**:

All the GPS modules that I have played with give out a series of standard strings of information or "sentences". These sentences are defined by the [National Marine Electronics Association (NMEA) protocol][1]. You are going to want to spend some time learning how to use this information.

The most commonly used string in an NMEA sentence is **$GPRMC**. From this you can extract date, time and position. But there is a lot more useful information in an NMEA sentence, so do your research.

When you have decided which GPS module you want to use, just use Google to search for sample Arduino code specific to that module. That should be enough to get you started.

**On the subject of GPS Modules:**

There are many available. Just Google search for "Arduino GPS module".

They vary in price from a few GB pounds to well over a hundred GB pounds. It all depends on what you need from it, and what you can afford. Personally, I got very good results from cheap (~ £5 GB) Neo-6M modules (like the one shown here) with some mobile robots I was experimenting with.

![neo-6m][2]

Now, I've just typed "*Neo-6m GPS Arduino*" into Google, and one of the first sites was this [Instructable][3], which has more than enough information to get you going with this combination.

**Path planning**

Yes, you could give a robot a GPS and a target location and have it plan a route and move to the new location.

Sounds easy doesn't it?

It isn't.

It really, *really* isn't!

Path planning is a complicated discipline. There is an introductory course on [Computational Motion Planning][4] available (free to audit last time I looked) on Coursera if you are interested. It's part of a Robotics "Speciality", so depending on your existing skills, you might want to work through the modules in sequence.

[If you do decide to do all the modules in the Speciality, I shared [my notes][5] for some of the modules via my Scribd account. Some of these also contain elements on motion planning. (***Be warned***, some of them also contain a lot of maths!)]

The best practical advice I can give is to start small.

I tested my robots in a local park, over distances measured in tens, rather than hundreds of metres. I then introduced obstacles (trees) in a different part of the park, and things got a whole lot more interesting! (Not least, of course, because GPS really doesn't like trees! So you have to use other sensors when the robot isn't receiving data from the GPS ...).

And if you think that's complicated, just wait until you introduce "moving obstacles", like people, dogs, cars, bicycles, ...!

Hopefully that will give you some pointers to get you started. When you hit problems with your code (and you're almost certainly going to hit problems with your code!), sites like this will be a godsend.

I really wish Arduino: SE had been around back when I was banging my head against the proverbial wall trying to work out why my code wasn't doing what I expected it to!

  [1]: http://www.gpsinformation.org/dale/nmea.htm
  [2]: https://i.stack.imgur.com/GrgHw.jpg
  [3]: http://www.instructables.com/id/How-to-Communicate-Neo-6M-GPS-to-Arduino/
  [4]: https://www.coursera.org/learn/robotics-motion-planning
  [5]: https://www.scribd.com/lists/15471316/Aerial-Robotics-notes


body:
How do I transfer a series of byte[256]-buffers to a server with an ENC28J60 Ethernet adapter? I get blocks of `uint8_t` from an Arducam camera module and I'd like to transfer them to a host. Does somebody have an idea how to solve that? I asked a previous question regarding that topic but now new issues arrived.

This is how the array is filled:

    uint8_t temp = 0, temp_last = 0;
    byte buf[256];
    length = myCAM.read_fifo_length();
    while (length--) {
      temp_last = temp;
      temp =  SPI.transfer(0x00);
      if ((temp == 0xD9) && (temp_last == 0xFF)) {
        buf[i++] = temp;
        is_header = false;
        i = 0;
      }
      if (is_header == true) {
        //Write image data to buffer if not full
        if (i < 256)
          buf[i++] = temp;
        else {
          i = 0;
          buf[i++] = temp;
        }
      }
    }

title: Transfer byte-buffer with ENC28J60

Answers: 1

body:
Assuming you are using the EtherCard library you can send a UDP packet with:

    ether.sendUdp(packet_data, length, srcPort, hisip, dstPort );

Assuming you have already set up your source port and have the destination IP address and port in `hisip` and `dstPort`.

The prototype for the function is:

    void sendUdp (char *data,uint8_t len,uint16_t sport, uint8_t *dip, uint16_t dport);

The example `udpClientSendOnly.ino` with the library shows you UDP sending in action.


body:
I have a Leonardo with a Yun shield, and I would like to be able to control the arduino with a windows form app, but thats besides the point for now at least. Currently, I am using putty and the commands Telnet Localhost 6571. However, I would like to avoid doing that and I was wondering if anybody new how to communicate with the arduino from port 22 at the yun's IP, rather than connecting to the yun and then to the remote local machine. That or I am missing something entirely!

This is the code I am using to try and access the console port of the Leonardo:

<!-- language: lang-java -->

    namespace ConsoleApp2
    {
        class Program
        {
            static void Main(string[] args)
            {
                //connect to arduino
                ConnectionInfo ConnNfo = new ConnectionInfo("10.1.1.211", 22, "root", new AuthenticationMethod[] { new PasswordAuthenticationMethod("root", "123456789") });
                using (var sshclient = new SshClient(ConnNfo))
                {
                    sshclient.Connect();
                    //connect to console port of arduino
                    TcpClient tcp = new TcpClient("localhost", 5671);
                    sshclient.Disconnect();
                }
                Console.ReadKey();
            }
        }
    }

Thank you

title: Linux SSH command for Arduino Console

Answers: 1

body:
The console port is only listening on 127.0.0.1 (for security), so only the Yun itself can connect to the console.

You can weaken security and open the port up to the entire local network by editing the file `/usr/lib/python2.7/bridge/console.py` and change the value `127.0.0.1` to `0.0.0.0`.

Any machine on your local network will then be able to connect directly to port 6571.


body:
I'll like to code for a game, and it'll come with a stop option that allows the player to exit/restart the game.

How should I code for that stop button? Do I put it in a separate while loop under the void loop?

title: Coding for a stop button

Answers: 3

body:
There are lots of possible approaches. One possibility would be to set up your code something like this:

    enum { STOPPED, PLAYING } flag;

    void setup() {
      // setup stuff ...
      flag = STOPPED;
    }

    void loop() {
      while (flag == STOPPED)
      {
        // wait for start button
        if (start button pressed)
        {
          // initialise the game ...
          flag = PLAYING;
        }
      }

      while (flag == PLAYING)
      {
        // play the game
        if (stop button pressed)
        {
          flag = STOPPED;
        }
      }
    }

body:
One of the easiest ways to restart your game is to use the inbuilt reset line. The Arduino Uno/Due/M0/101 has a physical reset button next to the USB connector. For some of the other baords like the Arduino Mega, it is closer to the chip in the middle of the board.

The reset line is held high by a pull up resistor. This button shorts the reset pin to Gnd, resetting the microcontroller.

Once reset, the microcontroller starts up again as if it has just been powered on. This has the advantage of saving on adding code to handle the game being reset.

body:
If you code your loop without delay() or busy loops then it is pretty easy:

    void loop(){

        if(DigitalRead(RESET_BUTTON)){
           // Reinitialize game state

        }

        //rest of game logic.

    }


body:
I have written code to see values of a 5K potentiometer from 0 to 1023. Whenever I rotate the knob, the value should change from 0 to 1023. I have connected the potentiometer to the Arduino's pin A1, but there is a problem with readings. Whenever I am rotating the potentiometer's knob, the serial port is only showing 1023. Please help.

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

    void loop() {
      int sensorValue = analogRead(A1);
      Serial.println(sensorValue);
      delay(500);
    }

title: Problem reading in Arduino serial port with 5K potentiometer

Answers: 2

body:
It sounds like it might be a wiring problem. Check that you have the potentiometer connected correctly. Your circuit should look something like this:

![single potentiometer circuit][1]

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

body: Disconnect the pot and take some readings. You should get some random values near zero. That would mean you're not connecting the leads right or the swinger is stuck at one end.


body:
I have this Arduino Nano, Ethernet shield W5100 and RC522 as card reader. They are sharing pins D13, D12, D11, D10 is SS pin for W5100 D8 is SS pin for RC522. Problem is with pin D12, like it doesn't share it.

For example if I unplug D12 from W5100 RC522 reader works, if I wire it back it doesn't work anymore. W5100 works no matter if RC522 is wired or not, so problem would be somehow with pin D12.

Does anybody have some ideas, what I'm doing wrong right here?

title: Arduino Nano + RFID RC522 + Ethernet shield W5100

Answers: 1

body:
I had almost exactly this situation with one of my projects.

The problem is that some Serial Peripheral Interface (SPI) devices don't properly put the MISO pin into high-impedance when SS is pulled high. I eventually resolved this by placing a tri-state buffer in the MISO line for each of the SPI devices.

I used a [74HC125][1] (4-channel tri-state buffer).

This is the page on [Better SPI Bus Design in 3 steps][2] that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).

  [1]: https://assets.nexperia.com/documents/data-sheet/74HC_HCT125.pdf
  [2]: https://www.dorkbotpdx.org/blog/paul/better_spi_bus_design_in_3_steps


body:
I'm developing on the Arduino platform (ESP8266 with USB -> serial) and sometimes the USB port that is being used stops working and gets frozen. Then I need to plug the device into another USB port. It happens again and once all the USB ports stop working I have to restart the machine, which is really annoying.

As far as I remember there is a command that can restart the USB subsystem individually, but I can't remember. How to restart USBs without restarting the entire system? Thanks.

I'm using Mac OS X Sierra.

title: How to restart USB subsystem?

Answers: 2

body:
You are using a USB to UART adaptor. The Arduino has no concept of what that is - it just sends and receives UART data. The adaptor is completely separate and the Arduino can do absolutely noting at all with it.

If you are powering the whole circuit through that adaptor it may well be that it only requests 50mA from the computer. If you draw more than that (which you most likely are) the computer is free to shut the port down. It sounds like that may be what is happening.

What can you do? Well, two things:

1. Use an adaptor that requests enough current for your needs (may be hard to find)
2. Power your circuit separately using another power source.

Of the two I would suggest external power.

body:
You're probably thinking of `kext[un]load`.

    sudo kextunload /Library/Extensions/SiLabsUSBDriver.kext
    sudo kextload /Library/Extensions/SiLabsUSBDriver.kext


body:
I'm using a USB Barcode scanner connected via a USB shield, I'm able to get the readings from the barcode using [this][1] example, After getting this readings, I'd like to save it to an SD card but the SD card won't initialize since the barcode also uses SPI, how can I deactivate the ICSP in order to activate the SD card? Or how to switch between multiple SPI slaves?

 [1]: https://github.com/felis/USB_Host_Shield_2.0

title: Switching between SPI Devices when one is an SD card

Answers: 2

body:
with SPI there is an implicit slave select pin on each device that must be pulled low to enable the device.

Connect each slave select pin of the SPI device to their own unused digital pin on your arduino and keep it pulled high until you want to talk to the slave.

However not all SPI devices will properly put the MISO pin into high impedance when SS is pulled high so you may need to use a tristate buffer on that pin or use a multiplexer.

When adding your own tristate buffer (for example a HS125) you need to connect each MISO pin of the SPI device to the input of a buffer, the slave select is then connected to the output enable pin of the tristate. The outputs of the buffers can be connected together along with the MISO pins of the devices that do properly go high impedance to the MISO of the master.

When using multiplexers there are 2 options:

1. You can daisy chain 2:1 multiplexers by connecting the MISO of the device to the 0-input of the mux and the Slave select to the select input pin of the mux.

2. you can use a >2 multiplexer to select the correct MISO line based on the address of a set of S lines. Then with a decoder you can provide the actual SS signal to the SPI device. This way you only need 2 SS pins for 4 SPI devices.

body:
Refer to the schematic below for a visual explanation of what is explained in this thread regarding a tri-state buffer.  I have used this circuit successfully on a PCB.[![enter image description here][1]][1]
I got this schematic from:
© 2017 Vishnu M Aiea. www.vishnumaiea.in

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


body:
I have connected my arduino according to the schematics in the image, with a few additions.

**The setup**

1. A DC motor (water pump) drawing power from Vin, going to ground via a transistor based in A0 analog output. Between the transistor and A0 is a 270 ohm resistor. In parallel to the motors poles is a diode, for protection.

2. A 3,1" (4x20) LCD screen with an I^2C chip (draws 5V, A4 and A5 and GND)

3. A Potentiometer directly on the I^2C chip LED pins (replacing the jumper) - for control of the light intensity. (Vin and middle pin of pot, gnd unconnected)

4. A Potentiometer connected to A1, 3,3V and GND.

**Code description:**
Using the Timer and the LiquidCrystal_I2C library,
Once every other second the LCD is refreshed
Once every day the water pump is started with an analogWrite(A0, HIGH) and it runs for 1-60 seconds based on the potentiometer setting.

**The issue.**

It seems the output of A0 does not deliver enough voltage to trigger the pump. This is a new error, before I got the screen, it ran the pump fine.

I suspect one of three things. 1: I have broken something in the arduino power regulator, and the voltage outputs on analog pins are lower than they should be (or their ability to supply current) -> Must get new arduino. 2: I have somehow saturated the ground pin or there is a connection issue. 3: The LCD display is drawing too much current. (Leading to either 2 or 1, but won't be fixed by getting a new arduino)

**What have I already tried**

I have tried, with the arduino connected via mains to short it between 3,3V and the transistor base, and then it runs. So the transistor is OK, the pump is OK. I have tried to map the output to another analog pin to display the value of this pin while the program is running, and it does display a value while the pump is supposed to be running, so it is doing something. I have used a multimeter to measure the pins, but I really don't know what "normal" is so I decided to stop fiddling around with that. I have also tried using other analog outputs (excepting 4 and 5, they are claimed by the lcd I^2C logics)

Can anyone of you please give me some pointers in the right direction, to help me to determine the error in question? What should I try?

Disclaimer, due to having the normal issues of life, love and the fact that a day only has 1440 minutes, I usually only have time to work on my pet projects during weekends...

If this question is not relevant or poorly written, please let me know, I'll try to clarify (or delete it).

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

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

title: Analog output low voltage issue, how to troubleshoot

Answers: 2

body:
why analogWrite? analogWrite parameter values are 0 to 255 (or 1023) so analogWrite(pin, 1) is close to 0.

analogWrite is PWM on digital ports and doesn't work on analog ports
[analogWrite reference][1]

use digitalWrite

  [1]: https://www.arduino.cc/en/Reference/AnalogWrite

body:
The analog pins are for analog **input** not output. You can only use them for *digital* output.

Change

    analogWrite(A0, HIGH)

to:

    digitalWrite(A0, HIGH)

`analogWrite()` can only be used on PWM capable pins (the ones marked with `~`). On any other pin it sets the pin HIGH if the analog value > 127 and LOW if the analog value <= 127.

Since you are writing HIGH, which is equal to 1, the output is LOW because 1 < 127.


body:
I have a PN532, so it's capable of both reading and writing. I've used it for a few perfectly functional things, but I want it to authenticate based on the contents (for example 1024 bytes) of a tag.

I'd generate some pseudorandom data, possibly on my PC, and write that into each card, and use a checksum of that as the key.

Should I just stick with the standard authentication of tokens, or is this a worthwhile alternative method? The UIDs of the tokens are not interesting for authentication.

If worthwhile, what checksumming algorithms should I use? If not, would someone care to explain how I can program the memory of tokens, and how to use that in addition to UID for auth?

Thanks in advance.

title: RFID access system with PN532 reader

Answers: 1

body:
First off, you don't want to use a checksum for authentication.

A checksum can be thought of as a hash with a very small size. The smaller the size of a hash the less unique it is. The less unique it is the more likely it is that incorrect data will generate the same hash and authenticate someone it shouldn't.

For instance, a 32 bit checksum (hash) of 1kB data (8192 bits of information) is a 256-fold reduction in the uniqueness of the value. At 32 bits you get 232 unique values. With 8192 bits you get 28192 possible values. I can't calculate how many values that actually is, but as you can imagine there will be many billions of billions of combinations that would all equate to the same checksum.

If you must use a checksum then make it an actual recognised hash. For instance an MD5 (considered weak by today's standards) has 128 bits. SHA-256 has, as you would imagine, 256 bits.

However calculating these hashes on an Arduino is not a simple matter owing to a lack of memory. Not impossible, but not that easy.

If you're going as far as to use such large amounts of data for authentication and using heavy mathematical routines to create a hash you may as well go the whole hog and use a proper cryptographic key pair.

One method would be to encrypt the UUID of the card off-line and store the encrypted result on the card - that data would then be unique to that card and tied to it - you wouldn't be able to clone the card unless you could clone the UUID as well.

Then either the UUID is read by the Arduino and also encrypted using the same key and if the results match authentication succeeds. Or the encrypted value is decrypted by the Arduino and compared to the UUID to see if they match. Which you choose depends on if you have asymmetric or symmetric encryption (the former is more like a hash but requires the encryption key to replicate it whereas a hash doesn't).

You can also include other information with the UUID, such as the name of the card owner (for identification purposes), etc - as long as you are able to already know that data to create the cryptographic has to compare with what is on the card.


body:
I am using an Arduino Uno and an MCP23008 GPIO pin expander, I have a momentary button connected to GPIO 2 on the MCP23008 and an LED light connected to GPIO 1 on the MCP23008. What I want is for the LED to turn on when the button is pressed down, and off otherwise. The code I currently have is this:

       #include "Wire.h"       //import Wire library
       byte inVal;             //declare byte variable

       void setup() {

          Serial.begin(9600);
          Wire.begin();
          Wire.beginTransmission(0x20);   //MCP23008 i2c addr
          Wire.write(0x00);               //MCP23008 internal register addr for I.O.dir
          Wire.write(00000010);           //set all pins as output, except for #2 as input
          Wire.endTransmission();
        }

        void loop() {

          Wire.begin();
          Wire.beginTransmission(0x20);   //MCP23008 i2c addr
          Wire.write(0x09);               //MCP23008 internal register addr for GPIO access
          //Wire.write(0xFF);             //set all output pins to HIGH, commented out for now.
          Wire.endTransmission();
          Wire.requestFrom(0x20,1);       //get one byte of input input from MCP23008
          inVal=Wire.read();              //set pyte as variable

          //Serial.println(inVal,BIN);    //output byte to serial monitor, commented out for now

          Serial.println(bitRead(inVal, 1)); //output second bit from byte(1 or 0, for HIGH or LOW, depending on the press of the momentary button.
          if((bitRead(inVal, 1)==1))      //if the bit from the button is high,
          {
            Wire.beginTransmission(0x20);
            Wire.write(0x09);
            Wire.write(0xFF);             //then set all output pins as HIGH
            Wire.endTransmission();
          }

          else if((bitRead(inVal, 1)==0))  //if the bit from the button is low,
          {
            Wire.beginTransmission(0x20);
            Wire.write(0x09);
            Wire.write(0x00);             //then set all output pins as LOW
            Wire.endTransmission();
          }
        }

I don't know as much Arduino as I do Python, and I have even less experience with i2c connections and the Wire library, but this looks to me like it should be working.

The bit printed on the serial monitor is HIGH, until I press the button once, then it stays LOW forever until I modify and re-upload the code to the Arduino.
Not sure what's going wrong here. Anything helps, thanks.

title: Arduino Wire communication with MCP23008 GPIO pin expander to turn on an LED with a button press

Answers: 1

body:
I see one major thing wrong at first glance:

      Wire.write(00000010);           //set all pins as output, except for #2 as input

That doesn't set GPIO 1 (which you call number 2 - counting starts at 0 not 1) to be an input, that sets GPIO 3 (number 4) as an input.  Numbers starting with `0` are octal, not binary. For binary the prefix is `0b`:

      Wire.write(0b00000010);           //set all pins as output, except for #2 as input

And then you read using:

    bitRead(inVal, 1)

which would have read GPIO 1 which is configured as an output.

So you have a switch on GPIO 1 which is an output, which you then drive high (causing a short internally which can damage the pin), and as a result you drive the pin HIGH internally. Now it's always high, so a read of the pin sees the HIGH you are driving from it. Hence it gets stuck at 1.

Fixing your IODIR write should help solve that problem.


body:
I am working on an assignment that converts a reading of force into pounds and then finds the maximum and average of all the values received

This is my code:

    void setup()
    {

     // put your setup code here, to run once:

     Serial.begin(9600);

      // declare the outputs and inputs
      pinMode( 0 , INPUT);

      //figure out what pin the reading is going to be input to

      fsrReading = analogRead( 0 ) ;
      //the # is the same pin used to get input

      //or use analogRead ( # ), it depends if the pin input is on the analog side of the arduino

      // should this be under the while loop or here?

      //list functions here
      long ForceInPounds(long);
      long FindMax(long);
      long FindAvg(long);

      //declaring variables of functions
      FM = FindMax(new long);
      FA = FindAvg(new long);

            Serial.println("The max value is:");
            Serial.println(FM); //calls FindMax function

            Serial.println("The average value is:");
            Serial.println(FA); //calls FindAvg function

      }

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

     int counter1= 0;

      while (counter1< 100)
      //runs test 100 times

      //should I just make this a function? instead of embedding it in the void loop

     {
          Serial.print("Analog reading = ");

          Serial.println(fsrReading);

          //declaring variable of function used in this segment
          FiP = ForceInPounds(new long);

          Serial.print("Force in Newtons:");
          Serial.println(FiP); //calls ForceinPounds function

          counter1 ++;
      }

    }

    //FUNCTIONS

    long ForceInPounds(const long)
    // converts recorded voltage to resistance to conductance to force to pounds
    {
     fsrReading = fsrVoltage;

     if (fsrVoltage== 0)
     {
       Serial.print("No pressure");
     }
     else
     {
       fsrResistance = 5000.0 - fsrVoltage;
       //convert voltage to resistance
       fsrResistance *= 10000.0;
       fsrResistance /= fsrVoltage;
       fsrConductance = 1000000.0 ;

       //convert resistance to conductance
       fsrConductance /= fsrResistance;
       if (fsrConductance <=1000.0)
       //convert resistance to conductance
       {
         fsrForce = fsrConductance/80.0;
       }
       else
       {
         fsrForce = fsrConductance - 1000.0;
         fsrForce /= 30.0;
       }
       fsrPounds = fsrForce/4.45;

       //convert force to pounds
     }

     return fsrPounds;
    }

    long FindMax(long)
    {
      int counter2 = 0;

      while (counter2 < 100);
      {
        if ( fsrPounds > maximum)
        {
              maximum = fsrPounds;
              counter2++;
        }
        else
        {
              maximum = maximum;
              counter2++;
        }

      }
      return maximum;

    }

    long FindAvg (long)
    {
      long start = 0;
      //variable to begin avg function
      long avg;
      int counter3 = 0;

      while (counter3 < 100);
      {
        start = start + fsrPounds ;
        counter3 ++;
      }

      avg = start/100;
      return avg;
    }

What am I doing wrong? This is my first time working with Arduino.
Thanks

title: How do I fix this error? It says "warning: invalid conversion from 'long int*' to 'long int' [-fpermissive]

Answers: 2

body:
This is most likely not what you want to be doing

    //declaring variables of functions
    FM = FindMax(new long);
    FA = FindAvg(new long);

And it is entirely incompatible with these definitions

    //list functions here
    long ForceInPounds(long);
    long FindMax(long);
    long FindAvg(long);

With the result that you pass a *pointer* to a `long` (ie, its address in memory), to a function which is instead expecting the *value* of a `long`.

However, it's going to be hard to propose a solution until you edit the body of the functions into your question.

There's probably no reason to use `new` here at all - let the functions allocate their own *temporary* variables on the stack, since they seem to return a value rather than a pointer.  Most likely even if this worked, the `new long` you create would be abandoned - ie, a memory leak.

body:
There are several fundamental problems with the code. It appears your understanding of function declaration, definition, and usage are not accurate.

This part:

      //list functions here
      long ForceInPounds(long);
      long FindMax(long);
      long FindAvg(long);

Is unneccesary.

`setup()` is not the place to declare function variables:

      //declaring variables of functions
      FM = FindMax(new long);
      FA = FindAvg(new long);

If your functions use variables internally, the place to declare them is within the function definition.

In your FUNCTIONS section, you start off defining this function:

    long ForceInPounds(const long)

The first `long` declares that the function will return a `long`, and the `(const long)` would normally declare what variable types your function accepts as parameters, as well as the name(s) of said parameters. You have only provided a type `long`, and a modifier `const`, but no name. It doesn't make sense to pass in a `const` variable anyway, as the `const` indicates the content of the variable will never change from the initial value. In your code, not only is the variable not named, it is not given an initial value.

Within that `ForceInPounds()` function, you start with:

      fsrReading = fsrVoltage;

which overwrites your initial `fsrReading = analogRead(0);` with an undefined value, as you have neither declared a type for `fsrVoltage`, nor given it an initial value.

Also, you call `analogRead(0)` once in setup, so it only captures the value once. The `fsrReading` variable is not continually updated with the analog reading. You have to keep calling `analogRead(0)` and storing it in a variable each time through your loop.

There are other problems with the code, but these are a few of the fundamental problems. There is no simple/quick fix to your code.

If you don't come from a C or C++ background, you may want to read a quick overview of them, at a minimum. Start with some of the Arduino example sketches and get a good understanding of how functions are defined and how they work.


body:
Here is my problem. I'm working on making a wifi addressable RGB LED (like WS2812b) controller, I'm using an ESP8266 as the hardware. I'm also creating a phone application for controlling the device and setting different modes. What I'm doing right now is that I communicate with the module by sending GET commands from my phone app. For example to change the brightness I send `http://192.168.4.1/I125I` Then on the ESP side the code is as follows:

    WiFiClient client = server.available();
      if (client) {
      String inData= client.readStringUntil('\r');
      if (inData.indexOf("I")!=-1){
     BRIGHTNESS=str2int(inData.substring(inData.indexOf("I")+1,inData.lastIndexOf("I")));
    }}

  It works, but I'm not sure if this way of sending data is efficient at all. if change colors too rapidly the ESP resets. I recently found another code that uses GET and POST commands but different methods are used, like the following

    server.on("/brightness", HTTP_POST, []() {
        adjustBrightness();
      });

Then inside adjustBrightness function brightness is adjusted. This way it looks more professional but Is it more efficient?

I recently bought a commercial [RGB LED controller][1] that uses ESP8266 as its core. I tried to see what the phone app sends to the controller using the [Drony][2] app. For my app I could see all the get command the app was sending

    192.168.4.1/I255I

    192.168.4.1/R200RG90GB76B

    ...

but for the commercial controller I just saw one connection, something like "157.10.12.10:5172"

Is this using websockets?
Is using websocket a better way? is it more robust?

I'm writing the code in Arduino IDE.

  [1]: https://www.amazon.com/SUPERNIGHT-Wireless-Controller-Working-Android/dp/B01JS0KEBW/ref=sr_1_5?ie=UTF8&qid=1487557438&sr=8-5&keywords=wifi led controller
  [2]: https://play.google.com/store/apps/details?id=org.sandroproxy.drony&hl=en

title: Communication with ESP, HTTP requests or WebSocket?

Answers: 1

body:
> This way it looks more professional but Is it more efficient?

No, the differences are minuscule. It's only really the location of any parameters that are different - either as part of the URL (`GET`) or as part of the body (`POST`).

> Is this using websockets? Is using websocket a better way? is it more robust?

No, it's just a TCP connection (or maybe UDP connection, it's hard to tell from your description) sending unknown data. It's impossible to tell what the data us from the port number, you would have to actively sniff the data and work out what it is.

Yes, it is generally more efficient doing that kind of thing (though not necessarily more "robust") - HTTP is a very generic system that can transfer many different kinds of data in a request so needs large amounts of superfluous information that is not applicable to controlling an LED, whereas a simple TCP or UDP socket only transfers the minimal amount of data needed to get the job done.


body:
I have a U80 Smartwatch from Bluetooth Watch International, which has bluetooth function. It is meant to be connected via to my smartphone (and it works perfectly).

I also have an Arduino Uno board and a corresponding BLE ZS-040 bluetooth chip.

I need for my smartphone to be able to detect my Arduino board, so I can send data from a simple circuit connected to the Arduino board to the smartphone.

Basically, my circuit is meant to be a simple push button. When the button is pushed, and the circuit is closed, the Arduino board will send a signal to the smartwatch. This will cause the smartwatch to ring and vibrate, as if it is receiving a call. Then to turn off the ringing and vibrating, the user can simply 'answer the phone call', and it will stop.

From what I understand, (I'm very new to Arduino) I have to connect the Arduino board to the smartwatch first, which means I have to somehow get the board to be detected by my watch, which it's not doing yet, eventhough the bluetooth module is connected to the board.

Then the push button needs to send a signal to the watch. Which means the command {if buttonpush='1', send (receiving call)}, so when the button is pushed, the signal is sent and the watch acts as if it is receiving a call. Basically showing all the physical signs (eg. vibrating and/or ringing based on the watch's setting, showing 'answer/deny call', etc.). Btw, the push button is not to be held down. As long is the button is pushed and released once, the signal should be sent, and the watch will buzz until the 'phone call' is answered or denied.

1. I have absolutely no idea how to get the board connected to the smartwatch via bluetooth.
2. And while I have a rough idea on the push button circuit I need, I also need to send the signal for the watch to act like it has received a call.

Mainly, I'm looking for any help with coding here. If anyone can help with the physical circuit connections, that would be awesome too.

title: Connecting Arduino Uno to a smartwatch via bluetooth

Answers: 2

body:
HC-05 is a Bluetooth 2.1 SPP only chip (BR/EDR). Your bluetooth watch will be Bluetooth Low Energy 4.x (BLE Single Mode).

The two are not compatible.

You will need a BLE module for the Arduino which is capable of running as a "Central Device".

body:
This isn't exactly an answer but I will like to share my experience after attempting a similar project for the past week.

I have an Arduino UNO and a HM-10 Bluetooth module that is capable of functioning in central mode. I referred to http://www.martyncurrey.com/hm-10-bluetooth-4ble-modules to setup.

I am trying to connect the Arduino UNO/HM-10 with a Hexiwear (http://www.hexiwear.com) bluetooth IoT development smartwatch that is capable of sending sensor data such as steps, heartrate, temperature etc. via bluetooth to a BLE central device.

The Hexiwear will generate a random 6 digit pin when you attempt to connect to it. It works with its own companion Android app and reads sensor data perfectly. Someone managed to pull in the hexiwear's sensor data to a Raspberri Pi via BLE here: https://mcuoneclipse.com/2016/12/19/tutorial-ble-pairing-the-raspberry-pi-3-model-b-with-hexiwear/comment-page-1/#comment-97375.

With my Arduino UNO, I managed up to the point were I could connect the hexiwear and it pops up to ask for the random 6 digit pin so that it could pair to my Ardunio.

And then I am stuck, because I know nothing about the Arduino UNO and HM-10 that can send the pin code back to the Hexiwear.

Here's where I thought might be useful:

1) Do you have the U80's BLE specifications. This is how much hexiwear's BLE specification looks like https://github.com/MikroElektronika/HEXIWEAR/blob/master/documentation/HEXIWEAR Bluetooth Specifications.pdf.

My Hexiwear wearable comes with source code. If I try hard enough I can probably hack it to make what I want to do possible.

2) Does U80 require pairing with pin code? I am stuck here in my project.

3) Is the library for your BLE chip capable to sending said BLE requests and responses to communicate with the U80? This is where I believe I am going to be stuck further.

Hope this helps in some ways.


body:
I recently bought a simple SMAKN 315MHz RF receiver and transmitter, and I got everything working so that the transmitter transmits the value of a joystick, and the receiver receives that and uses it to set the analogWrite() of a motor on a PWM pin.

However, the moment the motor turns on, the receiver just weakens tremendously. At that point it only gets a message when I stick the receiver right against the transmitter. I’m powering the arduino and motor with a 3.7v LiPo battery btw.

Any help? I’ve tried with a 9V alkaline and a 9V adapter and nothing significantly changed.

title: RF receiver becomes weakened after motor turns on

Answers: 1

body:
That behaviour is to be expected. Motors are very noisy and cause massive amounts of interference in radio signals.

The best thing you can do is to try and suppress that interference. For this you will need three 0.1µF (100nF) ceramic capacitors.

One capacitor is connected between the terminals of the motor to reduce noise transferred down the wires (wires make good antennae). The other two connect between each of the terminals and the metal body of the motor.

The metal body of the motor then becomes a shield to trap the noise.

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

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


body:
I'm trying to control [this servo][1], and whenever I leave the Uno connected, via USB, to the PC, most of the time the servo barely moves, and sometimes jitters.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/6YHV7.png)

<!-- End schematic -->

I connected the oscilloscope to try to understand / solve my problem, and I see that the signal I send is the same whether or not the USB is connected. I measured the voltage over the 5V/GND and it's constant at 5V and doesn't dip/spikes. I tried with a pull-down resistor on the signal pin (don't know if it's a good idea) and it doesn't change anything.

If I unplug the battery, but keep the USB connected, the servo stays immobile, but I figure that's because the Arduino can't feed a servo, hence why I wanted to use an external power for it. The second power source is a [PowerBoost 1000C][2] with a LiPo battery.

As soon as I unplug the USB port, the servo just starts moving properly, so I figured it must be interference of some kind. I saw the accepted answer to [this question][3] and it has me doubt whether I should use a battery while it's plugged in, but surely there is a way. Would I kind of need to connect the GND of my circuit to the GND wire of the USB before it actually enters the Arduino?

I didn't post the code as it's basically just the swipe demo from the website, and because it works when on battery only.

Regards

  [1]: https://www.parallax.com/sites/default/files/downloads/900-00005-Standard-Servo-Product-Documentation-v2.2.pdf
  [2]: https://cdn-learn.adafruit.com/downloads/pdf/adafruit-powerboost-1000c-load-share-usb-charge-boost.pdf
  [3]: https://arduino.stackexchange.com/questions/21061/two-arduinos-one-power-source

title: Unplanned behavior with two power sources

Answers: 1

body: Beginner error: As stated in the diagram, I connected the external source of power to the 5V pin, while it should have been connected to the Vin pin. /ashame


body:
I'm trying to create a comma delimited file using this [SDFat library](https://github.com/greiman/SdFat)

Calling this code creates my file

    const char Header[24]="Desired RPM,Output RPM\n";
    ...
    foo()
    {
      SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);
      SpeedCache.write(Header);
      SpeedCache.sync();
    }
    ...

After running, I have a file containing
>Desired RPM,Output RPM'\n'

When I call the following function, I want it to add `int target` and `int reference` to the bottom of the file.

    bool SDClass::SetLine(SdFile Cache,int target, int reference)
    {
      bool good = false;
      char NewLine[32];
      Cache.seekEnd();
      sprintf_P(NewLine,(PGM_P)F("%d,%d\n"),target,reference);
      Serial.println(good=Cache.write(NewLine));
      Cache.sync();
      return good;
    }

 On the first call, this works so for an input of `SpeedCache,50,100` I get
>Desired RPM,Output RPM'\n'
>
>50,100'\n'

However, if I then write an input of `SpeedCache,5,10` I get
>Desired RPM,Output RPM'\n'
>
>5,10'\n'

How do I adjust my function so that I will get:
>Desired RPM,Output RPM'\n'
>
>50,100'\n'
>
>5,10'\n'

title: Arduino SDFat Libray overwrites last value

Answers: 2

body:
You just need to open the file in APPEND mode:

    SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);

> O_APPEND
>
> The  file  is  opened  in append mode.  Before each write, the file offset is positioned at the end of  the  file,  as  if  with               lseek.

You should also pass your file around by *reference* so it doesn't keep creating new copies of the internal structure:

    bool SDClass::SetLine(SdFile &Cache,int target, int reference)

body:
How do you pass the file by reference?

```
SdFat sd;
SdFile DataFile;

isSD = DataFile.open(FileName, O_WRITE | O_CREAT | O_AT_END);
```


body:
I have declared a struct with some variables that right now are fixed, but one of the variables on the struct needs to be what the Arduino's serial port reads.

    struct testing_var
    {
        const char *name;
        byte key[32];
        byte pt[16];
    };

    static testing_var const test1 = {
        .name        = "Speck-128-ECB",
        .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                        0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
        .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                        0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
    };

As you can see for how I have declared it, I'm trying to get a plaintext from the serial port and the Arduino should encrypt that. I have a function that does this encryption, but I can't quite figure out how to pass what the serial port reads to the struct.

    void loop() {

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

I need to pass this *var1* as the variable *pt* in the struct. Any clues? I'm maybe missing something very obvious, but I don't usually work with structs.

**EDIT:**
I'm trying to assign the value read by the serial port to the struct by creating another function that goes like this:

    void setPlain(struct PlainText *myPlain, const char* thePlain){
        myPlain -> plaintext = the Plain;
       }
Then, in the *loop*, I use:

      if (Serial.available()>0) {
        var1 = Serial.read();
        setPlain(&PlainText, var1)
    }

I'm getting an error using this function, I guess that it has something to do with the type of variable I'm trying to assign, these values are in HEX, not in char. But I'm not really sure it that's it or what other workaround should I use.

title: Transfer serial data to struct variable in Arduino

Answers: 1

body:
You read the serial port one char at time, and assign it to *test1.pt[i]*, where i is an index varying from 0 to 15.

And `test1` cannot be `const`, because you are going to modify it with the serial data.

Here is a test code showing how to do it.

    struct testing_var
    {
        const char *name;
        byte key[32];
        byte pt[16];
    };

    //  test1 cannot be 'const'
    static testing_var test1 = {
        .name        = "Speck-128-ECB",
        .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                        0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
        .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                        0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
    };

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

    void loop() {
      Serial.println("Enter 16 chars:");
      //  Read 16 chars from Serial
      for (int i=0; i < 16;) {
        if (Serial.available()) {
          test1.pt[i++] = Serial.read();
        }
      }
      // Do something with the data, like print it.
      for (int i = 0; i < 16; i++) {
        Serial.print(char((test1.pt[i])));
      }
      Serial.println();
    }


body:
I have just received inkshield purchased from [Nerd Creation Labs][1], I stacked inkshield on my Arduino Mega and uploaded [THIS CODE][2] provided by the creator of inkshield,and it works pretty well.
I can print text ;)

Questions :

1: The code given above can only print text in a single Font. Can i add multiple Fonts in a single code.?

2: How can i change the Font to something like Times New Roman, Arial,calibri or more stylish Fonts like snell RoundHand and Zapfino.?

Please help

Thank you

  [1]: http://nicholasclewis.com/projects/inkshield/
  [2]: https://github.com/NicholasCLewis/InkShield/blob/master/ArduinoLibraries/InkShieldMega/examples/SerialTextInkShieldMega/SerialTextInkShieldMega.pde

title: Changing Text Arduino inkShield

Answers: 2

body:
> 1: The code given above can only print text in a single Font. Can i add multiple Fonts in a single code.?

Sure you can.

> 2: How can i change the Font to something like Times New Roman, Arial,calibri or more stylish Fonts like snell RoundHand and Zapfino.?

The top 700-odd lines of the code are the font. You just need to find a way of creating the same kind of data from your own chosen font.

body:
The fonts are the little bitmaps starting at line 50. Each 16 bit value is 1 column of the letter to be printed. There are 10 columns of pixels per character (the `rowsPerChar` value). The least significant bit is the bottom row.

So to change the font all you need to do is change those bitmaps.


body:
In my code I need to set five pins to output mode. I have the pinMode() statements in my setup.

I am trying to make my Arduino code run a bit faster, and I came across a tutorial which swaps digitalWrite() for PORTB &= _BV(PB6) (high), and makes it run ~25 times faster.

I'm wondering if there's a similar type of substitution I can do for pinMode(), that will make it run faster as well? Or is pinMode() already a fast command, so I shouldn't worry about it?

Thanks

title: Alternative code for pinMode()?

Answers: 3

body:
The Arduino reference manual has all you need to know:

* https://www.arduino.cc/en/Reference/PortManipulation

The register you need is the `DDRx` register (Data DiRection X). Set a bit to 1 for output and 0 for input.

body:
yeah. the corresponding registers are DDRx.

with a little bit of coding, you can easily convert pinMode() to your own, say, mypinMode() that operates on the DDRx directly.

the datasheet is your best friend, as always.

body:
It isn't worth it for something done once, if you only do it in `setup`. However if you need to toggle the mode frequently yes it can be done. You sadly haven't said which pins, but assuming they are D2 to D6 (digital pins 2 to 6) *on a Mega* you can do this to set **output** mode:

      DDRE |= bit(PE3) | bit(PE4) | bit(PE5); // D5, D2, D3
      DDRG |= bit(PG5); // D4
      DDRH |= bit(PH3); // D6

For **input** mode you have to "and" in the ones-complement of the bits like this:

      DDRE &= ~(bit(PE3) | bit(PE4) | bit(PE5)); // D5, D2, D3
      DDRG &= ~(bit(PG5)); // D4
      DDRH &= ~(bit(PH3)); // D6

The exact register names are in the datasheet, and the mappings to the pins on your board are in the schematic (available from [the Arduino site](https://store.arduino.cc/usa/arduino-mega-2560-rev3)). The relevant part is this:

[![Mega pins D0 to D7][1]][1]

The bit numbers are in grey on the left (eg. PE4) and the board pin numbers are in green on the right (eg. 2 is digital pin 2).

The `bit` macro works similarly to the `_BV` one you mentioned in your question. It shifts `1` left the required number of bit positions to be in the right place.

---

A somewhat simpler and more portable solution is to use the digitalWriteFast library which you can download from:

https://github.com/NicksonYap/digitalWriteFast

This uses various compiler tricks to detect if you are using a constant for `pinMode` and `digitalWrite` and converts them into the appropriate register manipulation. You just install the library and add `Fast` to the function names, eg.

    pinModeFast (2, OUTPUT);
    digitalWriteFast (2, HIGH);

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


body: The ATmega328P has a separate clock signal for Flash and EEPROM (CLKFLASH) than it has for the RAM (CLKCPU). Why is this?

title: Why is CLK_FLASH separate from CLK_CPU?

Answers: 1

body: It's to do with programming the chip. When you are programming the chip using an external programmer you need the flash and EEPROM to be running. However you don't want the CPU to be running since you are doing things with the flash that it would normally access. By having the CPU (and RAM) on a separate clock you can clock the flash without clocking the CPU and all is well.


body:
I got one of these cheap STM8 boards from China and was hoping to find a way to use this with arduino code.
[![STM8 development board][1]][1]
Does anyone know of an arduino boot loader and board package that works with them ?

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

title: STM8 Development Board with Arduino IDE

Answers: 2

body:
There is a bootloader on those chips to slow serial programming. A much easier way to to get a stlink debugger.

There are also some packages that allow Arduino styled programming on those chips. I wrote one myself that runs on iar and I think at least one on sdcc.

Those chips are really nice.

body:
Start the Arduino-IDE. In File->Preferences, Settings tab, enter

https://github.com/tenbaht/sduino/raw/master/package_sduino_stm8_index.json

Open Tools->Board:...->Boards Manager

Find Sduino by typing 'sd' into the search line

Click on the list entry

Click on Install.

This link is more comprehensive

https://tenbaht.github.io/sduino/


body:
I'm using the Adafruit I2C FRAM breakout board with my Nano and it works as advertised, but every time I write a variable to this thing I have to use library function calls with addressing. This makes it run slower than I want it to, especially since I'm using the memory to keep camera pixel information and I need to process it quickly.

As user Majenko put it:

>A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.
>
>A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5*8)+2+4+1+1 = 48 bits.
>
>So for a read and write it's 38+48 = 86 bits.
>
>Therefore you'd require 86*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.
>
>At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.
>
>If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.

It's much faster to write entire arrays at a time, but I need to write the data int-by-int as the data is encountered, since my whole reason for using the breakout board was to avoid needing local buffer space.

So is it possible to somehow configure this so that my I2C bus writes to the FRAM memory autonomously just like it does with the stack/heap in the onboard SRAM memory? Because then I could just declare my arrays as normal and let the processor take care of it, and then I would be so happy.

title: Is it possible to configure FRAM memory for use as stack and heap?

Answers: 3

body:
I don't have experience with FRAM, but below are some results with SRAM: 23LC1024 (128 KB SRAM with SPI). Tests have been performed with an Arduino Uno.

(I had to use an answer instead of a comment because of the (screenshot) table alignment.

As you can see, write/read of a page (32 bytes) is faster than other types, but it depends on the amount of bytes you have to write to use pages.

(Because I want to use reasonable complex structures, I decided to go for a microcontroller with more RAM because stack and heap space cannot be used from external SRAM).

[![Speed tests][1]][1]

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

body:
Yes it is possible to have c variables use external RAM. The [Atmel AVR FAQ][1] discusses this. It's also possible to have the heap and stack (not recommended but possible), use external RAM.

Bear in mind that having this dealt with autonomously is still going to take roughly the same amount of time as it's going to have to execute similar functions to the ones you list above, albeit without having to code the transactions.

Have you considered a mega, and cache 1-6k of data then transfer that all at once. Using SPI would be faster, even more so with 1-6k. You can have an SPI LCD and RAM off the same pins, they just need an additional digital pin for the second device.

  [1]: http://www.atmel.com/webdoc/avrlibcreferencemanual/FAQ_1faq_ext_ram.html

body:
**No, you can't use SPI or I2C memories to store stack or heap data in AVR microcontrollers**, as the AVR MCUs do not allow to map memories connected to the SPI or I2C buses. In other words, there is no way to tell the MCU that you connected a SPI or I2C memory, and how to use it, automatically. Therefore you can only use such memories to manually store/read data, by manually issuing all the correct command sequences, which will be very slow (as you wrote you are already doing by calling some libary functions).

Instead, you can use an external PARALLEL memory, connected to the external memory bus, which is present on SOME AVR microcontrollers (unfortunately, the ATMEGA328 has no external memory bus). Still you'll get a much slower performance with respect to the internal memory.

Finally, Arduino is not a  good platform to process (or store/read) pixel data from a camera, due to severe computing power and memory limits. Even if there are more powerful Arduino (or Arduino-compatible) boards, which feature much more powerful processors (e.g. Cortex M3 or M4), you would probably need to program them using a very optimized C (and not C++!) code, or even ASM. But at this point, there would no reasons to use an Arduino-compatible platform, instead of an another one, possibly much more powerful or even cheaper.


body:
I`m new here so just wanted to say hi!

I have been messing about with Arduino now for about 2 weeks, picking and trying different sketches for a greenhouse project I need.

Trying all sorts with LCD, temperature etc.

But what I actualy wanted was just a simple multiple timer say setting for every hour 9-6 activate for 2 mins to turn on a misting system for my plants, and that is now what I present in the following sketch, simple enough and it works, I have just removed some of the timings to keep the code compact on here.

Now the tricky bit, I want the misting system to come on in those hours chosen, but only if the Humidity is below a certain thresh hold, thats where I`m running into issues.

If anyone can look over the code and advise me where to put "if(h < humLowTrigger){"

I have tried before the times, included it in each line of the times and after the times and still not working.

So all help and knowledge greatly appreciated.

Cheers for now Alan

    #include <Wire.h>
    #include "RTClib.h"
    #include "DHT.h"

    #define humLowTrigger 70
    #define DHTPIN 7
    #define DHTTYPE DHT22

    DHT dht(DHTPIN, DHTTYPE);

    RTC_DS1307 rtc;

    void setup () {

    Serial.begin(9600);
    dht.begin();
    Wire.begin();
    rtc.begin();

    pinMode( A2, OUTPUT);
    digitalWrite(A2, LOW);
    }

    void loop () {

    float h = dht.readHumidity();
    float t = dht.readTemperature();

    DateTime now = rtc.now();

    if (now.hour() == 15 && now.minute() == 5) {
    digitalWrite(A2, HIGH);
    }
    if (now.hour() == 15 && now.minute() == 8) {
    digitalWrite(A2, LOW);
    }
    if (now.hour() == 15 && now.minute() == 10) {
    digitalWrite(A2, HIGH);
    }
    if (now.hour() == 15 && now.minute() == 12) {
    digitalWrite(A2, LOW);
    }

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %");
    Serial.println();
    Serial.println();
    delay(2000);

    }

title: Combining 2 IF statements, getting nowhere and pulling hair out! ;)

Answers: 2

body:
If you want to do something when two or more conditions meets , use an *and* operator (&&), like this:

    if (h < humLowTrigger && now.hour() == 15 && now.minute() == 5) {
    ... do something ...
    }

If you have a lot of conditional statements, you can simplify:

    if (h < humLowTrigger) {
       if (... other conditions 1 ...) {
         do something 1
         }
       ...
      if (... other condition n ...) {
         do something n.
         }
    }

 In your specific case:

    if(h < humLowTrigger) {
      if (now.hour() == 15 && now.minute() == 5) {
        digitalWrite(A2, HIGH);
      }
      if (now.hour() == 15 && now.minute() == 8) {
        digitalWrite(A2, LOW);
      }
      if (now.hour() == 15 && now.minute() == 10) {
        digitalWrite(A2, HIGH);
      }
      if (now.hour() == 15 && now.minute() == 12) {
        digitalWrite(A2, LOW);
      }
    }

**Better version**

But there is a problem with the previous code, beacuse the mister **must** turn off no matter what the humidity level is.

    // Turn on only if humidity below threshold.
    if (h < humLowTrigger && now.hour() == 15 && (now.minute() == 5 || now.minute() == 10)) {
        digitalWrite(A2, HIGH);
      }
    }
    // Turn off always.
    if (now.hour() == 15 && (now.minute() == 8 || now.minute() == 12) {
        digitalWrite(A2, LOW);
       }

body:
In addition to LookAlterno's answer (which I upvoted), the last part can be reduced to:

    if ((h < humLowTrigger) && (now.hour() == 15)) {
      if (now.minute() == 5) {
        digitalWrite(A2, HIGH);
      }
      if (now.minute() == 8) {
        digitalWrite(A2, LOW);
      }
      if (now.minute() == 10) {
        digitalWrite(A2, HIGH);
      }
      if (now.minute() == 12) {
        digitalWrite(A2, LOW);
      }
    }


body:
I'm trying to generate a sine wave on my Arduino micro.
I used this code.

    int Pin = 9;

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

    void loop()
    {
     float something = millis()/10000.0;
     int value = 128.0 + 128 * sin( something * 2.0 * PI  );
     analogWrite(Pin,value);
    }

I have a low pass filter at the output of the pin to smooth the wave. The problem is : I get a nice square wave with a duty cycle from 0 to 100%, but not a sine wave. Ideally, I'd like to set a frequency of 10 Hz.
Can anyone tell me where I made a mistake ? Thanks a lot !!!

title: Sine wave PWM Arduino Micro

Answers: 2

body: it is how PWM works. digital pins can do only 1 and 0.

body:
> Can anyone tell me where I made a mistake ?

put a lpf on the pwm output.


body:
the Arduino Primo Core website (https://store.arduino.cc/usa/arduino-primo-core) says that I can program the Arduino Primo Core using an Arduino Primo.

I have no idea how to do this!

Can you do it through the Arduino IDE? Which pins on the Arduino Primo Core should I connect to which pins on the Arduino Primo?

Thanks for your help!

title: How do I program the Arduino Primo Core using the Arduino Primo?

Answers: 2

body:
instructions were on arduino.org. it is turned off now, but you can find them in Web Archive (without downloads)
[Arduino.org pages in web archive][1]

  [1]: https://web.archive.org/web/20170711122201/http://www.arduino.org/learning/getting-started/getting-started-with-arduino-primo-core

body:
Juraj's answer answered my question, however I've gone back since and found the link to be broken. Fortunately I saved the file so I'll summarise here for others:

1. Download the nRF52 platform using the Boards Manager:

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

2. Connect the Arduino Primo Core to the Arduino Primo using a SWD connector (J2 on Arduino Primo Core and J9 on the Arduino Primo):

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

3. Plug the Arduino Primo into the PC using a USB data cable.

4. Select "Arduino Primo Core" from the `Tools > Board` menu:

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

5. Select the corresponding port of the Arduino Primo from the `Tools > Port` menu:

[![enter image description here][4]][4]

6. Select the `Blink` sketch from the `File > Examples > 1. Basics` menu.

7. Upload the sketch. If the light blinks on the Arduino Primo Core it has worked!

  [1]: https://i.stack.imgur.com/ReyCA.png
  [2]: https://i.stack.imgur.com/l7lp5.jpg
  [3]: https://i.stack.imgur.com/rZ64Z.jpg
  [4]: https://i.stack.imgur.com/CRsqQ.jpg


body:
I have been working on a project where I will be powering an Arduino and some LED light strips (2 x 3 Meter strips w/ 30 LEDs per meter). I am powering all of it from a 5v 10amp power supply.

Currently I have split the power cable and have it running to the board and the LED's in separate runs.

As I move from a breadboard to a more permanent proto-board, it would be great to add a barrel connector onto the proto-board and just have a single plugin for power so I can easily disconnect it.

Will this cause any issues if all of the power comes from the proto-board? Thanks!

title: How much power can a proto board handle?

Answers: 3

body:
There is no problem to have your power source coming from your protoboard to supply your arduino since your protoboard can gives to your arduino one of these possibilities explained [here][1].

  [1]: https://arduino.stackexchange.com/questions/39041/powering-an-arduino-with-more-than-5-v/39043#39043

body:
No, it's not practical do to that with protoboard of any form.

There are two reasons for this:

1. Barrel jacks are not rated for 10A - I think the most powerful I have seen is 3A.
2. To handle 10A over (for example) 6 inches of track you would require tracks roughly 8mm wide at 1oz copper. No protoboard provides such tracks.

Even if you're only using half the capacity of your power supply (5A) you still exceed a barrel jack, and would need traces about 3mm wide.

body: A common way to solve this is to solder a wire onto the tracks on the proto-board.


body:
I'm currently using the [SDFat library](https://github.com/greiman/SdFat) and am passing a global `FatFile`

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

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

I if have a function that requires an `SdFile` type and I know that a given instance of `FatFile` is a valid `SdFile` what is the best way to reopen `FatFile F` as `SdFile J`?

Right now I'm doing:

    SdFile ActiveFile;  //Global Active File
    ...
    void SDRun (FatFile &RunFat)
    {
      SdFile RunRoot;
      RunRoot.open("/", O_READ);
      ActiveFile.close();
      ActiveFile.open(&RunRoot,RunFat.dirIndex(),O_READ);
      ....

However, this only works when `RunFat` is in the root directory.

title: Open Parent Class as Child Class (SD Fat Library)

Answers: 1

body:
If `RunFat` is an instance of `SdFile` you can just cast it:

    SdFile& RunRoot = dynamic_cast<SdFile&>(RunFat);

`RunRoot` and `RunFat` are now the exact same file in the exact same state (no need to open it or anything) but seen as an `SdFile` not a `FatFile`.