text:
EDB char array problem. New input word overlaps the previous words saved
I have been searching everywhere now and nothing seems to work out for me. When I try to input a new word, it overlaps the previously entered words.
Here is my struct definition:
struct LogEvent{
  char fullname[30];
} logEvent;

Here is how I assign a value to fullname:
strcpy(logEvent.fullname, testName);

Here is how I print the output:
for(int i = 0; i <= db.count(); i++)
{
  EDB_Status result = db.readRec(i, EDB_REC logEvent);
  if(result == EDB_OK)
  {
     Serial.print(logEvent.fullname);
     Serial.print(" ");
  }
}

Here is the sample output:
Input 1 - Lebron James
Output 1- Lebron James

Input 2 - Kobe Bryant
Output 2 - Kobe Bryant Kobe Bryant  (The output should be - Lebron James Kobe Bryant)

Input 3 - LeGoat
Output 3 - LeGoat LeGoat LeGoat (The output should be - Lebron James Kobe Bryant LeGoat)

How to fix this?
EDIT. Here is my code:
#include "Arduino.h"
#include <EDB.h>

// Use the external SPI SD card as storage
#include <SPI.h>
#include <SD.h>

int recnumber = 1;
//Arbitrary definition
struct LogEvent {
    int id;
    int temperature;
    char fullname[30];
}
logEvent;

inline void writer (unsigned long address, const byte* data, unsigned int  recsize) {
    digitalWrite(13, HIGH);
    dbFile.seek(address);
    dbFile.write(data,recsize);
    dbFile.flush();
    digitalWrite(13, LOW);
}

inline void reader (unsigned long address, byte* data, unsigned int recsize) {
   digitalWrite(13, HIGH);
   dbFile.seek(address);
   dbFile.read(data,recsize);
   digitalWrite(13, LOW);
}
  EDB db(&writer, &reader);

// Run the demo
void setup()
{
    pinMode(13, OUTPUT);
    digitalWrite(13, LOW);

    Serial.begin(9600);
    Serial.println(" Extended Database Library + External SD CARD storage demo");
    Serial.println();

    randomSeed(analogRead(0));

    if (!SD.begin(SD_PIN)) {
        Serial.println("No SD-card.");
        return;
    }

    // Check dir for db files
    if (!SD.exists("/db")) {
        Serial.println("Dir for Db files does not exist, creating...");
        SD.mkdir("/db");
    }

    if (SD.exists(db_name)) {

        dbFile = SD.open(db_name, FILE_WRITE);

      // Sometimes it wont open at first attempt, espessialy after cold start
      // Let's try one more time
        if (!dbFile) {
            dbFile = SD.open(db_name, FILE_WRITE);
        }

        if (dbFile) {
            Serial.print("Openning current table... ");
            EDB_Status result = db.open(0);
            if (result == EDB_OK) {
                Serial.println("DONE");
            } else {
                Serial.println("ERROR");
                Serial.println("Did not find database in the file " + String(db_name));
                Serial.print("Creating new table... ");
                db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
                Serial.println("DONE");
                return;
            }
        } else {
            Serial.println("Could not open file " + String(db_name));
            return;
        }
    } else {
        Serial.print("Creating table... ");
        // create table at with starting address 0
        dbFile = SD.open(db_name, FILE_WRITE);
        db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
        Serial.println("DONE");
    }
    deleteAll();
    recordLimit();
    countRecords();
}
char testName[30];

void loop()
{
  if(Serial.available())
  {
    Serial.println("Waiting for name...");
    index = 0;
    for(int i = 0; i < sizeof(testName); ++i)
    {
      testName[i] = (char)0;
    }
    while(Serial.available())
    {
      char character = Serial.read();
      testName[index] = character;
      index++;
    }
    createRecords(testName);
    selectAll();
    delay(1000);
  }
  delay(1000);
 }

void createRecords(char *testName)
{
  Serial.print("Creating Record... ");
  logEvent.id = recnumber;
  logEvent.temperature = random(1, 125);
  strcpy(logEvent.fullname, testName);
  recnumber++;
  EDB_Status result = db.appendRec(EDB_REC logEvent);
}

void selectAll()
{
   for (int recno = 1; recno <= db.count(); recno++)
   {
      EDB_Status result = db.readRec(recno, EDB_REC logEvent);
      if (result == EDB_OK)
      {
        Serial.print("Recno: ");
        Serial.print(recno);
        Serial.print(" ID: ");
        Serial.print(logEvent.id);
        Serial.print(" Temp: ");
        Serial.print(logEvent.temperature);
        Serial.print(" Fullname: ");
        Serial.print(logEvent.fullname);
        Serial.print(" Length: ");
        Serial.println(strlen(logEvent.fullname));
      }
    }
 }

Here is the output:
Extended Database Library + External SD CARD storage demo

Openning current table... DONE
Truncating table... DONE
Record Limit: 2045
Record Count: 0
Record Count: 0
Waiting for name...
Name received: Kobe Bryant
LogEvent Fullname:
The sentence entered is 11 characters long
Creating Record... Done Creating Record...
Recno: 1 ID: 1 Temp: 64 Fullname: Kobe Bryant Length: 11
Waiting for name...
Name received: Lebron James
LogEvent Fullname: Kobe Bryant
The sentence entered is 12 characters long
Recno: 1 ID: 1 Temp: 64 Fullname: Kobe Bryant Length: 11
Creating Record... Done Creating Record...
Recno: 1 ID: 1 Temp: 64 Fullname: Lebron James Length: 12
Recno: 2 ID: 2 Temp: 78 Fullname: Lebron James Length: 12
Waiting for name...
Name received: Michael Jordan
LogEvent Fullname: Lebron James
The sentence entered is 14 characters long
Recno: 1 ID: 1 Temp: 64 Fullname: Lebron James Length: 12
Recno: 2 ID: 2 Temp: 78 Fullname: Lebron James Length: 12
Creating Record... Done Creating Record...
Recno: 1 ID: 1 Temp: 64 Fullname: Michael Jordan Length: 14
Recno: 2 ID: 2 Temp: 78 Fullname: Michael Jordan Length: 14
Recno: 3 ID: 3 Temp: 29 Fullname: Michael Jordan Length: 14

Update: I tried to use memset but the result is still the same as above.

@LookAlterno Sure

Okay, I'll try to work on that.

Okay. Working on it.

Can you upload the arrangement you made here I have the same problem

I managed to solve the problem. The problem is with the SD card library of Arduino. I downloaded this library sdFat library, included it in the sketch #include "SdFat.h", and defined SdFat SD. I also removed the #include <SD.h>.

I've just tried to extend one of the examples (with internal EEPROM), and it's working as expected:
/*
 EDB_Simple.pde
 Extended Database Library + Internal Arduino EEPROM Demo Sketch

 The Extended Database library project page is here:
 http://www.arduino.cc/playground/Code/ExtendedDatabaseLibrary

 */
#include "Arduino.h"
#include <EDB.h>

// Use the Internal Arduino EEPROM as storage
#include <EEPROM.h>

// Uncomment the line appropriate for your platform
#define TABLE_SIZE 512 // Arduino 168 or greater

// The number of demo records that should be created.  This should be less
// than (TABLE_SIZE - sizeof(EDB_Header)) / sizeof(LogEvent).  If it is higher,
// operations will return EDB_OUT_OF_RANGE for all records outside the usable range.
#define RECORDS_TO_CREATE 10

// Arbitrary record definition for this table.
// This should be modified to reflect your record needs.
struct LogEvent {
  int id;
  int temperature;
  char test[20] = {};
}
logEvent;

// The read and write handlers for using the EEPROM Library
void writer(unsigned long address, byte data)
{
  EEPROM.write(address, data);
}

byte reader(unsigned long address)
{
  return EEPROM.read(address);
}

// Create an EDB object with the appropriate write and read handlers
EDB db(&writer, &reader);

void setup()
{
  Serial.begin(115200);
  Serial.println("Extended Database Library + Arduino Internal EEPROM Demo");
  Serial.println();

  db.create(0, TABLE_SIZE, sizeof(logEvent));

  Serial.print("Record Count: "); Serial.println(db.count());

  Serial.println("Creating Records...");
  int recno;
  for (recno = 1; recno <= RECORDS_TO_CREATE; recno++)
  {
    logEvent.id = recno;
    logEvent.temperature = recno * 2;
    strcpy(logEvent.test, (String{recno*3} + " whatever " + recno).c_str());
    db.appendRec(EDB_REC logEvent);
  }

  Serial.print("Record Count: "); Serial.println(db.count());
  // Thanks to katts0...@gmail.com for the next line
  for (recno = 1; recno <= RECORDS_TO_CREATE; recno++)
  {
    db.readRec(recno, EDB_REC logEvent);
    Serial.print("ID: "); Serial.print(logEvent.id);
    Serial.print(" Temp: "); Serial.print(logEvent.temperature);
    Serial.print(" Data: "); Serial.println(logEvent.test);
  }
}

void loop()
{
}

The output:
Extended Database Library + Arduino Internal EEPROM Demo

Record Count: 0
Creating Records...
Record Count: 10
ID: 1 Temp: 2 Data: 3 whatever 1
ID: 2 Temp: 4 Data: 6 whatever 2
ID: 3 Temp: 6 Data: 9 whatever 3
ID: 4 Temp: 8 Data: 12 whatever 4
ID: 5 Temp: 10 Data: 15 whatever 5
ID: 6 Temp: 12 Data: 18 whatever 6
ID: 7 Temp: 14 Data: 21 whatever 7
ID: 8 Temp: 16 Data: 24 whatever 8
ID: 9 Temp: 18 Data: 27 whatever 9
ID: 10 Temp: 20 Data: 30 whatever 10

I'll try to look into this.

I tried this and it is working as you said. Maybe my problem is with the SD Card library SD.h

@Xirb or reader/writer is not working as expecter. I've used different signatures - it's called for each byte


text:
I'm trying to display the numbers 0-99 by multiplexing to two 7 segment displays. One number does not display
//Numbers 0-9.
int numberArray[10][7] = {
  { 0, 0, 0, 0, 0, 0, 1 }, //0
  { 1, 0, 0, 1, 1, 1, 1 }, //1
  { 0, 0, 1, 0, 0, 1, 0 }, //2
  { 0, 0, 0, 0, 1, 1, 0 }, //3
  { 1, 0, 0, 1, 1, 0, 0 }, //4
  { 0, 1, 0, 0, 1, 0, 0 }, //5
  { 0, 1, 0, 0, 0, 0, 0 }, //6
  { 0, 0, 0, 1, 1, 1, 1 }, //7
  { 0, 0, 0, 0, 0, 0, 0 }, //8
  { 0, 0, 0, 0, 1, 0, 0 }, //9
};

//Turn off all segments (common anode --> high = off)
void reset() {
  for (int i = 12; i >= 6; i--) {
    digitalWrite(i, 1);
  }
}

//turn on both segments (don't write anything to them)
void on(){
  digitalWrite(4,1);
  digitalWrite(5,1);
}

void setup() {
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  reset();
  on();
}
void loop() {
  for (int i=0;i<99;i++){
    twoDigitNumber(i);
  }
}

void twoDigitNumber(int number){
    digitalWrite(4,1);                   //turn on left display
    digitalWrite(5,0);                   //turn on right display
    digit(int(floor(number/10)));        //display the tens digit
    delay(10);
    digitalWrite(4,0);                   //turn off left display
    digitalWrite(5,1);                   //turn on right display
    digit(int(number-floor(number/10))); //display the ones digit
    delay(10);
}

//make the displays show a single digit number
void digit(int number) {
  for (int i = 12; i >= 6; i--) {
    digitalWrite(i, numberArray[number][12 - i]);
  }
}

This is my first time doing anything at all with Arduino, and I'm also brand new to the language.
I have a bit of circuitry attached to the display. I'm using 2n5551 NPN transistors to act as a switch. Collectors connected to 5v, bases are connected to pin 4/5 with a 200 ohm resistor. Emitters are connected to the common anode of the displays. pin 4 is for the left display, pin 5 for the right display. These are to display different numbers in each display. Something's probably wrong with this but I'm having a hard time learning about transistors.
When I use the function twoDigitNumber(), it only displays the number on the left display, but I can see a very dim copy of that same number on the right display. int() is there because i thought floor() would make it into a double and cause issues, but that didn't fix it.
I know every segment works. When I use digit(), it shows the same digit on both displays (as expected).
Any help is appreciated.

This line looks wrong: digit(int(number-floor(number/10))); - don't you want the number mod 10? That is: digit (number % 10);

If the number is 42 your calculation would give you 42 - 4 which would be 38 and that is not in the range 0 to 9.

Looks like I forgot to multiply the tens by 10 first before subtracting it.

Missing pinmode(4,OUTPUT) in your setup routine.
As a general comment, using variable names instead of 'magic numbers' makes your code easier to read - and thus usually easier to debug. for example:
const int leftDisplay = 4;
const int rightDisplay = 5;
const int seg1 = 12;
const int seg2 = 11;
[...]

You can also use HIGH and LOW instead of 1 and 0 for the digitalwrite elements

That worked. Thanks. I'm ashamed the solution was so easy.

source: Stack Exchange

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

sort: votes


text:
How do I create a constant loop with an event that only occurs once?
I am currently working in void loop() and have setup a distance meter that constantly checks the distance.
Once the distance threshold is met, a function is called. Now I only need this function to be called ONCE. But because the distance meter is constantly scanning (which I need), the function is also being repeatedly called. I tried making some sort of timer but I can't figure it out. Can someone please have a look at this?
if (distance <= 150){
    personPresent();
    }

  if(distance > 150){
    personAbsent();
      }

I need certain events within the if statement to occur only once. E.g., I want to register when there is a personPresent and have that event not fire repeatedly.
In this case, personPresent() is attached to a GPIO pin which triggers a buzzer sound. As it is now, the buzzer keeps on ringing as long as distance is less then 150. I need the buzzer to make a sound only ONCE and then not buzz for at least 5 minutes.

use a "flag" variable to remember that the function has been called

What you want is not to check the distance but to check that the distance condition changed.
static boolean present = false;

Inside loop:
if (present == false && distance <= 150){
    personPresent();
    present = true;
} else if(present == true && distance > 150) {
    personAbsent();
    present = false;
}

static boolean didItAlready = false;

if(distance > 50 && !didItAlready){
     doIt();
     didItAlready = true;
}

You simply need a variable to keep track of whether or not it has been done.  If and when you want to do the action again then set your variable back to false.

You just need a global variable to track whether it is done or not like this...
//  other Codes

bool State=0;

void setup(){

// other Codes...

}

void loop(){

if(distance <= 150 && State==0){

personPresent(); // This function should get executed only once
State=1;

}else if(distance>150 && State==1){

personAbsent(); // This sould also get executed once
State=0;

}

}

The global boolean variable ''' State ''' will keep track of how and when the functions need to be executed once, whenever conditions are met. And the boolean variable changes everytime (distance AND Sate) the conditions are met triggering those functions once per bool update.

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

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


text:
Basic Serial Transmission Protocol
I have a small piece of code here that I hope to run on Arduino. Basically what this code is doing is, it takes a nibble from the user, appends a startbit to it, and transmits the code through a transmitter module. The receiver end receives the bits and checks if startbit is being received. If startbit is not being received, then it prints out whatever was transmitted. If startbit is received, then it doesn't print the startbit, just the nibble all in one line.
My question is: is it convention/clever to use the bool array or should I not do that? Second, is there a way to make my code more efficient? Where can I clean it up? Also, is my code legible or very convoluted?
#include <Arduino.h>
#include <WirelessComm.h>

int tx_pin;
int rx_pin;
WirelessComm::WirelessComm(int rxPin, int txPin)
{
    pinMode(rxPin, INPUT);
    tx_pin = txPin;
    rx_pin = rxPin;
}

int countDigit(long n)
{
    int count = 0;
    while (n > 0)
    {
        n /= 10;
        count++;
    }
    return count;
}

void getDigit(bool *data, long num)
{
    int cd = countDigit(num);
    long shift = 1;
    for (int i = 0; i < cd; i++)
    {
        data[i] = (num / shift) % 10;
        shift *= 10;
    }
}

int WirelessComm::writeTx(long nibble)
{
    int i;
    bool data[11]; // warning: I didn't check for buffer overrun!
    int32_t startBit = 110101L; // larger than 32767, so cannot be in int
    if(nibble != 0)
    {
        int sbLen = countDigit(startBit);
        for (int i = 0; i < (int)(sizeof(data) / sizeof(data[0])); i++)
            data[i] = 0;
        getDigit(data, startBit);
        getDigit(data + sbLen, nibble);
    }
    else
        return -1;

    for(i = 0; i < 10; i++)
    {
        if(data[i] == 1)
        {
            digitalWrite(tx_pin, HIGH);
        }
        else
        {
            digitalWrite(tx_pin, LOW);
        }

    }
    return 1;
}

int WirelessComm::readRx(long nibble)
{
    bool first = 0;
    bool second = 2; //initially set to some random value
    bool third = 2;
    bool fourth = 2;
    bool fifth = 2;
    bool sixth = 2;
    bool counter = 0;
    bool val = 0;
    while(true)
    {
        first = digitalRead(rx_pin);
        if(first == 1);
        {
            second = digitalRead(rx_pin);
            if(second == 1)
            {
                third = digitalRead(rx_pin);
                if(third == 0)
                {
                    fourth = digitalRead(rx_pin);
                    if(fourth == 1)
                    {
                        fifth = digitalRead(rx_pin);
                        if(fifth == 0)
                        {
                            sixth = digitalRead(rx_pin);
                            if(sixth == 1)
                            {
                                while(counter < 4)
                                {
                                    val = digitalRead(rx_pin);
                                    Serial.print(val);
                                    counter++;
                                }
                                Serial.println();

                            }
                            else
                                Serial.println(first);
                                first = digitalRead(rx_pin);
                        }
                        else
                            Serial.println(first);
                            first = digitalRead(rx_pin);
                    }
                    else
                        Serial.println(first);
                        first = digitalRead(rx_pin);
                }
                else
                    Serial.println(first);
                    first = digitalRead(rx_pin);
            }
            else
                Serial.println(first);
                first = digitalRead(rx_pin);
        }
        else
            Serial.println(first);
            first = digitalRead(rx_pin);
    }
}

if(fourth = 1) - that, and all your similar tests, are wrong. That is assigning and then testing. So the if will always be true in this case.

If you want to bit-bang, I suggest you look at how SoftwareSerial does it.

Hey @NickGammon that if statement was a typo. And I initially used SoftwareSerial to do all my hardware tests. However, I'm trying to make my own library without the extra fluff. I had a very very hard time trying to understand what is happening in SoftwareSerial's code.

So to clarify, SoftwareSerial uses bit-bang? How are you able to tell?

What you are doing is called "bit-banging" (wikipedia link) but you have no guarantees about the timing of your bits.
In your writeTx routine you are changing tx_pin at some rate which depends on:

the clock speed of your MCU
the code that the C compiler generates

Moreover, the timing will be all screwed up if you happen to get an interrupt while sending the bits.
The same applies to your read routine.
The Arduino (really the Atmel MCU) has special hardware to perform both synchronous and asynchronous serial IO. The set up is rather complex because the hardware
is very versatile and capable of a lot of different functions.
In particular, it can deliver the bits at a specific baud rate for you so your code doesn't have to do it. It can also read in a serial stream and set a flag or invoke an interrupt when a complete word has been received.
This article can give you an idea of what the USART in an Atmel processor is capable of:
http://maxembedded.com/2013/09/the-usart-of-the-avr/

But the thing is, I don't want to do synchronous communication. I actually want to do asynchronous and then implement different ways of synchronizing the clock such as NRZ.

Also, i was told that if i know the interval of data, i can implement that and not worry about the clock signal. How should I approach that? What exactly does the interval of data* mean?

You still want hardware to do this for you. "knowing the interval of data" just means that you have set a specific baud rate - i.e. so many bits per second. The USART can handle asynchronous comms, and it can monitor the receive pin and respond to changes a lot faster than you can in code.

OO! i see what you are saying. ok ok. And so, should I just restart the code I'm trying to make? I've tried to create a buadrate function before, but I had very bad luck with it. One big problem was, when i tested how many times my receiver transmitter a bit in 1 second, it was 1000. So it wouldn't really be any use if I set the baud rate to be 1200 or something. Cause if the maximum it sent (since the pin was on high for the whole second) was 1000 transmissions, that's max hardware capability. right?

What you do is start learning how to program the USART of the AVR. Using the USART you can reliably handle 1Mbit per second. The article I mention in the answer is a good start. Start with getting standard RS-232 working. Get two Arduinos talking to each other over RS-232. The USART has a lot of registers you can configure - it takes a while to fully understand what can be done with it. And an upvote would be nice if you've found any of what I've said to be helpful.

Thank you very much! I have upvoted it. As soon as I reach 15 rep points, you will see the change! thank you so much!

Cause if the maximum it sent (since the pin was on high for the whole second) was 1000 transmissions, that's max hardware capability. right?  - if you read the datasheet, you will see that at 16 MHz clock the maximum baud rate is 2 Mbps. That's a lot more than your 1000 bits per second.

So to clarify, SoftwareSerial uses bit-bang? How are you able to tell?

By reading the code. For example, this is how it reads 8 bits. It does a delay (which you don't) for the exact amount of time, and then reads the pin, and "ors" it into the variable which is the assembled byte.
// Read each of the 8 bits
for (uint8_t i=0x1; i; i <<= 1)
{
  tunedDelay(_rx_delay_intrabit);
  DebugPulse(_DEBUG_PIN2, 1);
  uint8_t noti = ~i;
  if (rx_pin_read())
    d |= i;
  else // else clause added to ensure function timing is ~balanced
    d &= noti;
}

And to write the 8 bits:
// Write each of the 8 bits
for (byte mask = 0x01; mask; mask <<= 1)
{
  if (b & mask) // choose bit
    tx_pin_write(HIGH); // send 1
  else
    tx_pin_write(LOW); // send 0

  tunedDelay(_tx_delay);
}

Your rather elaborate nested if just seems complete overkill, when you see how SoftwareSerial does it in half a dozen lines.

Another typo:
if(first == 1);

You don't want that semicolon.

Second, is there a way to make my code more efficient?

Use loops, like SoftwareSerial does.

Also, is my code legible or very convoluted?

Very convoluted.

Where can I clean it up?

I suggest you browse through the SoftwareSerial library for ideas.
Meanwhile, HardwareSerial is available, so you don't need to write any of this. For that matter, SoftwareSerial is available too. If you are just doing it to learn, well and good.

You really should read about loops. Whenever I have to do something 8 times I have a loop of 8 (or even for "x" times, a loop of "x"). Unrolling into 8 different variables is just confusing and prone to errors. As you had, before you fixed it, doing if(fourth = 1) instead of if(fourth == 1).

Thank you very much for that explanation. I will do what you suggested as well.

Hey, the actual software serial library, frmo the installation files looks much different from the snippets you posted. Can you please show me where you are pulling your code from? Thank you so much!

I got that from IDE 1.0.6. It looks like they changed it a bit in 1.6.5, however conceptually it is similar. The changes look like efficiency tweaks to me. Fundamentally it is the same. They are reading/writing bits with a carefully calculated delay between each one.


text:
Synchronization and Implementing hamming code on Software Serial
I want to learn and use Hamming Code. Would it be wise to
alter the Software serial library to do this or just change the data being
transmitted in the actual Arduino sketch?
Also, for means of better synchronization, what would be the best method with regards to these tx/rx modules working with the Arduino using Software Serial. Am I constrained to using the built in synchronization from the library or may I also implement other forms of synchronization, like manchester and NRZ coding? If so, any guidance here?
EDIT
For implementing Hamming code, what if the interference occurs on the parity bit? Is there a way around this problem?

Could look something like this:
class HammingStream : public Stream {
public:
  HammingStream(Stream& ios) : m_ios(ios) {}
  virtual size_t write(uint8_t byte);
  virtual int read();
  virtual int available();
  virtual void flush();
protected:
  Stream& m_ios;
  uint8_t encode4(uint8_t nibble);
  uint8_t decode8(uint8_t code);
};

size_t HammingStream::write(uint8_t byte)
{
   m_ios.write(encode4(byte >> 4));
   m_ios.write(encode4(byte & 0xf));
   return (1);
}

int HammingStream::read()
{
  if (available() == 0) return (-1);
  uint8_t nibble = decode8(m_ios.read());
  return ((nibble << 4) | decode8(m_ios.read());
}

int HammingStream::available()
{
  return (m_ios.available() / 2);
}

void HammingStream::flush()
{
  m_ios.flush();
}

Then you could:
HammingStream HammingSerial(SoftwareSerial);
HammingSerial.println(F("hello world"));

The above leaves out the encoding/decoding but also error detection. Hamming decoding can capture up to two bit errors and do one bit correction (on 4-bit data).
An example of implementation of the coder may be found in Cosa. Here Hamming(8, 4) is used to improve VirtualWire performance. Please note that the coder table is adjusted for RF and avoiding DC signal (i.e. long periods of zero or one).
Cheers!

You can use this info and code: Hamming(8,4) with Arduino.
There's a PDF with documentation about the process of creating a class that implements hamming(8,4) and a link to the source code.
You can use any class that derives from Stream (like Serial or SoftwareSerial).
Edit: If you want to implement a Hamming ECC in a Arduino it would be useful to precompute all the possible message values (you'll find more info at the link above). In a Hamming(8,4) your message is 1byte = 4bits + parity 4 bits; so you must divide your bytes in nibbles. It would be better to put all that stuff (code, decode, manage the upper/lower part of the byte, etc...) in a class. An example using the Hamming class from the link above:
Tx:
#include <hamming.h>

Hamming hamming(&Serial);
char message[] = "Hello World!!";

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

void loop()
{
  hamming.write(message);
  delay(1000);
}

Rx:
#include <hamming.h>

Hamming hamming(&Serial);
char message[Hamming::SIZE];

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

void loop()
{
  if(hamming.isMessageReady())
  {
    hamming.read(message);
    Serial.println(message);
  }
}

If you need to send other kind of info: a float, integer... you can do it, but I think it's a better idea to tokenize/detokenize your information and handle it like a "string".
P.S. You can use any kind of physical layer insofar as it's a child of Stream: Serial, SoftwareSerial...But I've only tested over Serial.

This is a good link. However, in the case of future link death, it would be good if you could edit your answer to include a summary of the info and the salient part of the code required.

The SoftwareSerial can only transmit and receive EIA-232 formatted packets.  That is what it is written to do, and that is what it does.
It cannot transfer any other format.
If you want to use other encoding techniques you will have to use a different method than SoftwareSerial.
That might involve writing your own bit-banging routines in your sketch or in your own library, or using SoftwareSerial as a basis to adapt into your own library.
Note that the SoftwareSerial library is written in such a way that EIA-232 packets are a requirement - the falling edge of the start bit triggers reception of one packet - any other encoding that doesn't have that kind of start bit arrangement would require some completely different method of arranging the reception.

So I could just make a simple function inside my sketch, that when I transmit a number, it automatically reorganizes the data chunk with parity bits in it. And then transmits this new data as if it's just the payload. And then I can have the receiver sketch pick up this received data, and process it in another function inside the sketch right? Or would this not be a smart thing to do?

I'd much rather just make my own library. But would this library just restructure the data and call SoftwareSerial's write function(essentially the same thing as what i explained above)? Or would I have to completely rework the write function all together?

Hello, is there any advice you can give me about my EDIT. Also, would it not be wise to not implement use any NRZ coding on Arduino? @Majenko

authors: ნიკო ნარიმანიძე


text:
Upload Assembly to AVR on a breadboard using Arduino as ISP
I try to learn assembly and use an arduino uno R3 to act as a programmer. i have build a standalone circuit with an atmega328p, can upload usual sketches (written in c) and have also sucessfully burned the bootloader to the external chip with the arduino as an isp but i cant bring my assembly code onto the chip on the breadboard. i tried it with avrdude and the following command
avrdude -C avrdude.conf -p atmega328p -c avrisp -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i

and also
avrdude -C avrdude.conf -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i

but the code is always uploaded to the chip on the arduino - not to the one on the breadboard. can anyone lead me how to upload my assembly programm to the standalone chip on the breadboard using the arduino as isp? is this possible anyway?
EDIT This command worked for me
avrdude -C avrdude.conf -v -v -v -v -p atmega328p -c stk500v1 -P /dev/ttyACM0 -b19200 -Uflash:w:test.hex:i

You're using your Arduino as the programmer, but you're using "avrisp"?

i do so because the arduino ide doesnt compile and upload my asm code correctly - just inline asm. what should i use? -c arduino? i also tried that without any success.

Hello folks is my question bad written or does nobody have an answer?

It would be good to definitively separate the problem into pieces.  If you can get a bootloader on the breadboard chip, such that you can upload sketches to it over (USB-) serial rather than ISP, then you should also be able to upload valid assembly code built with a bootloader-compatible memory footprint.  But if you are using an Arduino as an ISP programmer, and are having problems differentiating between its bootloader and the programmed ISP sketch, then you need to solve that first.  Making sure the ISP sketch uses a different baud rate than the bootloader could help a lot.

thank you very much. im really new to that stuff, sry. where can i see what baudrate the bootloader uses? in the arduino ide its just a menu button i have klicked "burn bootloader". i dont have a usual programmer, just the arduino.

very sad, no answer even on stackexchange. maybe its impossible what i want to do. thank you all anyways if i'll find a solution, i will tell you too.

Hello folks is my question bad written or does nobody have an answer? - so, no answer after one hour, huh? Maybe a lot of people are in bed. Patience, old chap!

Try uploading the blink sketch to the standalone atmega328 first. Once you get that to work you can get the right command form the console (after enabling verbose output, in the settings).

@Gerben Thank you :D shame on me that i havent thought about that. works perfectly. Wont you add it as an answer? i cant give points to comments.

Great to hear you got it working. Maybe you could add the right command for in case someone else has the same problem in the future.

Try uploading the blink sketch to the standalone atmega328 first.
Once you get that to work you can get the right command form the console (after enabling verbose output, in the settings).


text:
Is there any DS2482 I2C to 1-Wire bridge functional library?
Please let me know if you know any good library for DS2482 I2C to 1-Wire bridge.
I tried to use the DS2482_OneWire library  but I got errors when trying to run the library examples (Read_temp_sensors and Scan_1Wire_Bus):
Error for Read_temp_sensors:

Read_temp_sensors:2:10: fatal error: DallasTemperature.h: No such file or directory

Error for Scan_1Wire_Bus:

Scan_1Wire_Bus
C:\Users\myuser\Documents\Arduino\libraries\DS2482_OneWire-master\OneWire.cpp: In member function 'uint8_t OneWire::waitOnBusy()':
C:\Users\myuser\Documents\Arduino\libraries\DS2482_OneWire-master\OneWire.cpp:121:3: error: 'delayMicroseconds' was not declared in this scope
delayMicroseconds(20);
^~~~~~~~~~~~~~~~~
exit status 1 Error compiling for board Arduino Nano.**

Thank you.

Please take a look at this library, https://github.com/mikaelpatel/Arduino-OWI. It handles both DS2482 and GPIO implementation. https://github.com/mikaelpatel/Arduino-OWI/blob/master/examples/DS2482/DS18B20/DS18B20.ino

The documentation may be found here, https://mikaelpatel.github.io/Arduino-OWI/dc/dfe/Hardware_2OWI_8h.html and https://mikaelpatel.github.io/Arduino-TWI/d4/d53/classDS2482.html

Thank you very much!

I guess to solve the first error, you also need this library, which contains the DallasTemperature.h file. The file get's included, but is not contained in the DS2482 library. Unfortunately there is no clue for that in the readme of the library. The author didn't commit anything since 2014, so the development of the library can be considered dead from that side. Though some people have forked the library to make little changes.
And the solution to the second error is described in this issue of the DS2482 library (just adding an include of "Arduino.h" in the OneWire.cpp file).

Hello @chrisl, Thank you for your prompt answer. I don't know how to implement it: "// Constructor with no parameters for compatability with OneWire lib
OneWire::OneWire()"... ecc " I still get an error for the second issue: bool isAllZeros(const uint8_t* const scratchPad, const size_t length = 9);
   ^~~~~~~~~~   Maybe you can still help me...

Please include your current code into your question, then I can test this myself

Hello @chrisl. Thank's again for your time. Firstly I just want to run the examples included in the library. So the last error presented before was associated with Scan_1Wire_Bus.  Please let me know if you are able to run all the ex file. Thank you

I dowloaded the DS2482 library and also the Arduino-Temperature-Control library, as described in my answer. After adding include "Arduino.h" to the top of OneWire.cpp I could successfully compile the example sketch Scan_1Wire_Bus.ino` from the DS2482 library for the Arduino Nano. I use Arduino IDE 1.8.9

Hello @chrisl.Unfortunately,for me is still not working.If I install only 2 libraries that you recommend before I'm getting errors when I'm using #include <DallasTemperature.h>.If I install the OneWire library directly from Manage Library I will not receive errors for the inclusion of "DallasTemperature.h": but I'm getting new errors I think because both libraries (DS2482/OneWire) has the same name "OneWire ".Because of this the object defineded in DS2482 are not visible anymore (class OneWire'has no member named 'checkPresence') Please let me know if I'm doing something wrong now . Thank you

Then you have 2 options: You can delete the OneWire library and only keep the DS2482 one. Or you can rename the DS2482 OneWire class to a different name. For the second option you would need to rename it both in OneWire.h and OneWire.cpp

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


text:
How to switch between multiple BMP180 sensors?
I have six BMP180 sensors for measuring temperature and pressure. The problem is that I can get the value from one sensor but I need values from all six sensors using a single Arduino Mega board. How can I do that? I have already tried powering each sensor with digitalWrite but that didn't work. If you have a solution, can you also provide the code for that?

what have you tried? ... what problems did you have?

The BMP180 uses the I2C bus and you cannot simply turn off the device, since that can block the I2C bus. Also it has only one, not changeable address. Thus you would need one I2C bus for every BMP180.
So know you have 2 ways to go:

You could use a Software I2C library and define one I2C port for each BMP. That would use 12 digital pins and you need to find a fitting library, that supports multiple instances. Due to the timed nature of the I2C bus, you most likely will only be able to service one bus at a time.
You could buy a multiplexer chip for both signal lines. Then you could switch the SCL and SDA lines to each BMP. For that you need the multiplexer chips, 2 pins for I2C and 3 digital pins for input of the multiplexer chips (assumes an 8-channel multiplexer)

how can i define port ports for each bmp, i checked the I2C library on github but i am a bit confused. Also which library should i use as i am alreading using bmp180 library and i dont think it supports multiple instances.

I don't know, what you mean by "the I2C library on github". There are surely many I2C libraries on github. You cannot use the Wire library, since it is a hardware I2C library, not a software I2C library. I haven't used such a library, so I cannot suggest a good one. I googled "github arduino software i2c" and found this in the first few results. You need to try yourself and look, which library gives you the needed functionality.

Maybe you don't find a library, that can have multiple instances, but where you can repeatedly begin() the library with different pins, everytime, that you want to communicate with one of the BMPs.

thanks chris i will look into it.

If you have n-MOSFETs available, a simple multiplex solution would be: SCL directly from master to all slaves. SDA from master to Source of MOSFET (for each slave one MOSFET), Drain of MOSFET with pull-up resistor (e.g. 4.7k) will be the SDA signal. Gate of MOSFET to select slaves (active <-> Gate=high level). Make sure your MOSFET turns on based on your used voltage levels.


text:
Nokia 5110 LCD number display problem
I have a problem regarding a Nokia 5110 LCD display. I am currently building a soldering station based on a PID controller. The original code was using a 7 segment display and I adapted the code to the Nokia display.
The problem is that when I rotate the potentiometer, the "read temp" and "set temp" is showing the exactly the same number, and after I finish rotating the potentiometer, the values return to their normal number.
How can I solve this problem ?
This is my code: https://pastebin.com/inPtkniX
This is the original project: https://www.allaboutcircuits.com/projects/do-it-yourself-soldering-station-with-an-atmega8/
//Soldering station Software using PID
//Thank you Alex from https://geektimes.ru/ for help with led array function
//AllAboutCircuits.com
//epilepsynerd.wordpress.com

#include <PID_v1.h>
#include <PCD8544.h>

PCD8544 lcd;
unsigned long updaterate = 500; //Change how fast the display updates. No lower than 500
unsigned long lastupdate;
int temperature = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Define the aggressive and conservative Tuning Parameters
double aggKp = 4, aggKi = 0.2, aggKd = 1;
double consKp = 1, consKi = 0.05, consKd = 0.25;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

void setup() {
  lcd.begin(84, 48);
  //We do not want to drive the soldering iron at 100% because it may burn, so we set it to about 85% (220/255)
  myPID.SetOutputLimits(0, 220);
  myPID.SetMode(AUTOMATIC);
  lastupdate = millis();
  Setpoint = 0;
}

void loop() {
  lcd.clear();
  //Read temperature
  Input = analogRead(0);
  //Transform the 10bit reading into degrees celsius
  Input = map(Input, 0, 450, 25, 350);
  //Display temperature
  if (millis() - lastupdate > updaterate) {
    lastupdate = millis();
    temperature = Input;
  }
  //Read setpoint and transform it into degrees celsius(minimum 150, maximum 350)
  double newSetpoint = analogRead(1);
  newSetpoint = map(newSetpoint, 0, 1023, 150, 350);
  //Display setpoint
  if (abs(newSetpoint - Setpoint) > 3) {
    Setpoint = newSetpoint;
    //temperature = newSetpoint;
    lastupdate = millis();
  }
  double gap = abs(Setpoint - Input); //distance away from setpoint
  if (gap < 10) {
  //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  } else {
    //we're far from setpoint, use aggressive tuning parameters
    myPID.SetTunings(aggKp, aggKi, aggKd);
  }
  myPID.Compute();
  //Drive the output
  analogWrite(11, Output);
  //Display the temperature
  show(temperature, newSetpoint);
}

void show(int value, int newspnt) {
  lcd.setCursor(0, 0);
  lcd.print("READ TEMP");
  lcd.setCursor(0, 1);
  lcd.print(value);
  lcd.setCursor(0, 2);
  lcd.print("SET TEMP");
  lcd.setCursor(0, 3);
  lcd.print(newspnt);
  delay(200);
}

Please include the code into your question, so that it stands alone, even, when the pastbin link becomes invalid

Look at line 55, where you are doing this
temperature = newSetpoint;

There is no reason to give temperature the same value as the set point. It does not make sense. And the temperature variable is the same, that you are using to display.
So, while you are changing the setpoint, the temperatur variable gets overwritten with the setpoint. When you are not changing it anymore, the measured temperature is still in this variable, when you are displaying it.
Just remove the mentioned line.


text:
Cannot start Arduino IDE after playing with several versions of it
On my Linux Mint 17 Quiana I have manually downloaded and ran several versions of the arduino IDE (1.05 which is in the repo, 1.6.x for some time, now 1.8.3). Things worked like a charm.
Now I am trying to get the IDE 1.8.5 going, but I cannot get the IDE started. Started means: I download, extract the files to a directory and run the install.sh command such that the desktop icon gets created. This finishe with a success message. Now I am clicking on the desktop icon, but nothing happens.
Need to say that the IDE 1.05 which comes as a package with Qiana works just fine. I have run the install.sh of both to and fro, but only the 1.05 will start properly. I checked on the desktop link, the execution rights, user, group etc. They are all looking fine for 1.8.5 but it wont start.
I tried to start the 1.85 arduino IDE from the command line - hoping to get some clue from error messages:
java -DAPP_DIR=/opt/arduino-1.8.5/ Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel processing.app.Base

--> running this it tells me, that the main class cannot be found.
Any hints where I am going wrong? Are there any config files to be cleared up, paths to be set ...?

You do not need to install Arduino at all. In fact I have never had it work right due to things not being found.
All you need to do is, from a terminal, run the arduino command in the extracted directory:
fred@computer:~/arduino-1.8.5 $ ./arduino

Any errors that then throws will be a clue as to why it doesn't want to work.

Hi there
thanks for replying. I found the issue based on the idea to call arduino from the command line as proposed by you. Stupid me had downloaded the 64bit version but am still running on a 32bit kernel. I now got the 32 bit IDE and it works like a charm.
The problem was so weird - it had to be something stupid :-/
Best
Al

1.05 is the latest available packaged version (and is quite dated).
You can download and (optionally) install the new version. See Installing Arduino IDE on Linux
Either remove (or ignore) the old version. Apart from the additional support the new version supplies, the directories differ - you can either change to the new (recommended) or change the settings.
There is no NEED to "install" the new version. The supplied script DOES NOT install in the traditional sense, it merely installs GUI links to the download.


text:
How do I properly convert a pointer (uint8_t* or void*) to a "normal" integer?
I'm writing a program for arduino that needs dynamic memory allocation frequently, but as I don't want the memory to get fragmented, I'm also writing a "memory handler" for it. This memory handler would need to do calculations involving both pointers and size_t variables, like this (example code is not part of program, but the structure of the calculations is the same):
size_t freeMemSize = nextPointer - currentPointer - currentSize;

Which would calculate the size of free memory between two reserved spaces.
Of course, arduino doesn't want to swallow this code, as it compares incompatible types. My questions are:

Is a cast to the correct integer type enough to solve the problem?
If it is, what is the "normal integer" counterpart of a pointer?

I guess this varies from processor to processor, so I should look for something like size_t, but for memory indices instead of sizes.
Board: Uno, Nano
IDE version: 1.8.2

If you want to do ordinary math rather than pointer math, intptr_t is specified to be an integer type capable of holding a pointer.

I think you might get more answers if you moved this to stackoverflow since it not specifically an Arduino issue, once you have the solution you could run it on any processor.

Assume the following declarations:
uint8_t* nextPointer;
uint8_t* currentPointer;
size_t currentSize;

Then the expression is valid:
size_t freeMemSize = nextPointer - currentPointer - currentSize;

If any of the pointers are void* the compiler cannot calculate the expression (pointer or size).
Cheers!

Yes, that will be it. One of my pointers were void* type. Thanks.

Beware this mixing of pointers and size_t only makes sense for pointers to objects of size 1.

@ChrisStratton The code is REALLY alpha version, and needs a lot of work, including variable types. But thanks for the warning, each advice helps to understand programming arduino a bit more.


text:
Arduino with external Wi-Fi antenna?
I need to create a project where I need to send data via Wi-Fi using an Arduino.
I need the Arduino to have a U.FL connector to place an external Wi-Fi antenna (I can't use the MKR1000 with integrated Wi-Fi antenna because the Arduino will be placed inside a metal box).
Is there any solution-like Arduino for this without the need to use an external board like: SparkFun WiFi Shield - ESP8266 ?
I could also use the BeagleBoard Green Wireless that contains this U.FL connector for an Wi-Fi antenna, but I wanted something smaller such as an Arduino.
PS: Wi-Fi is the only option.

some Wemos board clones have U.FL connector as alternative to on-board antenna https://robotdyn.com/wifi-d1-mini-esp8266-dev-board-usb-cp2104.html

It is commonly stated that many WIFI components have 50ohm impedance.  If true then swapping out internal and external antennas may be possible.  Even on boards which do not have an external antenna connector.  Notice that the SparkFun product you pointed to might be switchable to the external antenna by un-soldering, moving and re-soldering a jumper on the PCB (moving R10 to position R11 which is a do-not-place part).

I had "Grove UART Wifi" V1.0 with ceramic antenna in a metal box without external antenna. the AP was upstairs and the esp8266 worked without problems


text:
Wiring and Connecting WS2801 to NodeMCU ESP8266
After hours of searching for a solution and try many ways of wiring, I must asking here for Help:
I'm using a ESP8266 (ESP-12E) with a WS2801 - 4 Wire LED Strip and using this Pinout-Diagram to connect WS2801 wires to NodeMCU.
https://alexbloggt.com/wp-content/uploads/2015/10/nodemcu_pinout_700.png
Here is my Wiring:
LED     ESP
====   =====
5V --> Vin
GND --> GND
CK --> GPIO2 (D4)
SI --> GPIO3 (RX)

I have found this sample Program which should turn on and off all LEDs one after each other for 100ms. But it happens nothing after compiling and uploading it to NodeMCU board using Arduino IDE. Any help is highly appreciated.

//This program was taken from the FirstLight.ino supplies with the FastLED library
// It has been modified for use with a NodeMCU for use in a tutorial by NQMakerSupplies.com.au
// Hosted at theMakers.org.
//
// Special thanks to the people behind FastLED.io and all the contributors :)

#define FASTLED_ESP8266_NODEMCU_PIN_ORDER   // map output pins to what they are called on the NodeMCU
#include "FastLED.h"

///////////////////////////////////////////////////////////////////////////////////////////
//
// Move a white dot along the strip of leds.  This program simply shows how to configure the leds,
// and then how to turn a single pixel white and then off, moving down the line of pixels.
//

// How many leds are in the strip?
#define NUM_LEDS 10

// Data pin that led data will be written out over
#define DATA_PIN 3

// Clock pin only needed for SPI based chipsets when not using hardware SPI
#define CLOCK_PIN 2

// This is an array of leds.  One item for each led in your strip.
CRGB leds[NUM_LEDS];

// This function sets up the ledsand tells the controller about them
void setup() {
    // sanity check delay - allows reprogramming if accidently blowing power w/leds
   delay(2000);
   FastLED.addLeds<WS2801, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

// This function runs over and over, and is where you do the magic to light
// your leds.
void loop() {
   // Move a single white led
   for(int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed = whiteLed + 1) {
      // Turn our current led on to white, then show the leds
      leds[whiteLed] = CRGB::White;
      // Show the leds (only one of which is set to white, from above)
      FastLED.show();
      // Wait a little bit
      delay(100);
      // Turn our current led back to black for the next loop around
      leds[whiteLed] = CRGB::Black;
   }
}

Are you sure the VIN pin is providing 5V? It looks like it's only for powering the board. If you have LoLin's V3 board, it has a USB power out pin marked as VU.

I have a Amica (V2) and pretty sure that Vin outputs 5V. Because once I connect the led strip to Board all leds turn white and remain. If I connect CK to CLK and SI to MOSI, I can see a fancy blinking christmas lights during the Upload. Is DATA_PIN 3 --> GPIO3 and CLOCK_PIN 2 --> GPIO2 correct?

Just to make sure, NodeMCU has a different/weird numbering compared to all other ESP modules for the GPIO pins, you are aware of this? Just google 'nodemcu pin' or so, plenty of images.

The second thing to consider is voltages, ESP8266 GPIO voltage is 3.3V, if WS2801 is powered from 5v, I'd guess that it also expects a 5v data signal, so you might need a level converter of some sort. Again google, people would have already documented this :)

Also, this might be usefull, a bit, mayby https://github.com/FastLED/FastLED/wiki/ESP8266-notes

Thank you for your suggestions @cranphin, but as I mentioned before, I have googled many hours before giving up and ask my question here. So providing tip how can I google my problem does not really help forward. What I need is a concrete tip for wiring the NodeMCU and know if my wiring is wrong.

Changing the first line from
 #define FASTLED_ESP8266_NODEMCU_PIN_ORDER

to
 #define FASTLED_ESP8266_RAW_PIN_ORDER

has solved the Problem.

Had the same problem, and this was the solution for me as well, thanks for posting!


text:
Simple Text input using 5 buttons
So I have to get this function done but I'm not so bright and got confused.
(excuse me! I'm total noob)
The function is basically inputing text using five buttons, directional buttons and an ok button. The up and down buttons will be used to cycle through letters (a-z), and the left and right buttons will be used to control which array to cycle letters.
The control will be:

up button (up): ASCII-1 (z, y, x...)
down button (dw): ASCII+1 (a, b, c...)
right button (ri): array[i] ~> i+1 (go to next character/array)
left button (le): array[i] ~> i-1 (go to previous character/array)
ok button (ok): confirm text and changes the limit to stop function looping

I can't get it work with this code I write.

void intext()
{
  int lim=16;
  lcd.setCursor(0,1);
  lcd.print(input);
  for(i=0; i<lim ; )
  {
    if(digitalRead(dw)==HIGH)
    {
      if(input[i]<'a')
        input[i]='z';
      if(input[i]>'z')
        input[i]='a';
      input[i]=input[i]+1;
      delay(1000);
    }
    if(digitalRead(up)==HIGH)
    {
      if(input[i]<'a')
        input[i]='z';
      if(input[i]>'z')
        input[i]='a';
      input[i]=input[i]-1;
      delay(1000);
    }
    if(digitalRead(ri)==HIGH)
    {
      delay(1000);
      i=i+1;
    }
    if(digitalRead(le)==HIGH)
    {
      delay(1000);
      i=i+1;
    }
    if(digitalRead(ok)==HIGH)
    {
      lim=i+1;
      delay(1000);
    }
  }
}

void loop()
{
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Type your text:");
  intext();
  lcd.setCursor(0,0);
  lcd.print("Success!!");
  lcd.setCursor(0,1);
  lcd.print(input);
}

The result I wanted it to be is like this:
first you got the "type your text:" on the first row and blank in the second row.
our cursor is in the first column of the second row, so we can cycle through the alphabet letters. if you press right you can edit the next column of second row. you can get to the previous column in second row by pressing left. you can input up to 15 characters.
after done typing pressing ok will stop the typing and you will see "Success!!" in the first row and typed text in the second row.
Please help. I'm stumped.
Thank you.

Could you clarify the current behavior (you just said it does not work but that does not give any leads where to investigate)? Also, it would be good to see the setup() code and the variables declaration. Finally, a description if your wiring would be nice too, in particular you did not mention if you use pullup or pulldown resistors.

Thank you and sorry for not making things clear, I'm really clueless about things. I'm not very keen either so I just kind of trying to rewrite codes from scratch or trying to change how things will work. I guess you can check the complete code here http://pastebin.com/knbXsen4 ;;
My design... I'm not too sure if this good or bad, but after I tested it, and it does need debouncing. Here's the picture  http://i.imgur.com/KHn3zzh.png  again, thank you for your points. I'll try to be more informative and clear next time.

Several issues in the code you posted:

Every change to the text you do inside the for loop, will not be reflected to the LCD until the for loop will end (when i<limit will no longer be a true statement). You might want to add an additional code, inside the for loop and outside any of its conditional statements, that will repeatedly set the cursor and print input to the LCD. Something similar to the code you have prior to the for loop:
void intext()
{
  ... // rest of the code until the for loop

  for (int i; i<limit; )
  {
    ... // all the conditions for up/down/left/right/ok

    lcd.setCursor(0,1);
    lcd.print(input);
  }
}

Another problem is that when the user clicks left, the counter should be decremented, not incremented, and you should check for left boundary:
if(digitalRead(le)==HIGH && i>0) // left boundary check added
{
   delay(1000);
   i=i-1; // and not i=i+1;

}

After clicking Ok, and since the for loop does not increment i, the condition in the for loop (i<limit) will stay true, and the loop will not end until the user will click Right once more. To mitigate this, change the following
if(digitalRead(ok)==HIGH)
{
  lim=i; // and not: lim=i+1;
  delay(1000);
}

Otherwise, the user will have to click Right for completion, to increment i once more.

jfpoilpret comment about pull up/down is very important. Make sure you use pull up/pull down resistors in order to prevent input debounce (more details inside this link).

You're my light. Thank you.
Sorry for not giving a quality comment. I'm just... in awe..


text:
Serial Communication with two bluetooth modules on Arduino Mega
I'm trying to communicate with two bluetooth module (RN-42) on the Arduino Mega.
I studied about Serial communication in Arduino, and I used Serial1, Serial2 to get information at the same time from the modules.
At the setup period, baud rate will be set. The command "$$$" makes the bluetooth module go into the configuration mode. Until this, everything works pretty well.
The problem is, it seems nothing works inside the loop(). I think Serial1.print(inByte), Serial2.print(inByte) doesn't work properly. I checked the TX1, TX2 port whether it sends any data or not by using LED, and the LED never blinked.
Here's the code that I used.

void setup() {
  // initialize both serial ports:
  Serial.begin(9600);

  Serial1.begin(115200);
  Serial1.print("$$$");
  delay(100);
  Serial1.println("U,9600,N");
  Serial1.begin(9600);

  delay(100);
  Serial1.print("?");

  Serial2.begin(115200);
  Serial2.print("$$$");
  delay(100);
  Serial2.println("U,9600,N");
  Serial2.begin(9600);

}

void loop() {
  // read from port 1, send to port 0:

  while(Serial1.available()>0) {
    char inByte = Serial1.read();
    Serial.print(inByte);
  }

  while(Serial2.available()>0) {
    char inByte = Serial2.read();
    Serial.print(inByte);
  }

  // read from port 0, send to port 1:
  while (Serial.available()>0) {
    char inByte = Serial.read();
    Serial1.print(inByte);

    delay(10);
    Serial2.print(inByte);
  }
}

Thank you

Maybe try a Serial1.end() before the second Serial1.begin? Arduino reference documentation gives no specific info here. How do you exit command mode?

What i dont see is the part where you are asking module 1 to act as master, module2 to act as slave. And ask module 1 to connect to module 2.


text:
VisualMicro Can't compile in debug ('Serial' was not declared in this scope) for attiny84a
I was working on a project build initialy from the Arduino IDE to program an attiny84a (without a bootloader) using the board from https://github.com/damellis/attiny
I got an atmel-ice recently and I was trying to debug the arduino sketch using it.
I installed AtmelStudio (because I know it has an GUI debugger) and found VisualMicro that should help me to compile arduino sketch.
Unfortunatly as soon as a set the project to debug I got a compilation error :
'Serial' was not declared in this scope

(I don't have this error in Release mode).
My code doesn't use any serial (because I don't have any pin left), so this was wierd. I still tried to add the SoftwareSerial.h include (just in case) without success.
So I created an empty (I mean with only an empty setup() and loop() methods) and it throw the same error.
I tried to setup different versions of arduino IDE into VisualMicro (1.6.13, 1.8.1, 1.8.5 and 1.9 build 34) without success.
Then after a couple of hours I found the .cpp source generated by VisualMicro and it try to use the member "Serial" for some debugging reason.
I would like an easy way to integrate with arduino (all those library and easy to install library) and to be able to debug as well, what can I look for or do?
Thank

I found how to disable the vMicro debugging, in AtmelStudio open the "vMicro" menu then click the "Debugger" item and make sure the option "Atmel Studio Debugger" is checked.
1) Change the optimization flag to a usefull state (-Og or -O0) in order to NOT have "Unknown identifier" or "Optimized away" when looking at variable.
I tried:

Put -Og in the project property "Extra flags" (vMicro)
Before my code I added
#pragma GCC push_options
#pragma GCC optimize ("Og")

then at the end of my code
#pragma GCC pop_option

ANSWER: I probably fuckup in the rebuild because only the line below is enough (in the .cpp file):
    #pragma GCC optimize ("Og")

Replaced -Os in playform.txt (in this case it didn't work at all)

I saw a size changes in my binary (except for the last point), but when running the simulator I still couldn't see any value.
2) Couldn't start a debugging session
(When I try to change the debugging device it always crash AtmelStudio, I think it is because the target IC is force to ATSAM3X8E by the vMicro plugin which isn't supported on my computer, and because it isn't supported I can't change the target IC to attiny84a...)
ANSWER: When creating the project vMicro read the current board selected (yes before you even can select it) to detect if it has to create a 32 bits or 8 bits project
Also you MUST create a project with an .ino (even if it is empty) as the same name as the project in order to be able to compile.

'Serial' was not declared in this scope

This error is not surprising when compiling for ATtiny84 because in Arduino Serial refers to the hardware serial port and ATtiny84 doesn't have one.
But you didn't use Serial in your sketch so why should you get this error? The answer is this magical debug feature of Visual Micro that you desire. It turns out that on AVR microcontrollers such as your ATtiny84 all this actually consists of is Visual Micro automatically inserting various Serial.print() statements into your code, just as we always do manually to debug our code in the good old Arduino IDE:
http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-Explained.html
So in fact your sketch is attempting to use Serial without your knowledge or being able to see it! If you turn off debugging you should no longer get that error.
Visual Micro does allow you to change the debugging output to software serial:
http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-With-Different-Ports.html
but since you say you have no pins available that may not be any help.


text:
Arduino + SIM808 HTTP GET POST headers
I am trying to get working SIM808 with Arduino. Can GET and POST GPRS HTTP request but only what cames on it's just body from server side {"error":true,"message":"Unauthorized"}
but I need header as it brings cookie for session.
+CREG: 0,1

AT+SAPBR=3,1,"Contype","GPRS"

OK

AT+SAPBR=3,1,"APN","giffgaff.com"

OK

AT+SAPBR=3,1,"USER","giffgaff"

OK

AT+SAPBR=3,1,"PWD",""

OK

AT+SAPBR=1,1

AT+SAPBR=2,1

+SAPBR: 1,1,"xx.xxx.xxx.xxx"

OK
AT+HTTPINIT

OK
AT+HTTPPARA="CID",1

OK
AT+HTTPPARA="URL","http://www.xxx.co.uk/index.php"

OK
AT+HTTPPARA="UA","MH Tracker"

OK
AT+HTTPPARA="CONTENT","Content-Length: 42"

OK
AT+HTTPPARA="CONTENT","Content-Type: application/x-www-form-urlencoded"

OK
AT+HTTPSSL=0

OK
AT+HTTPDATA=41,30000

pass=xxxx&user=xxxx&action=xxxx

OK

AT+HTTPACTION=1

OK

+HTTPACTION: 1,401,39

AT+HTTPREAD

+HTTPREAD: 39

{"error":true,"message":"Unauthorized"}

OK

AT+HTTPTERM

I got some results, but with error, looks like my code have some junk characters
any advice

POST /client/index.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: www.mhprojects.co.uk
Content-Length: 41

pass=xxx6&user=xxx&action=xxx

SEND OK
HTTP/1.1 400 Bad Request
Date: Thu, 01 Feb 2018 00:38:56 GMT
Server: Apache
Content-Length: 357
Connection: close
Content-Type: text/html; charset=iso-8859-1

400 Bad Request

Bad Request
Your browser sent a request that this server could not understand.

Additionally, a 500 Internal Server Error
error was encountered while trying to use an ErrorDocument to handle the request.

Arduino code

    char data[350]="POST /client/index.php HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nHost: www.mhprojects.co.uk\r\nContent-Length: 41\r\n\r\npass=xxx&user=xxx&action=xxx";
int PowerOn = 12;//Power on pin
int Reset = 11;//Reset pin
char aux_str[50];
//////////////
void setup() {

  pinMode(PowerOn, OUTPUT);
  pinMode(Reset, OUTPUT);
  Serial.begin(9600);// UART baud rate

  power_on();

  Serial.println(F("Powering ON"));
  Serial.println();
  Serial.println(F("Connecting to the network..."));

  while( send_command("AT+CREG?", "+CREG: 0,1", 1000)== 0 );

}

/////////////
void loop() {

char buffer[200];

if (send_command("AT+CIPMUX=0", "OK", 2000) == 1)// Selects Single-connection mode
  {
  if (send_command("AT+CSTT=\"giffgaff.com\",\"giffgaff\",\"\"", "OK", 2000) == 1)// Sets the APN, user name and password
    {
      if (send_command("AT+CIICR", "OK", 10000) == 1)// Brings Up Wireless Connection
        {
          if (send_command("AT+CIFSR", ".", 3000) == 1)// Gets Local IP Address
            {
              if (send_command("AT+CIPSTART=\"TCP\",\"www.mhprojects.co.uk\",\"80\"","CONNECT OK", 10000) == 1)// Opens a TCP socket
                  {
                     sprintf(aux_str,"AT+CIPSEND=%d", strlen(data));
                     if (send_command(aux_str, ">", 1000) == 1) {

                     send_command(data, "SEND OK", 1000);

                     while (true)  {

                     read_UART_buffer(buffer,sizeof(buffer), 0);

                     }
                     Serial.println(buffer);
                     }
                                }
                                else
                               {
                             Serial.println(F("Error setup TCP connection\r\n\r\n"));
                           }
                        }
                      else
                    {
                  Serial.println(F("Error getting the IP address\r\n\r\n"));
                }
              }
             else
           {
         Serial.println(F("Error bring up wireless connection\r\n\r\n"));
        }
      }
    else
  {
Serial.print(F("Error setting the APN\r\n\r\n"));
    }
      }
        else
        {
          Serial.print(F("Error setting the single connection\r\n\r\n"));
         }

    send_command("AT+CIPCLOSE", "CLOSE OK", 1000);

    send_command("AT+CIPSHUT", "SHUT OK", 1000);

}

////////////////
void power_on() {

        // power on pulse
        digitalWrite(PowerOn,LOW);
        delay(500);
        digitalWrite(PowerOn,HIGH);
        delay(3000);
        digitalWrite(PowerOn,LOW);
        delay(3000);
}

///////////////
void reset()  {
  digitalWrite(Reset,LOW);
  delay(500);
  digitalWrite(Reset,HIGH);
  delay(3000);
  digitalWrite(PowerOn,LOW);
  delay(500);
}

///////////////////////////////////////////////////////////////////////////////////
int8_t send_command(char* ATcommand, char* expected_answer, unsigned int timeout) {

  uint8_t x = 0,  answer = 0;
  char response[50];
  unsigned long previous;

  memset(response, '\0', 50);    // Initialice the string

  delay(100);

  while ( Serial.available() > 0) Serial.read();   // Clean the input buffer

    Serial.println();
    Serial.println();
    Serial.println(ATcommand);    // Send the AT command

  x = 0;
  previous = millis();

  // this loop waits for the answer
  do {
    if (Serial.available() != 0) {  // if there are data in the UART input buffer, reads it and checks for the asnwer
      response[x] = Serial.read();
      Serial.print(response[x]);
      x++;
      if (strstr(response, expected_answer) != NULL)    // check if the desired answer (OK) is in the response of the module
      {
        answer = 1;
      }
    }
  }

  while ((answer == 0) && ((millis() - previous)  0) Serial.read();   // Clean the input buffer
}

////////////////////////////////////////////////////////////
void read_UART_buffer(char *buffer,int count, unsigned int timeOut) {
  int i = 0;
  unsigned long timerStart;
  timerStart = millis();

 while(1) {
  while  (Serial.available()!=0){
    Serial.write(Serial.read());
    char c = Serial.read();
    buffer[i++] = c;

  }
  //buffer[i]='\0';
    if((unsigned long) (millis() - timerStart)  > timeOut * 1000UL) {
            break;
        }
 }
}

Are you sure the Content length is 41? Doesn't seem like it, make sure it's the same length as your message body.
This depends from server to server, but I think you should also put a CRLF after your message body.

The problem was in delays, seems its very important, got working code

can you give us your sketch source code


text:
Is there alternative to arduino IDE program ESP8266 and ESP32 with arduino toolchain?
I use ESP8266 and ESP32 with arduino toolchain rather than pure arduino hardware.
Arduino IDE is standard and proven but what are the other IDE and advantage/disadvantage ?

Not an exhaustive list. Most advantages will be subjective.

UECIDE - Wide variety of boards, not only Arduino, better editor and serial monitor, plug-in based modules.
PlatformIO (Available as plugin for Atom editor, MS Visual Studio and Eclipse IDE) - Automatic library updating, one ini file that defines project settings and external libraries, making projects portable to other users without having to download all external libraries.
Arduino IDE for Visual Studio - For those who like VS?
Arduino Makefiles - More like old-school command-line coding, Linux-style development. Not an IDE.
Eclipse - Another quite popular IDE outside Arduino world.
Atmel/Microchip Studio 7 - Provided by the manufacturer of the AVR chips. "Arduino" sketches may not compile without changes to make them more like standard C++.

VisualMicro is a powerfull addon to Visual Studio 201x (no command line needed and intellisense work). That's the best solution for ESP/arduino developpement in my opinion. The free version is really complete to make tests.
VisualGDB is also a good tool to debug (JTAG necessary) but only for ESP tool chain (arduino could be added is future release said in the forum...).

For example, Eclipse IDE with Sloeber plugin is much better than Arduino IDE. You have all the features of Eclipse (coloring, error highlighting, auto-complete, open declaration ('drill down' to libraries), ...*). And every project has own settings (board settings, port, programmer ...). And the Arduino IDE buttons Upload, Verify, Session Monitor are there and the Arduino toolchain too.
*... projects management, version control, TODO lists, outline, ...

I have a very bad experience of ECLIPSE at school last year. Lot of parameters hard to adjust and too much bugs... Visual studio (and code version) are robust days after days.


text:
MD5 Password in Sketch
I'm playing with Over The Air (OTA) updates in my LoLin. I can make connections to my router and OTA updates seem to work well.
I'm uncomfortable storing my WiFi router SSID and password unencrypted in every sketch. Can I store an encrypted password instead for use in WiFi.begin()?
For example, Linux has wpa_pasphrase, which generates a 32-byte number which is an encrypted version of the password which can safely be stored in plaintext configuration files.

you can let the esp8266 store the password. see WiFiManager library

Can I store an MD5 password hash instead

No. MD5 is a "trapdoor" algorithm. It's one-way. You can make a hash from a password but you cannot make a password from a hash.
You could AES encrypt it, but you would need to have the AES key in your sketch to decrypt the password, which just moves the problem elsewhere.
Typically in a real-world situation you wouldn't have either the SSID or the password in the sketch. Instead you'd create a configuration system which would allow you to set (and of course change) both the SSID and password at runtime, and have the data stored somewhere (either EEPROM or in a file in SPIFFS, for example).
You might want to take a look at WiFiManager which automates that process for you.

I shall reword the question to remove "MD5". What I actually hope for is an equivalent to the Linux wpa_passphrase command, which generates a 32 byte encrypted number which I can store in plaintext configuration files instead of storing my password.

@KDM The same thing applies - all you're doing is moving the problem. Even worse in this case, since the result is the actual key that is used to connect, not just the source data that generates it internally.

I use Tzapu's WiFiManager https://github.com/tzapu/WiFiManager.
That starts your ESP as a WiFi access point (AP mode) which presents a web page at http://192.168.4.1 where you enter your WiFi SSID and password. It then stores the password and restarts WiFi as a station (STA mode).
On restart if the password is already stored then it just connects as a station.
If the SSID can't be found it runs the access point again.

I laud your intention and wish there were a good solution on the ESP8266 for what you're trying to do.
MD5 is a one-way hash function, so you won't be able to simply recover the original string to use in WiFi.begin().
MD5 is also considered to be "cryptographically broken and unsuitable for further use" as of 2008. So if you're concerned about more than just a casual eavesdropping attack sniffing out your password, MD5 isn't considered good for any kind of security application these days.
You'd need to use some form of reversible encryption, but you'd still need to store the key somewhere. If you were using an ESP32, it has the capability of encrypting its flash storage, but the ESP8266 can't do that, so you'll always be vulnerable to someone recovering keys or passwords if they get sufficient access to the CPU.

I don't really mind how the password is encrypted, but on my Raspberry Pi, I can load the config file with a hashed password for my WiFi router, so that my password isn't stored in plaintext. As such, there is a way to achieve what I want, even if it's not yet implemented on the Arduino library.

While it IS possible to reverse a password hash, especially MD5 (https://md5decrypt.net/en/), it doesn't buy you anything in the way of security since everyone else can also reverse them.
If you happen to have a second LoLin, you could set it up as an Access Point and have the first device connect to it instead of having it connect to your router. Then you could relay the communication to a PC over USB.
Sure, it's a bit of a pain, but it at least means that you don't have to expose your router's password on a device that someone can pick up and walk off with.

Hmmm... Having had a good thumb through this website, I now understand why MD5 is IRREVERSIBLE and why it can only be put back into plaintext if someone has already stored the original plaintext along with its checksum.

MD5 (and most other hashes) on their own are irreversible.
It's when you constrain the input to passwords that it becomes reversible. Normally with a hash, there are many inputs that can generate the same output. With a password hash, only one of the inputs will normally be 8-20 printable charaters. Knowing that, you just need to reference a table of known password->hashes and boom - hashed password reversed.
Salting the hash makes reversing the value more difficult and using a better hash than MD5 makes it harder yet. However, given enough time, all known password hashes can be reversed.


text:
'GIMSK' was not declared in this scope
I'm programming an ATTiny 85 using the Arduino IDE and an Arduino Nano as "Arduino as ISP" to program the ATTiny. I succeeded a week ago and now I want to program a second chip but get the 'GIMSK' was not declared in this scope error during compile.
The GIMSK is called at the start of the sleep() function. I tried adding #include <avr/interrupt.h> but continue to receive the compile error.
#include <avr/sleep.h>    // Sleep Modes
#include <avr/power.h>
#include <elapsedMillis.h>
const int hallPin = 2;     // the number of the hall effect pin
const int magnetPin =  1;      // the number of the magnet pin
const long debouncing_time = 15; //Debouncing Time in milliseconds
// variables will change:
volatile int hallState = 0;         // variable for storing the hall counter
volatile unsigned long last_micros;
elapsedMillis timer;

void setup()
{
  pinMode(magnetPin, OUTPUT);
  pinMode(hallPin, INPUT);
  digitalWrite(hallPin, HIGH);    // pullup enabled.
  // Attach an interrupt to the ISR vector
  attachInterrupt(0, pin_ISR, RISING); //default interupt pin is always 0 on attiny85 (physical pin 7)
  timer = 0;
}

void sleep()
{
    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
    PCMSK |= _BV(PCINT2);                   // Use PB2 as interrupt pin
    ADCSRA &= ~_BV(ADEN);                   // ADC off
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
    sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
    sei();                                  // Enable interrupts
    sleep_cpu();                            // sleep
    cli();                                  // Disable interrupts
    PCMSK &= ~_BV(PCINT2);                  // Turn off PB2 as interrupt pin
    sleep_disable();                        // Clear SE bit
    ADCSRA |= _BV(ADEN);                    // ADC on
    sei();                                  // Enable interrupts
} // sleep
etc.

Can anyone give me a pointer? I had saved my work so I'm puzzled by the error.
Thank you.

Solution:

Programming configuration for the ATTiny 85 via the Nano as ISP.

For what board are you compiling? Are you sure it was the Attiny85?

@chrisl, yes, ATTiny 85-20PU. I'm using the Nano plugged into a breadboard to program the bare chip. I'm using the procedure here.

In order to program the ATtiny85, you need a suitable board support
package, and you have to configure the Arduino IDE in order to target
that specific chip.
From the description of your issue, it sounds like you did that a week
ago, and then, maybe by accident, you undid the IDE configuration. Now
the IDE is targeting a type of MCU that does not have a register named
GIMSK. Double check that you have the right target configured.
Another possibility would be that the Arduino.h file for the core you
are using does not automatically include avr/io.h. If this is the case,
add
#include <avr/io.h>

at the top of your code.

You were correct with the "target that specific chip" comment. The Arduino IDE doesn't seem to save these with the project or they get switched when I'm working on the Nano and switching to using the Nano as ISP. I've added  a screengrab into my question which is now solved. Thank you.


text:
Can't flash my nodemcu esp8266
I wanted to flash my Nodemcu esp8266 v3.4 with esp8266 deauther code: script-github.
I did everything said. First I plugged in my nodemcu. Windows detected it and drivers for ch340 where already installed. I tried using the Nodemcu firmware programmer for flashing, but when starting flashing in the log there it was just stuck on "begin finding esp8266". Then I tried using the Arduino IDE, again I did everything the github wiki said. But I got this:
Sketch uses 829464 bytes (79%) of program storage space. Maximum is 1044464 bytes.
Global variables use 32132 bytes (39%) of dynamic memory, leaving 49788 bytes for local variables. Maximum is 81920 bytes.
esptool.py v2.8
Serial port COM5
Traceback (most recent call last):
  File "C:\Users\jakob\AppData\Local\Arduino15\packages\deauther\hardware\esp8266\2.7.5/tools/upload.py", line 65, in <module>
    esptool.main(cmdline)
  File "C:/Users/jakob/AppData/Local/Arduino15/packages/deauther/hardware/esp8266/2.7.5/tools/esptool\esptool.py", line 2889, in main
    esp = chip_class(each_port, initial_baud, args.trace)
  File "C:/Users/jakob/AppData/Local/Arduino15/packages/deauther/hardware/esp8266/2.7.5/tools/esptool\esptool.py", line 237, in __init__
    self._port = serial.serial_for_url(port)
  File "C:/Users/jakob/AppData/Local/Arduino15/packages/deauther/hardware/esp8266/2.7.5/tools/pyserial\serial\__init__.py", line 88, in serial_for_url
    instance.open()
  File "C:/Users/jakob/AppData/Local/Arduino15/packages/deauther/hardware/esp8266/2.7.5/tools/pyserial\serial\serialwin32.py", line 78, in open
    self._reconfigure_port()
  File "C:/Users/jakob/AppData/Local/Arduino15/packages/deauther/hardware/esp8266/2.7.5/tools/pyserial\serial\serialwin32.py", line 222, in _reconfigure_port
    'Original message: {!r}'.format(ctypes.WinError()))
serial.serialutil.SerialException: Cannot configure port, something went wrong. Original message: PermissionError(13, 'Ein an das System angeschlossenes Ger�t funktioniert nicht.', None, 31)
Failed uploading: uploading error: exit status 1

always format printouts as code for readability


text:
ESP32 TTGO T-Call connect to SX1276
I have an ESP32 TTGO T-Call and I want to add a LoRa SX1276. I am new to that and I am trying to write a simple program that, when it receives a packet from a LoRa sender, sends via gsm an HTTP request. GSM communication works fine with the TinyGSM library. My problem is the LoRa connection.
Specific chips according to this issue have some reserved pins. If I use the pins of the above example lora works but GSM does not work, because of the reserved pins for the SIM800. I am posting a piece of code with the LoRa setup that is not working. If there is a need for further explanation please ask. I will appreciate any kind of help.
#define SCK 14
#define SS 15
#define MISO 19
#define MOSI 27
#define RST 34
#define DIO0 33

SPI.begin(SCK, MISO, MOSI, SS);
//setup LoRa transceiver module
LoRa.setPins(SS, RST, DIO0);

while (!LoRa.begin(866E6)) {
    SerialMonitor.println(".");
    delay(500);
}
SerialMonitor.println("LoRa Initializing OK!");

Edited
With setting
#define LORA_MISO 19
#define LORA_MOSI 27
#define LORA_SCK 5
#define LORA_SS 18

#define LORA_RST 14
#define LORA_DIO0 26

Lora works (not sim800) but with the settings of @Juraj comment i am getting

E (11571) gpio: GPIO can only be used as input mode
[ 11575][E][esp32-hal-gpio.c:130] __pinMode(): GPIO config failed
E (11571) gpio: gpio_set_level(226): GPIO output gpio_num error
E (11586) gpio: gpio_set_level(226): GPIO output gpio_num error

Edit
Although the error exists it is working with the above settings:
#define LORA_MISO 2
#define LORA_MOSI 13
#define LORA_SCK 14
#define LORA_SS 15

#define LORA_RST 34
#define LORA_DIO0 25

Some packets from the sender are lost but it seems to be working. I don't know why, but it is working... Also it does not seem very stable.
Finally pins 34-39 can be used as input so #define LORA_RST 34 is not working. But it is not receiving yet from the sender.

try MOSI 12, MISO 19, SCK 18 and any pin as SS so your io 15 would be ok

@Juraj thx for your comment. I will try it and I will give you the feedback

@Juraj thx unfortunately i am getting E (11571) gpio: GPIO can only be used as input mode
[ 11575][E][esp32-hal-gpio.c:130] __pinMode(): GPIO config failed
E (11571) gpio: gpio_set_level(226): GPIO output gpio_num error
E (11586) gpio: gpio_set_level(226): GPIO output gpio_num error

try to swap MISO an MOSI in my suggestion. so MOSI 19, MISO 12, SCK 18

Althought Lora.begin, i am getting before begin same error and of course when sender sends nothing is recieved

Pin 14 looks a bit overloaded: #define SCK 14 and #define LORA_RST 14. Can't you move LORA_RST in an attempt to get both devices working simultateously?

My current settings are ```#define LORA_MISO 12
#define LORA_MOSI 19
#define LORA_SCK 18
#define LORA_SS 15
#define LORA_RST 34
#define LORA_DIO0 25 ```  and according to these settings i am getting the error when try to connect to Lora. Inialy i am trying to get lora work with other pins than the default where the conflict exists with sim800.

The issue seems to be arising from the pin definitions and the fact that the SIM800 and the SX1276 LoRa chip on the board might be competing for the same pins, causing interference
First, let's understand the TTGO T-Call pin mapping for SIM800:
SIM800L IP5306 version 20190610:

4: SIM800L RST
23: SIM800L DTR
26: SIM800L PWR
27: SIM800L TX
32: SIM800L RX
33: SIM800L RI

From the pins you've listed for the LoRa SX1276:

SCK: 14
SS: 15
MISO: 19
MOSI: 27
RST: 34
DIO0: 33

It's clear that MOSI on 27 and DIO0 on 33 interfere with SIM800L's pins.
You need to select pins for LoRa that do not interfere with the SIM800L. However, keep in mind that the ESP32 has certain pins that are not suitable for all types of connections.
a proposed remapping would be as follows:
#define SCK 14
#define SS 15
#define MISO 19
#define MOSI 22
#define RST 34
#define DIO0 25

Tell me if this works.

would like to thank you for the try but i am getting the above: E (4757) gpio: GPIO can only be used as input mode
[  4761][E][esp32-hal-gpio.c:130] __pinMode(): GPIO config failed
E (4757) gpio: gpio_set_level(226): GPIO output gpio_num error
E (4771) gpio: gpio_set_level(226): GPIO output gpio_num error. This happens when try connect to Lora

hi there in that case please change the "RST" to something like 13? if the pin 13 is not being used by some other modules and if available switching to that should work. if 13 is in use I think you can also use 12, 16, 17, 21, 22 as well. please make sure that the pin you assign does not interfere with anything else. just change the "RST" pin in my answer and it should start working. write back to me after checking the available pin and please tell me if it works. good luck. the problem with my first answer was probably 34 was input only but 13 should work. if it works please approve.

With my last edit in pins config and set rst to 33 worked like a harm! Mosi in 27 did not worked. I had to set to other like I did set it to 2.

I am very glad to hear that. Some pins are pre-occupied so they don't work. It seems like 34 was only input pin. 33 or 13 in that aspect would work. does mosi 22 works?

I haven't tested yet and I am done for today . I will check it tomorrow and I will give you feedback. Thx for your time


text:
ESP8266 Analog read interferes with wifi?
Short version:
I have a program that connects my ESP8266 to WIFI so I can control a relay connected to it over the internet or a button. I also have a sensor for my door. This software works perfectly, if I add a light dependent resistor to it (which is connected correctly since I do get readings from it) and start reading data I lose my WIFI connection. Has anyone got any idea why this is happening?
Long version:
So I have this program running on my Esp8266

#include <ESP8266WiFi.h>

IPAddress ip(192, 168, 0, 150);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);

const char* ssid = "mySSID";
const char* password = "myPSW";
const char* host = "192.168.0.228";

const int buttonPin = 0;
const int relayPin =  4;
const int doorPin = 5;
const int ldrPin = A0;

//int ldrState;
//int serialCount = 0;
//int ldrMin = 0;
//int ldrMax = 1024;
int buttonState = 0;
int doorState = 0;
byte Main_Light_State_Begin;
bool Main_Light_State;
bool doorNotified = false;
bool button_action_taken = false;
bool Main_Light_DBR = true;
String HTTP_Get_Response;

WiFiServer server(80);

//Functions
String HTTP_Get(char* Adress, String URL, bool Last_Line_Bool) {
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(Adress, httpPort)) {
    Serial.println("connection failed");
    return "Failed";
  }

  Serial.print("Requesting URL: ");
  Serial.println(URL);
  Serial.println("at adress");
  Serial.println(Adress);
  client.print(String("GET ") + URL + " HTTP/1.1\r\n" +
               "Host: " + Adress + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);

  String Response;
  String Last_Line;

  while (client.available()) {
    String line = client.readStringUntil('\r');
    Serial.print(line);
    Response = Response + line;
  }
  return Response;

  Serial.println();
  Serial.println("closing connection");

}

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

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);

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

  server.begin(); -
  Serial.println("Server started");

  Serial.println(WiFi.localIP());
  pinMode(relayPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(doorPin, INPUT);
//  pinMode(ldrPin, INPUT);
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Wifi NOT Connected");
  }
  //Sensors
  buttonState = digitalRead(buttonPin);
  doorState = digitalRead(doorPin);
  //ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
  //Serial.println(analogRead(ldrPin));
//  if (serialCount == 1000) {
//    Serial.println(ldrState);
//    serialCount = 0;
//  } else {
//    serialCount ++;
//  }

  //Doorsensor
  if (doorState == HIGH) {
    if (doorNotified == false) {
      Serial.println("DOOR");
      HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?door_opened=true", false);
      doorNotified = true;
    }
  } else if (doorState == LOW) {
    if (doorNotified == true) {
      doorNotified = false;
      delay(500);
    }
    else {
      doorNotified = false;
    }
  }

  //Button
  if (buttonState == LOW) {
    if (button_action_taken == false) {
      if (Main_Light_State == true) {
        Serial.println("SWITCH");
        Main_Light_State = false;
        digitalWrite(relayPin, HIGH);
        delay(500);
        Main_Light_DBR = false;
      }
      else if (Main_Light_State == false) {
        Serial.println("SWITCH");
        Main_Light_State = true;
        digitalWrite(relayPin, LOW);
        delay(500);
        Main_Light_DBR = false;
      }
      button_action_taken = true;
    }
  } else if (buttonState == HIGH) {
    if (button_action_taken == true) {
      button_action_taken = false;
      delay(500);
    }
    else {
      button_action_taken = false;
    }

  }
  //Main_Light_State
  if (Main_Light_State == true) {
    digitalWrite(relayPin, LOW);
    if (Main_Light_DBR == false) {
      HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?main_light_on_dbr=true", false);
      Main_Light_DBR = true;
    }

  } else if (Main_Light_State == false) {
    digitalWrite(relayPin, HIGH);
    if (Main_Light_DBR == false) {
      HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?main_light_off_dbr=true", false);
      Main_Light_DBR = true;
    }
  }

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

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

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

  if (req.indexOf("/main_light/on") != -1) {
    Main_Light_State = true;
    Main_Light_DBR = false;
  } else if (req.indexOf("/main_light/off") != -1) {
    Main_Light_State = false;
    Main_Light_DBR = false;
  } else if (req.indexOf("/main_light/switch") != -1) {
    Serial.println("SWITCH");
    if (Main_Light_State == true) {
      Main_Light_State = false;
    }
    else if (Main_Light_State == false) {
      Main_Light_State = true;
    }
    Main_Light_DBR = false;
  } else if (req.indexOf("/main_light/state") != -1) {

  } else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  client.flush();

  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
  s += (Main_Light_State) ? "1" : "0";

  client.print(s);
  delay(1);
  Serial.println("Client disonnected");
}

With the lines I commented like above everything works fine. I have a light dependant resistor connected (correctly, I get correct measurements from it) to A0. From the moment on I uncomment the lines involving this LDR and thus start reading data from it I lose my wifi connection. Has anyone got any idea why this is? Thank you!

Which ESP8266? There are many versions each with different abilities and facilities.

@Majenko The one with a serial chip and power regulator on board. (Diymall NodeMCU Devkit 1.0 CP2102 IIC SPI for Apple's MAC OS https://www.amazon.co.uk/dp/B00XJG7GEK/ref=cm_sw_r_other_awd_UnhOwbBSFS1GS)

I came across this while looking for info on analogRead problems. I think the "more elegant solution" may have a couple of problems. Problem 1. If the sensor read and processing takes less than 1 ms, the loop may return and you will get multiple executions of analogRead within the same millisecond - not the desired result. Considering that analogRead(A0) itself only takes about 70 microseconds, if the processing is quick you could easily have 10 or so executions of analogRead(A0) in that millisecond. Problem 2. If there are other things goind on which take multiple millieconds to complete (eg

I have found that this was caused by reading the analog pin to many times in a short period of time. I replaced
  ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
  Serial.println(analogRead(ldrPin));
  if (serialCount == 1000) {
    Serial.println(ldrState);
    serialCount = 0;
  } else {
    serialCount ++;
  }

with this:
if (serialCount == 10000) {
  ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
  Serial.println(ldrState);
  serialCount = 0;
} else {
  serialCount ++;
}

Although I thought of this approach before, my mistake was that I was still reading the sensor every time the code loops, I just wasn't printing it to the serial monitor until each 100th loop.
This still gives me a reading several times per second, which is way more then I need. Anyway, now I know that I can't read my ESP8266 Analog pin to many times per second or the wifi will disconnect (at least when using it with the Arduino IDE)

This works great, just had this exact problem 4 years on. Does anyone know if this is a reported bug? It probably should be.

This is an old question that has been answered, but I would like to offer a slightly more elegant solution (IMO!):
In my method which reads the analog data, I check and only read every 50 milliseconds:
void readAnalogSensor() {
   if( millis() % 50 != 0 )
       return;
   .
   .  // Do your sensor read and processing here
   .
}

This avoids having to keep a loop count and seems more deterministic - the loop count value will not necessarily increase in a consistent fashion depending on what else is going on in the loop.  Having the millis values available is also useful if you need to implement some button debounce code.

Wow this has indeed been a while, man I should pick this project back up! This is indeed a more elegant solution, thank you!

If for some reason the main loop is very slow and the loop goes from ...49 to ...51 it causes a skipped a analogRead. That is why I find the serialCount solution more durable.

Here is what I usually do to give repetition at fixed intervals:
void readAnalogSensor(){
  if (millis()<taskTime) return; // time is not expired yet
  taskTime += 50; // set time for the following execution
  // .... more code for the task that is done every 50 ms
}

This requires an unsigned long variable taskTime. You may also use a constant instead of the 50.
taskTime should be set to some value close to millis() at the end of setup(), otherwise there will be a rapid sequence of executions while taskTime catches up with millis().

Thank you. I wanted to avoid doing the arithmetic at every pass of the loop, but it seems this is not possible without causing the rollover error.