text:
Common ground serial communication trouble SIM800L
I have a trouble when i'm using SIM800L module with common ground with combinaison with : FTDI232+ARDUINO PRO and Li-po battery. I use common ground to allow Arduino see the serial of SIM800L.
I use battery (lipo) to power the SIM800L to allow 2A peak current.
Serial work but sometime the module reset(i think) and i see strange character. The SIM800L no work correctly.
I meet the same trouble when i use the FTDI's VCC, every time I use the common ground i have this problem.
Look the gif you can see the problem :

I'm using this wiring
It's strange because when i connect the SIM800L directly with FTDI232 i have no problem all work fine.
I use this code to debug the Serial communication :
#include <SoftwareSerial.h>
SoftwareSerial serialSIM800(RX,TX)
[..]
//On Setup
 Serial.begin(115200);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(115200);
  delay(1000);
  serialSIM800.print("AT\r");
  //[..]
void loop(){

 if (serialSIM800.available())
     Serial.write(serialSIM800.read());

 if (Serial.available()) {
    while(Serial.available()){
      Serial.print(">");
      char test=Serial.read();
      Serial.print(test);
      Serial.println();
      serialSIM800.write(test);
 }

There are a few things that escape me that's why I need your lights, thanks by advance.
Regards

Two suspicions can be investigated.
First thing is Software Serial which is always a candidate for  suspicion. I understand that you debug from the pc via FTDI.
You maybe better debug using Arduino Mega since it has multiple hardware serials until you satisfied with your project and port the code to the Arduino Pro afterward.
And second thing is If Arduino Pro version is 3v (you didn't mention) and causing logic levels issues.

If I were you, I would start testing from lower rates like 9600 and make higher until the data  is started to garble as you see.

Btw, your wiring shows SIM900L not SIM800 which have slightly different wiring recommendations. Which one is yours?

@Sener i do a mistake is really sim800l

I use 1200 baud rate and i use https://github.com/nickstedman/SoftwareSerialWithHalfDuplex for Software Serial this no work i have the same problem

I finally fixed my issue.
I disable the auto baud rate of SIM800L trough FTDI232, with these at commands:
AT + IPR = 9600
AT & W

AT + IPR: Fix the baud rate at 9600
AT & W: Save in SIM800L
Then when i use with SoftwareSerial i have no issue anymore. When i reset the module with short connect RST with GND i have a good reply from SIM800L :
RDY

+CFUN: 1

+CPIN: READY

Call Ready

SMS Ready

Thanks for your help.
Note : And be sure you are a good power supply and good wire.


text:
Switch Statement Alternative
I am working on a project where I've mapped an IR remote control to certain functions. I am currently using a massive switch statement to control the program based on the IR remote button pressed.
Is there a an alternative to using a switch statement, or is a switch the best way to go?
decode_results results; // Initialize the results

IRrecv irrecv(irPin); // Initialize the IR sensor

int buttonPressed;

void setup()
{
  Serial.begin(115200);
  Serial.println("Tile Controller");
  analogReference(DEFAULT);
  irrecv.enableIRIn(); // Start the receiver

  Wire.begin(); // Join the I2C network
}

void loop()
{
  if (irrecv.decode(&results))
  {
    if(results.value != buttonHeld)
    {
      buttonPressed = results.value;
      Serial.println(buttonPressed,HEX);
    }

    switch(buttonPressed)
    {
      case 0x3AC5: // 11 - Brightness Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Brightness Up Held");
          brightnessUpHeld();
        }
        else
        {
          Serial.println("Brightness Up Pressed");
          brightnessUpPressed();
        }
        break;
      }

      case 0xFFFFBA45: // 12 - Brightness Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Brightness Down Held");
          brightnessDownHeld();
        }
        else
        {
          Serial.println("Brightness Down Pressed");
          brightnessDownPressed();
        }
        break;
      }

      case 0xFFFF827D: // 13 - Pause
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Pause Held");
          pauseHeld();
        }
        else
        {
          Serial.println("Pause Pressed");
          pausePressed();
        }
        break;
      }

      case 0x2FD: // 14 - Power
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Power Held");
          powerHeld();
        }
        else
        {
          Serial.println("Pause Pressed");
          powerPressed();
        }
        break;
      }

      case 0x1AE5: // 21 - Red
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red Held");
          redHeld();
        }
        else
        {
          Serial.println("Red Pressed");
          redPressed();
        }
        break;
      }

      case 0xFFFF9A65: // 22 - Green
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green Held");
          greenHeld();
        }
        else
        {
          Serial.println("Green Pressed");
          greenPressed();
        }
        break;
      }

      case 0xFFFFA25D: // 23 - Blue
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue Held");
          blueHeld();
        }
        else
        {
          Serial.println("Blue Pressed");
          bluePressed();
        }
        break;
      }

      case 0x22DD: // 24 - White
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White Held");
          whiteHeld();
        }
        else
        {
          Serial.println("White Pressed");
          whitePressed();
        }
        break;
      }

      case 0x2AD5: // 31 - Red 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red One Held");
          redOneHeld();
        }
        else
        {
          Serial.println("Red One Pressed");
          redOnePressed();
        }
        break;
      }

      case 0xFFFFAA55: // 32 - Green 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green One Held");
          greenOneHeld();
        }
        else
        {
          Serial.println("Green One Pressed");
          greenOnePressed();
        }
        break;
      }

      case 0xFFFF926D: // 33 - Blue 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue One Held");
          blueOneHeld();
        }
        else
        {
          Serial.println("Blue One Pressed");
          blueOnePressed();
        }
        break;
      }

      case 0x12ED: // 34 - White 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White One Held");
          whiteOneHeld();
        }
        else
        {
          Serial.println("White One Pressed");
          whiteOnePressed();
        }
      }

      case 0xAF5: // 41 - Red 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red 2 Held");
          redTwoHeld();
        }
        else
        {
          Serial.println("Red 2 Pressed");
          redTwoPressed();
        }
        break;
      }

      case 0xFFFF8A75: // 42 - Green 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green 2 Held");
          greenTwoHeld();
        }
        else
        {
          Serial.println("Green 2 Pressed");
          greenTwoPressed();
        }
        break;
      }

      case 0xFFFFB24D: // 43 - Blue 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue 2 Held");
          blueTwoHeld();
        }
        else
        {
          Serial.println("Blue 2 Pressed");
          blueTwoPressed();
        }
        break;
      }

      case 0x32CD: // 44 - White 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White 2 Held");
          whiteTwoHeld();
        }
        else
        {
          Serial.println("White 2 Pressed");
          whiteTwoPressed();
        }
        break;
      }

      case 0x38C7: // 51 - Red 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red 3 Held");
          redThreeHeld();
        }
        else
        {
          Serial.println("Red 3 Pressed");
          redThreePressed();
        }
        break;
      }

      case 0xFFFFB847: // 52 -  Green 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green 3 Held");
          greenThreeHeld();
        }
        else
        {
          Serial.println("Green 3 Pressed");
          greenThreePressed();
        }
        break;
      }

      case 0x7887: // 53 - Blue 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue 3 Held");
          blueThreeHeld();
        }
        else
        {
          Serial.println("Blue 3 Pressed");
          blueThreePressed();
        }
        break;
      }

      case 0xFFFFF807: // 54 - White 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White 3 Held");
          whiteThreeHeld();
        }
        else
        {
          Serial.println("White 3 Pressed");
          whiteThreePressed();
        }
        break;
      }

      case 0x18E7: // 61 - Red 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red 4 Held");
          redFourHeld();
        }
        else
        {
          Serial.println("Red 4 Pressed");
          redFourPressed();
        }
        break;
      }

      case 0xFFFF9867: // 62 - Green 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green 4 Held");
          greenFourHeld();
        }
        else
        {
          Serial.println("Green 4 Pressed");
          greenFourPressed();
        }
        break;
      }

      case 0x58A7: // 63 - Blue 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue 4 Held");
          blueFourHeld();
        }
        else
        {
          Serial.println("Blue 4 Pressed");
          blueFourPressed();
        }
        break;
      }

      case 0xFFFFD827: // 64 - White 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White 4 Held");
          whiteFourHeld();
        }
        else
        {
          Serial.println("White 4 Pressed");
          whiteFourPressed();
        }
        break;
      }

      case 0x28D7: // 71 - Red DIY Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red DIY Up Held");
          redDIYUpHeld();
        }
        else
        {
          Serial.println("Red DIY Up Pressed");
          redDIYUpPressed();
        }
        break;
      }

      case 0xFFFFA857: // 72 - Green DIY Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green DIY Up Held");
          greenDIYUpHeld();
        }
        else
        {
          Serial.println("Green DIY Up Pressed");
          greenDIYUpPressed();
        }
        break;
      }

      case 0x6897: // 73 - Blue DIY Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue DIY Up Held");
          blueDIYUpHeld();
        }
        else
        {
          Serial.println("Blue DIY Up Pressed");
          blueDIYUpPressed();
        }
        break;
      }

      case 0xFFFFE817: // 74 - Quick
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Quick Held");
          quickHeld();
        }
        else
        {
          Serial.println("Quick Pressed");
          quickPressed();
        }
        break;
      }

      case 0x8F7: // 81 - Red DIY Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red DIY Down Held");
          redDIYDownHeld();
        }
        else
        {
          Serial.println("Red DIY Down Pressed");
          redDIYDownPressed();
        }
        break;
      }

      case 0xFFFF8877: // 72 - Green DIY Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green DIY Down Held");
          greenDIYDownHeld();
        }
        else
        {
          Serial.println("Green DIY Down Pressed");
          greenDIYDownPressed();
        }
        break;
      }

      case 0x48B7: // 73 - Blue DIY Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue DIY Down Held");
          blueDIYDownHeld();
        }
        else
        {
          Serial.println("Blue DIY Down Pressed");
          blueDIYDownPressed();
        }
        break;
      }

      case 0xFFFFC837: // 84 - Slow
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Slow Held");
          slowHeld();
        }
        else
        {
          Serial.println("Slow Pressed");
          slowPressed();
        }
        break;
      }

      case 0x30CF: // 84 - DIY 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 1 Held");
          diyOneHeld();
        }
        else
        {
          Serial.println("DIY 1 Pressed");
          diyOnePressed();
        }
        break;
      }

      case 0xFFFFB04F: // 84 - DIY 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 2 Held");
          diyTwoHeld();
        }
        else
        {
          Serial.println("DIY 2 Pressed");
          diyTwoPressed();
        }
        break;
      }

      case 0x708F: // 84 - DIY 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 3 Held");
          diyThreeHeld();
        }
        else
        {
          Serial.println("DIY 3 Pressed");
          diyThreePressed();
        }
        break;
      }

      case 0x708F: // 84 - DIY 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 3 Held");
          diyThreeHeld();
        }
        else
        {
          Serial.println("DIY 3 Pressed");
          diyThreePressed();
        }
        break;
      }

      case 0xFFFFF00F: // 84 - DIY 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Auto Held");
          autoHeld();
        }
        else
        {
          Serial.println("Auto Pressed");
          autoPressed();
        }
        break;
      }

    }
    irrecv.resume(); // Receive the next IR value
  }
}

Can we have a glimpse at the portion of your code in question? This helps us to better understand how the decisions in your program are made and will lead to better answers.

You could have an array of structs, with each struct containing the key code, a name, a "pressed" function pointer and a "held" function pointer.

The array of structs sounds like a good idea. I've never used a function pointer before so I guess I've got some learning to do :)

Your switch statement isn't that big - I've seen bigger.
However, as @MarkSmith says, using an array of structs with key codes and function pointers would be a way to go.  For instance, you may have the struct:
struct button {
    uint32_t keycode;
    void (*press)();
    void (*hold)();
};

Populated with data it would look like:
const struct button buttons[] = {
    { 0x3AC5, brightnessUpPressed, brightnessUpHeld },
    { 0xFFFFBA45, brightnessDownPressed, brightnessDownHeld },
    ... etc ...
    { 0xFFFFF00F, autoPressed, autoHeld },
    { 0, 0, 0 }
};

Note the last entry of { 0, 0, 0 } - this is being used as an "end of list" marker. An alternative is to keep track of how many entries are in the list, but this makes adding / removing entries easier.
Then you can iterate through the list until you find a keycode that matches or the special keycode 0:
for (int i = 0; buttons[i].keycode != 0; i++) {
    if (buttons[i].keycode == buttonPressed) {
        if (results.value == buttonHeld) {
            buttons[i].held();
        } else {
            buttons[i].press();
        }
        break; // We found the button, no need to continue
    }
}

This method decreases the amount of code you have, but has the adverse effect of increasing the amount of RAM you use. It's a tradeoff between making the code simpler and using more RAM. If you can afford the RAM usage it can make things so much easier to read, since you have a simple table for the commands and a simple loop for finding the right entry in the table.

Wow, thanks for that reply & code examples. I'm definitely going to give it a try.

source: Stack Exchange

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

sort: votes


text:
Arduino with OV7670 - a buffer
I have an Arduino UNO and OV7670 camera sensor without FIFO. I wanted to build a device, that would take frame once in a while, and would send it through bluetooth (HC-05) or wi-fi (esp-01). I didn't know though, that the microcontroller inside Uno has so little RAM memory, that the frame doesn't fit inside. Moreover, even Arduino Mega has too little memory...
My question is- is there anything I could do to take a VGA-resolution photo (circa 1MB) and send it through any serial medium?
I suppose it'd be some kind of a buffer or memory- I'm asking for references to concrete chips or solutions (like- would it be possible to encode or compress an image on-the-fly)?

The first thing you could do is but the camera with the buffer :)
The ESP-01 has much more RAM than the Arduino, I don't think its got enough still though.
You can buy the FIFO chip that the other version of the camera uses, you could try and retro fit your camera.

Oh. Looks like ESP-01 could have enough memory for grayscale or lower resolution frame. It's surprising to find that I could do without Arduino...
By 'retrofitting' you mean adding the FIFO manually to the camera circuit? It sounds like a pretty difficult process...

I have a camera with FIFO, one without and a couple of FIFO memory chips.  I wasn't sure if I could either attach the FIFO to the camera (I agree sounds horrid) or use the FIFO from the ESP.  But then I got distracted and its at the bottom of a heap of electronics somewhere.  So I can't tell you which way to go, just offer suggestions.  To be honest though, buying a camera with FIFO might be a lot less hassle.

Compress on the already belabored Uno/Mega? Nope. If you're okay with grayscale, you don't need 1 MB buffer space. With the YCbCr422 colour space, you can extract only the Y component and need only 640*480 = 307kB buffer for a VGA grayscale image.

if it's not a silly question, does the entire image need to be sent in a single transaction? i believe with i2c you could issue the command to capture, and then read back chunks at a time (that fit within your RAM) send those chunks, then repeat until no image data left to retrieve?

@JamesKent thing is, theres no command to capture. Once the camera is powered and an clock signal is applied, it begins spitting out frames on its signal lines, with the frame rate and time between bytes determined by the applied clock. Frames arent packetized and cant be requested for at leisure. You're either there to capture them or you arent.

Sorry, i misunderstood, what about stopping the clock to the camera periodically?

@JamesKent I'm not sure but if you stop the clock in the middle of a frame, you'll probably lose the rest of that frame's data. The camera needs the clock to function; won't even respond to commands over I2C.

If you're okay with grayscale, you don't need 1 MB buffer space. With the YUV422 colour space, you can extract only the Y component and need only 640*480 = 307kB buffer for a VGA grayscale image.
However, according to this, you can set the hardware serial baud rate to 1M-baud and transmit the image bytes as you receive them without buffering. main() shows how to set up the serial port and you can also see how they received each VGA pixel byte in Bayer-RGB and transmitted immediately; notice that all interrupts are disabled first, given the high-speed nature of the transfer. But instead of Bayer, I'd recommend you use YUV422 instead, meaning the camera sends 2 bytes per pixel. Because you're only interested in the Y byte, you can place that in the UART buffer and use the time spent in receiving (and discarding) the second U/V byte to give the UART peripheral some additional breathing room to send the Y byte, before you send the next one.
Regarding the high baud rate, the crystal frequency of the Arduino doesn't matter so much because you'll only be transmitting to your PC, which should be able to handle the speed even given the rate error. Note that in main(), double speed async is enabled, and UBRR is set to 500 kBaud to obtain 1-Mbaud. Also notice that an 8MHz PWM signal was used to clock the camera (XCLK signal) with no PLLs activated in the camera register settings. This is another tutorial related to the same code; may clear up a few things.
If you really want to use a chip solution, you can look up parallel SRAM like the HM628128; it's only 128kB though, you'll need to find a bigger one to hold an entire frame of 307kB. Parallel SRAM are great because you can attain really high write speeds because of the simple interface. You'll need some sort of counter connected to the SRAM address lines clocked by the PCLK line (divided by 2, since you only want every other byte) so that every pulse increments the address. This same clock will feed the nW signal to actually clock the data into the SRAM (after satisfying address setup times somehow). The camera data lines will be connected directly to the SRAM and you activate the SRAM's chip select signal based on your monitoring of the camera's VSYNC signal (to know when a new frame's about to start). When the frame's done, you read from the RAM and forward the bytes to your destination.
All this assumes you aren't trying for video, merely taking frames "once in a while". Though the first solution will work for video, albeit poor video.

You need to add a FIFO buffer to the camera, or work out a scheme for streaming data from the camera over the network, because you don't have anywhere enough memory to store the image.

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


text:
HC-06 RX pin usefulness
I have a HC-06 bluetooth module. The module has an RX and TX pin (the RX pin receives data and TX transmits data) which connect to the TX and RX pin of an Arduino respectively (in my case an Arduino pro mini).
My question is in what scenario would someone use the RX pin of the module(basically for what purpose would the bluetooth module receive a signal from the Arduino)?
For example let's say i have a simple LED that i turn off and on. I just sent the signal from my phone to the module and the module sends the signal to the Arduino. So basically i've connected the TX pin of the module (which transmits the data) with the RX pin of the Arduino (which receives the data).
In order to connect the RX pin of the module with the TX pin of the Arduino i have to use a voltage divider as the module only accepts 3.3 volts of signal while the Arduino transmits 5 volts of signal. I want to avoid that because in my project i need the PCB to be quite small.
So if someone only wants to transmit data from the module to the Arduino, is there a reason on why would he connect the other two pins?

If you never want to change the configuration of the module either, then no, you don't need to connect the module's RX pin.
However many people want bi-directional communication. Not only the ability to send a signal to turn the LED on or off, but also the ability to get the current state of the LED - is it on or off?
Or maybe to send an analog reading. Or the data from some sensor.
The HC-06 is a bi-directional module. If you choose to use only one direction then you only need to wire in one direction. However, tie the RX pin to 3.3V with a 10KΩ resistor to stop it floating and consuming extra power or causing random noise to be transmitted to your phone.
In fact, it's just like a phone. You can call someone up and just speak to them without listening to what they are saying. That's fine if all you want to do is call Mom and say "Pick me up in 5 minutes" and hang up. But if you want to ask your Mom "Can you pick me up in 5 minutes?" you have to actually listen for her answer "No, walk home you lazy oik!".


text:
Having problems with I2C - Slave is receiving "b ~ ,,,"
so I'm facing a pretty large problem. I'm experimenting with I2C and using one Arduino that acts as a countdown timer to send the current reading on the timer to another Arduino. I'm pretty new to electronics in general so bear with me.
The way the countdown timer works is it stores the time as a String, and uses substring and toInt() to adjust the timer.
I know that with I2C you can only send some data, Strings not included, so I tried converting the String to an array of characters using toCharArray(). My conversion seems to be working well, as I have tested it with the Serial.println() and it displays the time correctly.
Therefore, I am convinced the problem lies with the Slave code. I'm not sure how to set up the Slave Arduino to receive the actual time. Below, I've pasted links to the code of both the Master and the Slave respectively.
Master: https://pastebin.com/AFjTDZB7
Slave: https://pastebin.com/viNGWn9c
How should I change my slave code so everything works?
Also, when I changed the datatype of "time" in the Slave code from char* to int, all I got in the Serial Monitor was 48. Weird.
Would really appreciate any help and guidance cause I'm pretty stuck. All the tutorials I find online are pretty complicated.
Thanks!
Master Code:
#include < Wire.h >
String time = "10:11";
boolean doubleDigits = false;

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

void loop() {
  Serial.println(time);
  sendTime(time);
  int First2 = time.substring(0, 2).toInt();
  if (First2 > 9) {
    doubleDigits = true;
  }

  int Last2 = time.substring(3).toInt();
  if ((time.substring(3) == "00") && (time != "00:00")) {
    First2 = First2 - 1;
    Last2 = 59;
    if (doubleDigits == false) {
      time = "0" + String(First2) + ":" + String(Last2);
    } else {
      time = String(First2) + ":" + String(Last2);
    }
  } else if (time != "00:00") {
    Last2 = Last2 - 1;
    if (Last2 < 10) {
      if (doubleDigits == false) {
        time = "0" + String(First2) + ":0" + String(Last2);
      } else {
        time = String(First2) + ":0" + String(Last2);
      }
    } else {
      if (doubleDigits == false) {
        time = "0" + String(First2) + ":" + String(Last2);
      } else {
        time = String(First2) + ":" + String(Last2);
      }
    }
  }
  if (time.substring(1, 2) == ":") {
    time = "0" + time;
  }
  delay(1000);
}

void sendTime(String time) {
  Wire.beginTransmission(9); //transmit to device 9
  char buffer[32];
  time.toCharArray(buffer, 32);
  Wire.write(buffer);
  Serial.println(buffer);
  Wire.endTransmission(); //stops transmitting
}

//master

Slave Code:
#include <Wire.h>
char* time;

void setup() {
  Wire.begin(9); //start as slave on address 9
  Wire.onReceive(receiveEvent); //attach a function to trigger when something is received
  Serial.begin(9600);
}

void receiveEvent(int bytes) {
  time = Wire.read(); //read one character from the I2C

}

void loop() {
  Serial.println(time);
  delay(1000);
}

//slave

Edit: added code

Can't see the code, can't answer the question.  I would expect 48 if you changed a char* of the time to an int without understanding what you were doing.  48 is ASCII 0.

@CodeGorilla, alright, added the code to the main post. Can you take a look please? Would really appreciate it.

You still need to fix sendTime in the master code, but...

In the slave code.  receiveEvent takes a number of bytes as a parameter, presumably you are supposed to read this many bytes, can you call read with that number?  Even if you did you are reading to a char pointer, which will cause issues unless read is allocating the memory, which you should then be releasing.  Basically you have a couple of issues here and you need to look at them.
In the Master code. sendTime doesn't look right.  I would expect you to have to send a certain number of bytes using the Write function.  You are just sending 32 chars, the fact you are sending signed char's rather than unsigned char's shouldn't be an issue (but its technically incorrect).
I don't really understand what you are trying to achieve in the rest of loop, annotation would help :)

OK, If you take this as a new version for the slave you should be able to see it working.  It might not be 100%, but you should get something.  (I haven't even compiled this code, so you might have to sort out a few bugs)
#include <Wire.h>

#define MaxTimeBufferSize (33)
#define MaxReadSize  (MaxTimeBufferSize - 1)
char timeBuffer[MaxTimeBufferSize];

void setup()
{
  Serial.begin(9600);  // Init first so you can see any issues during setup.
  Wire.begin(9); //start as slave on address 9
  Wire.onReceive(receiveEvent); //attach a function to trigger when something is received
}

// Assumes the bytes are actually printable ASCII characters.
void receiveEvent(int bytes)
{
  const int bytesToRead = (bytes < MaxReadSize) ? bytes : MaxReadSize;
  for (int index = 0; index < bytesToRead; ++index)
  {
     timeBuffer[index] = Wire.read(); //read one character from the I2C
  }
  timeBuffer[bytesToRead] = 0; // Null terminate the bytes (so they will print as a string)
}

void loop()
{
  if (timeBuffer[0])  // Only print the buffer if there is new data
  {
    Serial.println(timeBuffer); // The buffer is NULL terminated.
    timeBuffer[0] = 0;  // Stop the buffer  printing again.
  }
  delay(1000);
}

Hey, thanks for your reply, @CodeGorilla. I realize that Slave contains a problem, I just don't know how to fix it. That's why I'm asking for help.
Also, for the Master code, all it does is act as a countdown clock, by maintaining a String called "time" and uses some toInt(), concatenation and toString() functions to change the value of time every second and send that value to the Slave.

works like a charm! Thank you, really appreciate it!

@A.Lordos, the code by @CodeGorilla shows how to read more than one byte as a Slave. It stores the received data in a buffer, and that buffer is printed to the serial monitor to show it.
May I make a suggestion: start all over and do it right.
Forget the String objects and use a integer (int, or unsigned or unsigned long) as a countdown counter for the seconds. Count the seconds, nothing else.
When you need to display the counter, then you can make it in the format of "10:11". But only to display it, the base of the sketch is still that single variable for the seconds.
When you need to transmit the counter to the Slave, send the integer variable as binary data (the integer itself), not a text string.
In the Arduino examples, a text is transferred over the I2C bus. That is however almost never done. In most cases binary data of variables is transferred over I2C.
This is a good tutorial: Nick Gammon's Tutorial about I2C


text:
How to use analogWrite() on multiple pins at the same time?
I would like to do,
analogWrite(100,3);
 analogWrite(200,6);
at the same time. But the problem is that only the led on pin 3 lights up. I want both to light up at the same time. I've heard about direct port manipulation, but I can only find an alternate for digitalWrite() but I couldn't find one for analogWrite(). Can someone please help me with just a simple example on just how to do the above operation?
I'm using arduino uno.

You have your parameters the wrong way round:
analogWrite(2, 100);
analogWrite(6, 200);

However: pin 2 on the Uno cannot do PWM, so you will have to pick a different pin. Look for the pins marked with ~ - they are the PWM pins. On the Uno that is pins 3, 5, 6, 9, 10 and 11.

yeah I'm sorry it's pin 3. Now how to i turn both on at the same time?

Just like that. When you run analogWrite() it starts PWM on that pin and it keeps going until you tell it otherwise. If you aren't getting anything out then you have probably broken that pin through misuse or doing something else in your code that's stopping PWM.

No. if i use pin 6 first, then pin 3. The pin 6 lights up and not pin 3

And if you do it the other way around? And NOT PIN 2.

analogWrite(6, 100);
analogWrite(3, 200); This turns on pin 6

NOT PIN 2

I think you have blown the LED on pin 3.  You haven't said that you have a resistor between the LEDs and the Uno.  If this is the case you might have fried the LED on pin 3.  If its good then try doing (3, 100) not 200 and see if that works.

I guess someone has to introduce multiplexing here...


text:
TWI Wire.setClock() on non arduino AVR MCU issue
Using an Atmega168P - programmed by means of avrdude with the .hex file generated by Arduino IDE.
The following code sets the 8 MHz Atmega's TWI interface to just 15.625 kHz:
  Wire.begin(); // Initiate the Wire library
  Wire.setClock(100* 1000);
  delay(10);

While this one doubles it to 31.25 kHz:
  Wire.begin(); // Initiate the Wire library
  TWBR = (F_CPU/(100*1000) - 16)/2;
  TWSR &= 0b11111100;
  delay(10);

Looking to get 100 kHz clock. What am I missing ?

Calculations are int (16-bits) by default. Try 100*1000L. Or better define F_TWI as 100000L and use TWBR = ((F_CPU/F_TWI)-16)/2;

@MikaelPatel That was it! You may want to turn that into an answer as well, thanks.

You get 100kHz with just Wire.begin(), because that is the default. The Wire.setClock has limits (I don't know the limits) but 50kHz to 200kHz should work: Wire.setClock(50000L) to Wire.setClock(200000L). I hope you are not trying to compile 16MHz code for a 8MHz ATmega chip. If there is no 8MHz ATmega168P in the menu, you should create an entry in boards.txt.

Looking to get 100 kHz clock. What am I missing?

Calculations are int (16-bits) by default in AVR GCC. Try 100*1000L. Or even better:
#define F_TWI 100000L

and use:
TWBR = ((F_CPU/F_TWI)-16)/2;

or:
Wire.setClock(F_TWI);

Cheers!


text:
Attiny85: Watchdog does not initialize properly when using switch(case)
I have a project in which I am putting my ATtiny85 to sleep. Here is the watchdog configuration (in the setup) that works just fine:
void setup()
{
  /*  Setup the LCD */
  lcd.init();                           // initialize the lcd
  lcd.backlight();                      // Print a message to the LCD.
  lcd.clear();
  lcd.setCursor(0,0);

  /* Inform the user about initialization process */
  lcd.print("Initializing...");
  delay(1000);

  /* Config pins */
  pinMode( LED_PIN, INPUT );
  pinMode( STATUS_PIN, OUTPUT );

  /* Initialize pins */
  digitalWrite( STATUS_PIN, HIGH );

  /*** Setup the WDT ***/

  /* Clear the reset flag of watchdog interrupts, so that they are available again. */
  MCUSR &= ~(1<<WDRF);

  /* Enable configuration changes */
  WDTCR |= (1<<WDCE) | (1<<WDE);

/*
WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                         Oscillator Cycles     VCC = 5.0V
  0         0      0        0             2K (2048) cycles       16 ms
  0         0      0        1             4K (4096) cycles       32 ms
  0         0      1        0             8K (8192) cycles       64 ms
  0         0      1        1            16K (16384) cycles    0.125 s
  0         1      0        0            32K (32768) cycles    0.25 s
  0         1      0        1            64K (65536) cycles    0.5 s
  0         1      1        0            128K (131072) cycles 1.0 s
  0         1      1        1            256K (262144) cycles 2.0 s
  1         0      0        0            512K (524288) cycles 4.0 s
  1         0      0        1            1024K (1048576) cycles 8.0 s
*/
  /* set new watchdog timeout prescaler value */
  WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;

  lcd.clear();
  lcd.print("Initialisation");
  lcd.setCursor(0,1);
  lcd.print("complete.");
  delay(500);
}

Here is the function that actually puts my microcontroller to sleep:
void enterSleep(void)
{
//  /* disable all interrupts */
//  cli();
  lcd.clear();
  lcd.print("Asleep...");

  /* Enable the WD interrupt (note no reset). */
  WDTCR |= (1<<WDIE);

  set_sleep_mode( SLEEP_MODE_PWR_DOWN );   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */
  sleep_enable();
  // Status pin goes low
  digitalWrite( STATUS_PIN, LOW );
  /* Now enter sleep mode. */
  sleep_mode();

  /* The program will continue from here after the WDT timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  // Status pin goes low
  digitalWrite( STATUS_PIN, HIGH );

  /* Re-enable the peripherals. */
  power_all_enable();

  /* Disable the WD interrupt */
  WDTCR &= ~_BV(WDIE);
}

Then I decided to do a switch case construction, so that I won't have to change manually WDTCR register each  time I want to change the sleep time. So here is my new setup code:
int sleepTime = 0;

void setup()
{
  /*  Setup the LCD */
  lcd.init();                           // initialize the lcd
  lcd.backlight();                      // Print a message to the LCD.
  lcd.clear();
  lcd.setCursor(0,0);

  /* Inform the user about initialization process */
  lcd.print("Initializing...");
  delay(1000);

  /* Config pins */
  pinMode( IN_PIN, INPUT );
  pinMode( STATUS_PIN, OUTPUT );
  pinMode( DEBUG_PIN, OUTPUT );

  /* Initialize pins */
  digitalWrite( STATUS_PIN, HIGH );
  digitalWrite( DEBUG_PIN, LOW );

  /*** Setup the WDT ***/
//  sleepDevice.watchdogInit();
    /*** Setup the WDT ***/
    /* Clear the reset flag of watchdog interrupts, so that they are available again. */
    MCUSR &= ~(1<<WDRF);

    /* Enable configuration changes*/
    WDTCR |= (1<<WDCE) | (1<<WDE);

  /*
  WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                           Oscillator Cycles     VCC = 5.0V
    0         0      0        0             2K (2048) cycles       16 ms
    0         0      0        1             4K (4096) cycles       32 ms
    0         0      1        0             8K (8192) cycles       64 ms
    0         0      1        1            16K (16384) cycles    0.125 s
    0         1      0        0            32K (32768) cycles    0.25 s
    0         1      0        1            64K (65536) cycles    0.5 s
    0         1      1        0            128K (131072) cycles 1.0 s
    0         1      1        1            256K (262144) cycles 2.0 s
    1         0      0        0            512K (524288) cycles 4.0 s
    1         0      0        1            1024K (1048576) cycles 8.0 s
  */

  switch( sleepTime ){
    case 0:
      WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
      break;
    case 1:
      WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 1<<WDP0 ;
      break;
    default:
      WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
      break;
  }

  lcd.clear();
  lcd.print("Initialisation");
  lcd.setCursor(0,1);
  lcd.print("complete.");
  delay(500);
}

The enterSleep function is not changed.
But this time sleeping does not work at all! In fact, ATtiny sort of freezes. Does any one has any idea why it is so? To me it looks like the Arduino IDE is confused with switch case instruction, but maybe there is something wrong with my code...

Several things going on here. First, you do not need to fiddle with the change enable bit to change the prescaller. Second, you do not know the value of the watchdog timer at any point in your code, so random stuff can happen.  I would (1) disable to watchdog timer completely, (2) update the prescaller bits (3) only just before sleeping (a) clear the watchdog counter with a  wdt_reset(), (b) then enable to WDT and the interrupt. (c) sleep. On waking, disable the WDT immediately.

@bigjosh But why is it so, that everything works fine when I don't use switch? As soon as I use it, nothing works...

The switch statement is at least one additional compare and branch compared to the original code. This means more cycles, which may be enough for the WDT to expire. Do you get the result when you run the switch with the same prescaller? Do you get the same result when you add a few nops before the the line that sets the prescaller in the orginal version?

Also keep in mind that you are enabling config changes and then entering the switch statement, but you have no way to ensure that all cases of the switch will execute within the 4 cycle window that opens after the enable bit is written. I'd start with the simplest case and work your way back - too much unpredictable stuff going on here to be able to pin down which of the problems you are actually seeing.

Note that if the Watchdog is enabled, it keeps being enabled, even after a reset. This can be especially problematic, if you set it to a very short time. So the very first thing you should do in your setup is to disable the WDT.

@bigjosh So after I set the Enable bit, I have to ocnfig the watchdog prescaler, right? That shines some different light on issue...

Alright, thanks to you guys I fixed the issue.
The main thing is that any changes in the configuration have to be made within 4 cycles after the CONFIG ENABLE bit is set. It is done with this instruciton:
/* Enable configuration
WDTCR |= (1<<WDCE) | (1<<WDE);

Now switch works like a charm. So the final code for watchdog setup looks like this:
void Sleeper::watchdogInit( void ){
    /*** Setup the WDT ***/
      /* Clear the reset flag of watchdog interrupts, so that they are available again. */
      MCUSR &= ~(1<<WDRF);

    /*
    WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                             Oscillator Cycles     VCC = 5.0V
      0         0      0        0             2K (2048) cycles       16 ms
      0         0      0        1             4K (4096) cycles       32 ms
      0         0      1        0             8K (8192) cycles       64 ms
      0         0      1        1            16K (16384) cycles    0.125 s
      0         1      0        0            32K (32768) cycles    0.25 s
      0         1      0        1            64K (65536) cycles    0.5 s
      0         1      1        0            128K (131072) cycles 1.0 s
      0         1      1        1            256K (262144) cycles 2.0 s
      1         0      0        0            512K (524288) cycles 4.0 s
      1         0      0        1            1024K (1048576) cycles 8.0 s
    */

    switch( sleepTime ){
        case 0:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
            break;
        case MSEC_500:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 1<<WDP0 ;
            break;
        case MSEC_250:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 0<<WDP0 ;
            break;
        case MSEC_125:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 1<<WDP0 ;
            break;
        case MSEC_64:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
            break;
        case MSEC_32:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
            break;
    default:
      /* Enable configuration changes*/
      WDTCR |= (1<<WDCE) | (1<<WDE);
      WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
      break;
    }

Accept your own answer to close this question.

Try this for your sleep function...
void enterSleep(void)
{
  lcd.clear();
  lcd.print("Asleep...");

  // Status pin goes low
  digitalWrite( STATUS_PIN, LOW );

  /* disable all interrupts, if we get interrupted we might timeout the WDT */
  cli();

  /* Reset the watchdog counter so we know that we are starting at 0 */
  wdt_reset()

  /* Enable the WD interrupt (note no reset). */
  WDTCR |= (1<<WDIE);

  set_sleep_mode( SLEEP_MODE_PWR_DOWN );   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */

  sleep_enable();
  sei();
  /* Now enter sleep mode. */
  sleep_cpu();
  cli(); // Make sure we have time to disable WDT before we get reset

  /* Disable the WD interrupt */
  WDTCR &= ~_BV(WDIE);

  /* The program will continue from here after the WDT timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  sei();

  // Status pin goes low
  digitalWrite( STATUS_PIN, HIGH );

  /* Re-enable the peripherals. */
  power_all_enable();

}

Problem is that the whole program freezes right after I setup the watchdog prescaler with switch case. Even if I never use enterSleep function, it still does happen.

If the wdt is enabled when you change the prescaler, it is possible the whatever the current value of the counter is happens to be above the new prescaler, which would cause an instant wdt timeout. That is why it is important to always clear the counter before updating the prescaller- and to do it when no interrupts are possible so the processor doesn't get sidetracked in between the steps.

If WDE is set, the Watchdog Timer is in Interrupt and System Reset Mode. The first time-out in the Watchdog Timer will set WDIF. Executing the corresponding interrupt vector will **clear WDIE** and WDIF automatically by hardware, so calling WDTCR &= ~_BV(WDIE); is pointless.


text:
Serial communication on Arduino Uno
I have a Raspberry Pi 3 connected to the serial of my Arduino Uno (pins 0 and 1), but I also have another device connected to two other serial pins on the Arduino (pins 10 and 11, using the SoftwareSerial library).
What I want to do is send a string from the RPI, then the Arduino gets it and resends that information through the other serial port to my device.
Until now the Arduino can receive the information from the RPI, but I'm not sure how to send that same string through the other serial port, the one going to the device.
Here is the code I'm using:
#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    b = Serial.readString();
    Serial.println("Data from RPI:");
  }
  portOne.listen();
  while(portOne.available() > 0){
      Serial.println("Data from port one:");
      Serial.println(b);
    }
  }

I just get the data coming from the RPI, but nothing from portOne.
Any thoughts?

You might find this interesting about buffers on both sides of a Nano connected to a Raspian system running a Python data logger, using just a regular USB programming cable between the two:
https://arduino.stackexchange.com/questions/11710/does-data-came-on-serial-port-store-for-some-time

Instead of just using pins 1 and 0 I use the regular serial-to-USB programming cable.  Ont he Pi it comes in as /dev/ttyUSB0 or /dev/tty ACM0 depending on the board.  The main advantage of doing this is that you can WiFi int o your Pi with RDP and remotely reprogram the ASrduinos on the fly as necessary.  Your strange readings may well be because of the way you are cabling to the module.  Perhaps try software.serial and regular pins?

After reading more about the SoftwareSerial, I managed to get the communication I wanted in a simpler way. This is what I ended up using in my void loop:
void loop() { // run over and over

  if (Serial.available()>0) {
    HW = Serial.read();
    mySerial.write(HW);

  }

  if (mySerial.available()>0) {
    SW = mySerial.read();
    Serial.write(SW);
  }
}

Thank you all for your help, your answers gave me also a better understanding of what I was doing.

Your code is not reading the SoftwareSerial. b is only populated when the Pi sent data. The loop below sends what it reads from the SoftwareSerial, after that is prints a new line println() (only because that's what your code is doing)
The listen() method of SoftwareSerial is only required if you have more than one SoftwareSerial connection.
#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    b = Serial.readString();
    Serial.println("Data from RPI:");
  }

 //not required with only one software serial connection
 //portOne.listen();

  if (portOne.available() > 0)
  {
   while(portOne.available() > 0){
      byte byteRead = portOne.read();
      Serial.write(byteRead);
    }
    Serial.println();
   }
  }

I tried something like this with no luck. I read that a limitation SoftwareSerial has, is that the ports can retrieve data one at a time. Could this be affecting me? should I interrupt the serial port between the RPI and the Arduino?

Try the softwareSerial on pins 2 and 3 otherwise post a code example. You haven't given much information such as baud rates so the issue could be anything. There isn't normally an issue using serial and soft serial together.

I added an Edit of the question where I added the code.

I have updated the answer, see if that makes sense to you.

If you goal is to relay a string from RPI through the Arduino to a device connected via SoftwareSerial then you should be doing something like this:
#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {

  if (Serial.available() > 0) { // data available on HW Serial
    b = Serial.readString();    // Read it
    portOne.print(b);           // and write it to SW Serial
  }

}


text:
How can I store the received data from nRF24l01+ module in an array (code in description)?
This is my sample RX code for 4 Tx and 1 Rx nRF24l01+ modules. I want to store all the data received from 4 pipes into an array (recArray).
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8);

const uint64_t pipes[4] = {0xF0F0F0F0E1LL, 0xF0F0F0F0E2LL, 0xF0F0F0F0E3LL, 0xF0F0F0F0E4LL};
char text[32] = {0}; #received data
int recArray[4]={0, 0, 0, 0}; # array to store the received bytes

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(1, pipes[0]);
  radio.openReadingPipe(2, pipes[1]);
  radio.openReadingPipe(3, pipes[2]);
  radio.openReadingPipe(4, pipes[3]);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

I would suggest to send 2 bytes to this module
the first byte is the pipe number (0xE1,0xE2,0xE3,0xE4)
and in the second byte Data
void loop()
{
  if (radio.available())
 {
  radio.read(&text, sizeof(text));
  for (int i=0; i < 4 ; i ++)
   {
     if( text[0] == ((unsigned char *)(&pipes[i]))[0]
        recArray[i] = text[1];
   }
  Serial.println(text[1]);
 }
}


text:
HC-06 pairing to arduino
I have a bluetooth module HC-06 and want to pair it to my Arduino UNO. The thing is when I researched how to do so, I got different answers. What pairing should I use? Thank you in advance. I have highlighted the differences.
First version:
https://www.instructables.com/id/Add-bluetooth-to-your-Arduino-project-ArduinoHC-06/
HC-06>>>Arduino
VCC>>>>3.3v
GND>>>>GND
TXD>>>>RXD
RXD>>>>TXD
Second version:
http://42bots.com/tutorials/hc-06-bluetooth-module-datasheet-and-configuration-with-arduino/
HC-06            <<>> Arduino
HC-06 Ground GND <<>> GND
HC-06 VCC pin  <<>> 5v
HC-06 TX/TXD pin <<>> Arduino RX
HC-06 RX/RXD pin << resistors >> Arduino TX
[![enter image description here][1]][1]
[![enter image description here][2]][2]

Which you use depends on two factors: the HC-06 carrier board you have, and which Arduino you are using.
If your carrier board has (and most do) a 3.3V regulator then you power the board from 5V.
If your Arduino is a 5V Arduino (such as an Uno) then you need a voltage divider on the (arduino)TX->(hc)RX pins otherwise you risk damaging the bluetooth module.

Thanks. How can I tell the carrier board of the HC-06 only by looking at the device itself. I have no manuals or other information about it.

@B.Parvi Post a picture.

@B.Parvi Ok, that's one of the normal cheap eBay carriers. Yes, it has a voltage regulator. Give it 5V on Vcc.


text:
Adafruit Huzzah espcomm_open failed
I recently bought an adafruit huzzah as well as a serial to usb cable to connect it to my computer running windows 10. I was able to get the board set up in arduino following the directions found here. I copied and pasted this sketch:
void setup() {
  pinMode(0, OUTPUT);
}

void loop() {
  digitalWrite(0, HIGH);
  delay(500);
  digitalWrite(0, LOW);
  delay(500);
}

into the arduino 1.8.2 IDE, followed these instructions:

Hold down the GPIO0 button, the red LED will be lit
While holding down GPIO0, click the RESET button
Release RESET, then release GPIO0
When you release the RESET button, the red LED will be lit dimly, this means it's ready to bootload

and tried to upload only to get an error:
In versions 1.6.5 and 2.0.0 of the esp library I get these errors:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_open failed

In versions 2.1.0 - 2.3.0 of the esp library, I get these errors:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I've tried switching the tx and rx leads, I've tried versions 1.6.5-2.3.0 of the esp8266 library. I've also tried it on the other board that I ordered and got the same errors. Any ideas on what could be the problem?
EDIT: I've now tried it on a generic esp-01 board and am having the same issue

in Arduino IDE, open the serial monitor, click the reset button on the huzzah - do you see anything in the serial monitor - if nothing at all (no text or even garbage characters) then you either: a) have tx/rx connected incorrectly, or b) haven't selected the correct COM port, or c) have a defective huzzah (or you killed it)

aside: if you like the huzzah, checkout the wemos D1 mini (1/2 price) and the nodeMCU (1/3 price)

You may find this helpful: https://github.com/esp8266/Arduino/blob/master/doc/faq/a01-espcomm_sync-failed.md. If it solves your problem please come back and write an answer to your question to help others who have the same trouble.

@per1234 I followed the guide and noticed that in my verbose upload output, it's setting the board to nodemcu. Is that normal for a Huzzah?

I had to install the SiLabs CP2104 drivers and reboot.
Make sure you don't have 2 connection (Arduino IDEs, VS Code with PlatformIO, ...) open. Also, I kept pressing the reset button the first time.
https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/using-arduino-ide


text:
HMC5883L - Tilt compensation without Accelerometer
Trying to get an HMC5883L to compensate for being installed in 90 degrees. Doesn't seem to me that it'll need too complex math or accelerometer. But I have no idea how to do the compensation for it. Any idea?
Using the Adafruit HMC5883L and its library.

You can always use the normal tilt compensation equations with a fixed value instead of a calculation from the accelerometer; Since you know the rotation beforehand the equations may not be as complex. For example, if the tilt is only on one axis, it's just one rotation matrix multiply (and you don't need to calculate the result z axis) instead of 3 in general.
If the tilt is constant and exactly 90 degrees, You just need to swap which magnetometer axis are put into the magnetic field angle equations. If one axis is pointed towards the center of the earth, you can use the other two axis to calculate the direction of the magnetic field without an explicit rotation transformation.


text:
How to make ESP8266-1S module work on Arduino Uno?
I currently have an Arduino Uno with an ESP8266-1S. However I can't make them work... I use the ESP8266wifi.h library and its connection functions do return a true (returns true when received a valid IP), but I can't find it in my network...
When I send 'AT' ending with CR and NL on 115200 baud I still don't get a response.
Also, do I have to connect RX with RX and TX with TX or RX to TX and vice versa?
And also, do I need any converters? Because now I directly connect the TX and RX to the Arduino's TX and RX.
So this is how my board looks like:

So what am I doing wrong?

Are you sending the "AT" from code running on your Uno or are you sending it from the Serial Monitor (or any other terminal program running on your computer)?

I send it using the serial monitor from Arduino

ESP8266 WiFi module and 5V Arduino connection

you need to short rst to gnd on the uno to bypass the avr and use uno as an "ftdi"

do I have to connect RX with RX and TX with TX or RX to TX and vice versa?

If you want to do serial communication between a sketch running on the Arduino and the ESP8266 you must connect the RX pin on the Arduino to TX on the ESP8266 and the TX pin on the Arduino to TX on the ESP8266.
If you want to do serial communication between the Serial Monitor on your computer through the USB port on the Arduino to the ESP8266 you must connect the RX pin on the Arduino to TX on the ESP8266 and the TX pin on the Arduino to RX on the ESP8266.
TX stands for Transmit and RX stands for Receive. So it makes sense that you should connect the transmit pin to the receive pin in the first case. But why connect transmit to transmit and receive to receive in the second case? The reason is that you are not communicating between the main microcontroller (ATmega328P on the Uno) and the ESP8266. You are communicating between the USB-serial chip on the Uno (usually ATmega16U4 on the official Arduinos or CH340 on the clones) and the ESP8266. The main microcontroller is not being used at all, you're just using the Arduino as a bulky and inconvenient USB-serial adapter.
In fact some people will go so far as to remove the ATmega328P from their DIP Unos for this purpose. The RX pin on the USB-serial chip is connected to the TX pin on the main microcontroller as well as the TX header pin and vice versa for TX pin on the USB-serial chip. This means by connecting the ESP8266's TX pin to the TX pin on the Uno's header you are actually connecting it to the RX pin on the USB-serial chip. I would highly recommend getting a USB-serial adapter made for this purpose rather than trying to use an Arduino. You can buy FTDI FT232 or CH340 breakout boards on eBay or Aliexpress for < $2 USD w/ free shipping.

do I need any converters? Because now I directly connect the TX and RX to the Arduino's TX and RX

This is actually two questions. Let's address the easy one first. The TX pin of the ESP8266 is going to put out around 3 V. Even though the ATmega328P is running at 5 V this will still be seen as a high so no level conversion on that pin is necessary.
Now for the question of whether it's needed on the ~5 V level from the Arduino to the ESP8266 RX pin. There's a lot of disagreement on the question of whether the IO pins on the ESP8266 are 5 V tolerant. We certainly know that it's possible to connect the ESP8266 to 5 V levels as there are many projects published online that do this but the question is will this will shorten the life of the ESP8266?
The datasheet for the ESP8266 does not say the inputs are 5 V tolerant. There is a statement on the ESP8266 forum from a member of the Espressif (creator of the ESP8266) staff:
http://bbs.espressif.com/viewtopic.php?t=1145

We donot recommend you to apply 5V to IO.

We have a comment from someone on Facebook named "Teo Swee Ann" who appears to be the CEO of Espressif:
 https://www.facebook.com/groups/1499045113679103/permalink/1731855033731442/?comment_id=1732364133680532

i can reply officially here: it is 5V tolerant at the IO. while the supply voltage is at 3.3V.

So there is conflicting information and none of it has been presented in the most official manner, such as actually putting it in the datasheet. One thing we do know for sure, you will not harm the ESP8266 with 3.3 V levels. So the safest option is to avoid giving it 5 V inputs. However, as you are currently struggling just to get the most basic communication working the extra complication introduced by adding level shifting circuitry may not outweigh the possibility of reducing the life expectancy of your ESP8266.

Thank you for your great answer ,but I still have some questions: for serial com, do I have to connect the TX and RX both to the RX of Arduino? Or is it a typo? And when I try to upload the code, I get the espcomm_upload_mem failed error... And can I give the module 5V supply voltage for testing, or is that a total no-go?

That was a typo. I've fixed it now. Thanks for pointing that out. It should be TX-TX, RX-RX for communication from Serial Monitor to the ESP8266.

Regarding the espcomm_upload_mem failed error. Are you trying to upload code directly to the ESP8266 using the Arduino IDE? That's fine but be aware If you do that you will overwrite the AT firmware and will no longer be able to use the ESP8266wifi library on the Uno or control it from the Serial Monitor using AT commands unless you reinstall the AT firmware. Note that there is a library named ESP8266WiFi included with the Arduino ESP8266 core that has a similar name but is completely different from the ESP8266wifi library.

Regarding 5 V supply voltage. You should never power the ESP above 3.6 V and I wouldn't go much above 3.3 V to be safe. The discussion about 5 V tolerance is only for the IO pins. There has never been any confusion regarding the maximum supply voltage, that is stated clearly in the datasheet. Some ESP8266 boards do have voltage regulators that allow them to be powered by 5 V but they reduce the voltage to the ESP8266 to 3.3 V. The ESP-01 type module shown in your wiring diagram does not have the voltage regulator.


text:
Name of the Arduino Nano clone in the device manager
I'm working on an app using Matlab and it recieves data from an arduino. I've changed my board into an Arduino Nano (clone) recently. My program will automatically check for the device's name in the list of serial devices connected and it will connect to it directly once the user presses connect. The user doesn't have to input any Com port number or baud rate. This worked fine with my previous boards (UNO, Pro Micro, Leonardo). I just need to change the search string in my code and it'll automatically connect. My current board however is different, I'm using VMA102 (Arduino Nano clone). It uses FTDI drivers which I downloaded following this tutorial. I can upload the codes correctly to it but I just doesn't show a name with in the ports list in Arduino IDE as shown in the picture below.

Now when I looked it up in the device manager the name was 'USB Serial Port (COM5)' so I pasted 'USB Serial Port' as my search text in Matlab, it doesn't find it. I concluded that the correct name for it is not 'USB Serial Port' but rather the 'no name' as shown in Arduino IDE. Is there a way to find what is it called or how I can change it into a unique name so that my app can search for it?
Edit: here is the code, it works fine with all the other boards:
    devices = IDSerialComs();%gets all the avilabe com ports and thier names (name, com#)
    assignin('base','devices',devices);%save it to main workspace
i=1;index=0; tesst= zeros(length(devices),1);%saves the comparison results
while i<=length(devices)
    tesst(i)= strcmp(devices{i,1},'USB Serial Port');%compare the received names with the board's name
    % 'SparkFun Pro Micro''Arduino Uno'
    if ( tesst(i)==1 )
        index=i;%save the index
    end
    i=i+1;
end

if(isempty(find(tesst,1)))
    msgbox({'Connection failed' ' plug the device, wait for 5 seconds then try again'} ,'Connection Failure','error');
else
    msgbox('Connection successful, proceed to the next tabs', 'Connection success');
end
%get the COM# associated with the index and add COM before it to from the comport number as a string
COM_Num = strcat('COM',num2str(devices{index,2}));
comport= serial(COM_Num, 'BaudRate', 115200);

and here is a screenshot of my device manager

Thanks

Please include program code that performs search and connect a serial device and a screenshot of the device manager.

The name shown in the Arduino IDE's Tools > Port menu is set in the Arduino boards.txt file (https://github.com/arduino/Arduino/blob/1.8.2/hardware/arduino/avr/boards.txt#L49) so that is not relevant to Matlab. Can you search for VID/PID instead? FTDI FT232RL chips come with a default VID: 0403, PID: 6001 unless the purchaser specifies otherwise. That still won't help you if there are multiple FT232RL attached to the computer but it's an improvement at least.

Assuming that I only have 1 FTDI FT232RL (which is the plan), what should its typical name be "0403 6001"? and is this the same with CH430 drivers (in case I want to buy one)

I've done some debugging, and I found out that the function that searches for all the serial devices returns an empty cell when my Nano is the only board connected. Could this be because it has no name (Arduino shown "no name" only a port number)

CH340 is VID: 1A86, PID: 7523

The  IDSerialComs() function scans the Windows registry and associated active COM ports with their registered "Friendly Name". To scans using the following path:
'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\'

But driver FTDI uses another path:
'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\FTDIBUS\'

Try to modify the function so that it meets your needs.

Thank you very much @AltAir! I modified it an it worked! I hope this helps others as well.

If you do a windows search for the device manager you will be able to see all the com devices currently connected to your computer. Unplug and replug your Arduino and it should be pretty easy to spot.
Mine is the USB-SERIAL CH340

Yes i've done that, my board is called "USB Serial Port" which is not found when searched for. From my research, I read that with this driver all connected devices that use this FTDI driver will have exact same name, even if connected at the same time.

Does USB Serial CH340 appear when you look for your board in Arduino IDE? or does it only show the com port number?

It just shows up as a com port in my IDE, I use STINO

Matt, yes it will show as a com port only in the IDE, I realized that only the original boards will show up by their name in the IDE.


text:
Why analogue pins affect each other?
I have a sensor and it generates an analogue signal.
I am reading all analogue data and sending it to my computer.

uint8_t sensors[] = { A0,A1,A2,A3,A4,A5,A6 };
const int len = sizeof(sensors) / sizeof(sensors[0]);
void loop(void)
{
    for (size_t i = 0; i < len; i++)
    {
        auto sensor = sensors[i];
        int sensorValue = analogRead(sensor);
        // Convert the analogue reading (which goes from 0 - 1023) to a voltage (0 - 5V):
        float voltage = sensorValue * (5.0 / 1023.0);
        char t[100];
        sprintf(t, "%d:%d$\n", sensor, sensorValue);
        uint8_t t1[100];
        //PrintSerial.println(t);
        memcpy(t1, t, 100);
        wifi.send(t1, strlen(t));
    }
    delay(300);
}

I plotted the analogue reading. Why does the graph look like this?

breadboards have a few puff of capacitance between rows

This is to be expected.
The other pins have nothing connected to it, so their voltage is floating.
The Arduino MCU only has a single ADC. To read the different analog pins, it uses a multiplexer to connect the pin you want to read to the single ADC. The ADC inside the MCU have a "sample and hold" capacitor inside it.
To read the voltage at the pin, it will connect the pin, to charge the sample and hold capacitor. It will then disconnect and measure the voltage of the sample and hold capacitor, one bit at a time.
So in your case, by reading the voltage at the connected pin, it will charge the capacitor. It will then read the unconnected pins. But because nothing is connected the sample and hold capacitor will stay at about the same voltage, because the unconnected pin will neither charge, nor discharge it.
Measuring the voltage on the sample and hold capacitor will slightly lower this voltage, so that's why in the graph the lines will be lower than the previous measurement.
PS Also, because all the pins are placed in a breadboard, you'll have some capacitive coupling between the adjacent pins.

So there is no problem?It wouldn't decrease the accuracy if there is another pin?

Not really. Unless the signal you are trying to read has a very high output impedance. You could connect the unused pins to ground, if you want to get a cleaner graph.

The acc is really a little capacitor. As you switch channels, the charges in the acc capacitor get carried from one input channel to the next. If the next input channel is of very high impedance, or very low capacitance, the charges on the acc capacitor dominate and its voltage changes little.
In addition, poor code can cause it too - usually from a lack of sufficient time for the add to complete.

You mean I need add a delay in for loop?


text:
Writing a custom character on an lcd
I am using a 16*2 lcd display as a dashboard computer.
I want it to display a logo at the very beginning of the code, but some letters occupy the space of 4 characters, and are using both lines of the display, and creating those letters character by character (some actually require 6 characters) is very difficult.
Is there anyway i can address the lcd as a big matrix ?
there would be 16 lines ( the oringinal 2 lines * 8 lines of each character) and 80 columns (the original 16 columns * 5 columns each character has).
This would make it A LOT easier.

Model of the display and links to technical documentation?

The display:http://www.ebay.com/itm/1602-16x2-Character-LCD-Display-Module-HD44780-Controller-Blue-Arduino-/171983948287?hash=item280b0ac9ff:g:RsQAAOSwtnpXmusW
Data:
https://www.sparkfun.com/datasheets/LCD/HD44780.pdf

In the character generator RAM, the user can rewrite character patterns by a program.  Page 13 of the datasheet.

If I remember correctly, you can create up to 8 custom characters (custom bitmap). You can then use those characters anywhere on the display. There is no way to directly set pixels.

The chip you are using (HD44780) only works with characters; you can't address single pixels. If you read the datasheet, the word "pixel" is absent.
Of course, you can add a wrapper that implement a drawPixel(row,col) function by defining custom characters and then sending it to the display.
The result will be unpleasent to the eye, because there is a gap between chars on screen, and another gap between rows.

A better alternative is an OLED display like this:

You can find the same display with I2C or SPI interfaces. Basic model is B&W, but you also have color and touch sensitive variants.

some letters occupy the space of 4 character

use CGRAM to define 4 characters and display them over two lines.


text:
ESP8266-01 connected to Arduino Mega - Current output?

I was thinking of powering my arduino with an external 9 V power source, but I am still trying to figure out the best way to get the right amount of current for the Wi-Fi module. Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?
If there is an easier way to do this I am all ears. I will be using Arduino Mega, not uno as shown in the picture.
EDIT: Voltage divider will be used on the RX pin and I might go for a logic level converter instead of the voltage regulator

you don't need 500ma supply current for ESP01s. If you use a 1000u cap, it doesn't even spike above 100ma.

Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?

Either way you're going to need a power supply that can supply the current. A transistor doesn't magically create more current, it merely allows a small current to control the flow of a larger current.
So you will need an external power source that can provide enough current.

I might go for a logic level converter instead of the voltage regulator.

Incorrect. A logic leven converter cannot provide anywhere near enough current to power a device. It can barely provide enough to light an LED.
You are right to want to ditch the voltage regulator though.
As it stands you have a chain of regulators, each one wasting power. At 500mA that's lots of power.
9V -> [REG] -> 5V -> [REG] -> 3.3V

That's 4V dropped in the first regulator at ~500mA, and 1.7V dropped in the second regulator at ~500mA. Since P=VI, 4×0.5 = 2W, and 1.7×0.5 = 0.85W. Since you are providing 9×0.5 = 4.5W of power from the battery, you have 1-((2+0.85)÷4.5) = 0.366, or 36% efficiency. That's about two thirds of your battery power wasted just in heat.
Instead you want to use a switching voltage regulator. These are far more efficient and convert voltage into current rather than voltage into heat. This means that you draw less current from your battery, meaning you can use a battery with a higher internal resistance.
Ideally you would use two - one to convert the 9V into 5V to power the Arduino, and another to convert the 9V directly into 3.3V to power the ESP8266. That would be the most efficient arrangement.
There are plenty of breadboard friendly modules on eBay that can do that, or other small modules you can wire in to your circuit without a breadboard (I myself sell one on eBay that I designed).


text:
Arduino Uno WiFi - WiFi mode keeps changing
I have an Arduino Uno WiFi device, which is turned on all the time (day and night). The WiFi mode is set to 'STA'. But from time to time it switches to 'AP+STA' mode automatically, so the device is visible in the network as an Access Point, which is not what I want. Is there a way to prevent my Arduino Uno to switch the WiFi mode by itself? Can it be done via code maybe? Thank you for your help.
Here's the code that is working on it (and it's still working without any problems):
#include <Wire.h>
//#include <Ciao.h> // for older IDE
#include <UnoWiFiDevEd.h> // for newer IDE

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

int sensorsValues[] = {9999,9999,9999};
int timerCount = 25;
static const uint8_t analogPins[] = {A0, A1, A2};

// for LEDs
int NUMPIXELS = 9;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXELS, 2); // (numOfPixels, pinNo, options)

boolean hasChanged = false;

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code
  //start serial connection
  Serial.begin(9600);
  for(int i=0; i<3; i++){
    pinMode(analogPins[i], INPUT_PULLUP);
  }
  strip.setBrightness(40);
  strip.begin(); // Initialize the NeoPixel library.
  strip.show(); // Initialize all pixels to 'off'
  Ciao.begin();
}

void loop() {
  for (int i = 0; i < 3; i++) {
    int sensorVal = analogRead(analogPins[i]) >= 1000 ? 1 : 0;
    if( sensorsValues[i] != sensorVal ) {
      hasChanged = true;
      if (sensorVal == 1) {
        // green light
        strip.setPixelColor( (i*3), 100, 255, 100);
        strip.setPixelColor( (i*3)+1, 100, 255, 100);
        strip.setPixelColor( (i*3)+2, 100, 255, 100);
        strip.show();
      } else {
        // red light
        strip.setPixelColor( (i*3), 255, 50, 50);
        strip.setPixelColor( (i*3)+1, 255, 50, 50);
        strip.setPixelColor( (i*3)+2, 255, 50, 50);
        strip.show();
      }
    }
    sensorsValues[i] = sensorVal;
  }
  timerCount += 1;
  if( hasChanged == false && (timerCount % 30) == 0 ){
    CiaoData data = Ciao.write("rest", "xxx.xxx.xxx.xxx", "/d/add/A001/active", "GET");
    if (!data.isEmpty()){
      String st = String(data.get(1));
      String re = String(data.get(2));
    }
  }
  if (hasChanged == true && (timerCount % 5) == 0 ) {
    CiaoData data = Ciao.write("rest", "xxx.xxx.xxx.xxx", "/d/add/A001/a/" + String(sensorsValues[0]) + "," + String(sensorsValues[1]) + "," + String(sensorsValues[2]), "GET");
    if (!data.isEmpty()){
      String st = String(data.get(1));
      String re = String(data.get(2));
    }
    hasChanged = false;
  }
  if (timerCount > 30) timerCount = 0;
  delay(1000);
}

Are you running any code on it?  If so is it possible for you to post the code.

Yes, the code reads 3 analog sensors, send their values to server if any has changed and it controls LED strip. Seems like I can't post the code here..

You can't do that :)  You'll need to edit your post.  Have you tried monitoring it with something like Blink running (a do nothing program).  If it doesn't do it then its your code, if it does its something to do with the board.

@CodeGorilla I just edited my question adding a code.

So unless Ciao.write() is flicking the AP on and off its a function of the board.  There might be some register you can set to prevent it, but your going to have dig through the documentation for the board.  Sorry :(

Well, I already dig a lot in the documentations but found nothing. That's why I posted this question here.. Anyway, thanks.

OK. I found a little workaround. Arduino UNO Wifi web interface gives some possibilities. When you go to http://<IPADDRESS>/wifi/info you'll get json formatted info about its wifi connection settings, including WiFi mode (STA or AP+STA). To set new WiFi Mode you can go to http://<IPADDRESS>/wifi/setmode?mode=<MODE> to set new mode. mode=1 is for 'STA', mode=2 is for 'AP' only and mode=3 is for 'AP+STA'.
I've created a little cron job on my server that checks the wifi mode and changes it if needed.

Note that when the Uno WiFi board first boots, it is in AP+STA mode...

Which means it broadcasts its own SSID (that's the AP part).

AND

It can connect to an existing wireless AP on your network, if you've configured those settings (that's the STA part, because it's a STAtion off the infrastructure AP).

IDEALLY

You will change it to STA mode so it connects to your existing wireless AP only and stops broadcasting as its own AP.

Why does yours go back to AP+STA mode?  Is your sketch crashing/running out of memory/rebooting?  Is it older firmware?  I'm not sure.

The thing is that I have 5 Uno WiFi boards that are working all the time, all of them doing exactly the same stuff (just in different areas of our warehouse). Only two of them are sometimes switching to AP+STA mode in a different periods of time - sometimes once a week, sometimes more frequently. Other 3 devices are running without an issue.


text:
Adding data to an SD card file
I'm reading data from the Shinyei PPD42 particle sensor unit.
Everything seems to work, but I'm encountering two problems

When I restart Arduino, the file is not being extended, nor overwritten. It just remains how it was before.
Even though my code looks fine, Arduino stops writing data to the SD card after 90 seconds.

Thanks for having a look at my code.
#include <SPI.h>  //een bibliotheek aan code toevoegen; Arduino heeft deze nodig om de Shield te kunnen 'lezen'
#include <SD.h>   //zie hierboven

int PM=8; //de fijnstofmeter zit in digitaal poortnummer 8

const int chipSelect = 10; //const = een variabele die nooit verandert

unsigned long sampletime_ms = 30000;  //unsigned long = een variabele die erg hoog kan oplopen, maar nooit negatief kan zijn

//hieronder volgen nog enkele variabelen. Denk eraan: float betekent dat het decimale getallen kunnen zijn

unsigned long duration;
unsigned long starttime;
unsigned long lowpulseoccupancy = 0;
unsigned long timediff;
float ratio = 0;
float concentration = 0;
unsigned long tijd = 30;

//void setup wordt één keer uitgevoerd, bij het opstarten van de Arduino-minicomputer

void setup()
  {
    Serial.begin(9600); //de snelheid (in bits/second) aan welke de seriële data zal worden getransfereerd
    pinMode(PM,INPUT);  /*PM is de variabele van helemaal bovenaan: pinMode vraagt twee parameters 1)de poort (werd gedefinieerd bovenaan) 2)INPUT of OUTPUT
                          Ditmaal leest de fijnstofmeter gegevens die we vervolgens IN onze Arduino willen importeren, dus INPUT*/

    starttime = millis(); //hoelang draait het programma? millis() geeft de duur sinds het werd opgestart

    Serial.println("SD-kaart opstarten indien aanwezig... "); //Je schrijft nu neer dat de SD-kaart wordt gezocht en opgestart (println = hierna op volgende regel verder gaan)

    //hieronder staat een 'als'-lus: als aan de eerste voorwaarde wordt voldaan, voert hij uit wat eronder staat, anders gaat Arduino verder achter de afsluitende accolade

    if (!SD.begin(chipSelect)) //Als er NIET (!) kan worden begonnen met de SD-kaart te selecteren ...
      {
        Serial.println("Corrupte of ontbrekende SD-kaart!"); //dan wordt deze boodschap getoond
        return;
      }
    //Als de SD-kaart dus WEL werkt, gaan we hieronder verder

    Serial.println("SD-kaart werkt...");
    Serial.print("Fijnstofsensor start op. Even geduld! Metingen om de 30 seconden.");
    Serial.println("\n");
  }

//void setup wordt oneindig lang uitgevoerd, tenzij je dat anders bepaalt

void loop ()
  {
    duration = pulseIn(PM, LOW); //als de fijnstofdetector niet meet (LOW), beginnen meten
    lowpulseoccupancy = lowpulseoccupancy+duration; //na elke meting de 'duration' (30 sec)  optellen bij de totale tijd

    if ((millis()-starttime) >= sampletime_ms)
      {
        //hieronder de wiskundige berekeningen om het fijnstofgehalte te berekenen

        ratio = lowpulseoccupancy/(sampletime_ms*10.0);
        concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62;

        //hieronder alles wat zal worden geprint naar het seriële venster

        Serial.print("Fijnstofconcentratie na ");
        Serial.print(tijd);
        Serial.println(" seconden:");
        Serial.print(concentration);
        Serial.println(" deeltjes/0,01cf");
        Serial.print("\n");

        File dataFile = SD.open("test.txt", FILE_WRITE); //het bestand meting.txt moet op de SD-kaart worden geopend om erin te schrijven

        if (dataFile) //als het bestand kan worden geopend, volgende gegevens printen
          {
            dataFile.print("Fijnstofconcentratie na ");
            dataFile.print(tijd);
            dataFile.print(" seconden: ");
            //dataFile.println(ratio);
            dataFile.print(concentration);
            dataFile.print(" deeltjes/0,01cf");
            dataFile.print("\n");
            dataFile.close();
          }

        else //als het bestand niet kan worden geopend ...
          {
            Serial.println("Fout bij het openen van test.txt");
          }

        tijd = tijd + 30; //meting afgerond, totale tijd = +30 seconden
        lowpulseoccupancy = 0; //de status van de fijnstofmeter is terug 'LOW'
        starttime  = millis(); //volgende meting starten
      }
  }

Try to put your comments also in English (you never know when a non-Dutch person will read it ... like mostly here) ... succes!

You need to open the file in append mode:
SD.open("file.txt", O_RDWR | O_APPEND);

It depends on the file being there. If it fails to open because the file isn't there you can open it in "create" mode instead:
SD.open("file.txt", O_RDWR | O_CREAT);

For example:
// Try and append
File f = SD.open("file.txt", O_RDWR | O_APPEND);
if (!f) {
    // It failed, so try and make a new file.
    f = SD.open("file.txt", O_RDWR | O_CREAT);
    if (!f) {
        // It failed too, so give up.
        Serial.println("Failed to open file.txt");
    }
}

// Only write to the file if the file is actually open.
if (f) {
    f.print(/* your data here */)
    f.close();
}

Do I only add the second line instead of the SD.open line I had?

No. You need both. I'll expand to show you.

Thank you. Will this yield the same result? File dataFile = SD.open("test.txt", O_CREAT | O_APPEND | O_WRITE);

I don't think you can both create and append at the same time. You can give it a go though. Personally I like to be specific about these things so there is no chance for ambiguity.

Majenko, any idea what I did wrong here? Using your solutions since my adaptation doesn't work after all: https://pastebin.com/k4xbyBpR

You need the writing to the file to only happen once the file has been confirmed as open through whatever method. That is - Open for append, if failed, open for create. If succeeded then write. I'll modify my example.

Let us continue this discussion in chat.


text:
Not sure I'm understanding pipes for NRF24
I've started working with the NRF24 library for some fun little side projects. I have only gotten through some basic tests but I'm starting to look at ways to tinker with the code. I have more experience as a programmer so the hardware side is always new to me. Where I'm a little confused is how the pipes are used. Working from this example, I see that one pipe is used to listen and another is used to transmit. If there's just two devices, why don't they both use the same pipe? If you have multiple devices on the same pipe transmitting, can it jumble the signals? Is there a way to receive on multiple pipes? I'd love more information on how pipes are or should be used.

I don't see any reason for doing this.
Multiple devices sending data at the same time will cause collisions irrespective of the pipe-nr they are using.
Pipe is also a not very accurate name for what it actually is. It's just a number, that the receiving NRF can check, to see if the packet that was received was intended for it. Kind of like a MAC address on a network.
You can have two unique reading pipes. Then there are 4 more pipes you can use, that are identical to the second pipe, except for the last byte.
The first pipe is used to specify the pipe you are sending through. So if you send to different pipes, this pipe isn't ideal for listening, as you'd have to change it back every time you send a packet. Possibly loosing a packet that was send in between.
If you want more information, i'd suggest reading the datasheet, and read the documentation of one of the libraries. I personally checked the sourcecode of the library a lot while at the same time referencing the datasheet, to really understand what it's doing.

Thanks that helps clear it up a bit. I've got a bit more to learn on it still but I think that clears some of the confusion up for me.

They are kind of weird these NRF24s

But they're cheap and if they work, they work. :D


text:
ATtiny85 Comparator C interrupt on timer 1
I have a program that uses Timer1 comparator A in CTC mode. I realize that I need to set OCR1C for the timer to reset at given value. However there is no such thing as an interrupt generated by timer1 counter matching OCR1C value.
Moreover, if I enable CTC and set for example OCR1A to 10, and OCR1C to 50, the interrupt handler ISR(TIMER1_COMPA_vect) will be triggered when the counter reaches OCR1C value, not OCR1A. I'm really confused...
Can anyone explain to me what's going on?
EDIT:
Here is the program that I'm using.
main program:

#include "avr/interrupt.h"

ISR (TIMER1_COMPA_vect) {
  PORTB ^= (1<<PB0); //toggle pin
}

void setup() {
  cli();
  // put your setup code here, to run once:
  //prescaler value 8192 sets one clock tick to about 1ms
  TCCR1 |= (1<<CS13)|(1<<CS12)|(1<<CS11)|(0<<CS10);
  //turn CTC mode on
  bitSet( TCCR1, CTC1 );
  //set comparatorA value
  OCR1A = 10;
  //enable compA interrupts
  bitSet(TIMSK, OCIE1A);
  //set comp C value
  OCR1C = 19;
  // initialize counter 1 on 0
  TCNT1 = 0;
  pinMode( 0, OUTPUT );
  digitalWrite( 0, HIGH );
  sei();
}

int main() {
  setup();
  // put your main code here, to run repeatedly:
  while(1) {
    }
 return 1;
}

You wrote “there is no such thing as an interrupt generated by timer1 counter matching OCR1C value”. Quoting the datasheet: “In PWM mode (either PWM1A=1 or PWM1B=1) the bit TOV1 is set (one) when compare match occurs between Timer/Counter1 and data value in OCR1C”. TOV1 is the flag that triggers the TIMER1_OVF interrupt. Note that you can enable PWM mode while keeping the PWM outputs disconnected from their pins (bits COM1xy cleared).

@EdgarBonet Alright, but in non-PWM mode theoretically matchA interrupt should be called whenever TCNT1 reaches OCR1A value, right? But this does not happend. In fact it is triggered only when it reaches OCR1C

I uploaded your program to an ATtiny25V (essentially a slower ATtiny85 with less memory) and I get exactly the expected behavior: a square wave on pin 0 with a period of roughly 328 ms. Note that the clock runs at 1 MHz, as the CKDIV8 fuse is programmed by default.

@EdgarBonet So you get a square wave that is high for OCR1A and low for OCR1C-OCR1A ticks?

I get 50% duty cycle, as expected from reading your code.

@EdgarBonet Ok so change the value of OCR1C to 50 and see if duty cycle changes

Did it. Period became 838 ms, duty cycle didn't change, just as expected.

@EdgarBonet But... it should change, right? Because only function that changes PB0 is ISR attached to matchA interrupt. For rest of time it should be LOW. When Counter1 reaches OCR1C, timer1 resets and whole thing starts over. If this is right, duty cycle shoulde definitly change. Correct me please if im wrong

Well, you are wrong. The only thing that changes PB0 is the ISR: every time the timer hits the OCR1A value, the pin toggles. When Counter 1 reaches OCR1C, timer1 resets and this has no effect whatsoever on PB0. If you want the timer to toggle a pin all by itself, you should use a PWM mode rather than an interrupt.

So if OCRC1A is 10 and OCRC1C is 50, pin toggles at 10, resets at 50, and then toggles at 10 etc... so duty cycle shoulde be 80% on one cycle and 20% at next. Right?

No. Pin toggles at 10, then pin toggles at 10, then pin toggles at 10... Duty cycles is 50%. Let me repeat it again: Timer 1 resetting has no effect whatsoever on PB0. Repeat: no effect whatsoever.

Let us continue this discussion in chat.

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


text:
IR sensor not detecting light or dark sufaces
I wrote code for the vibrating motors to vibrate when an IR sensor detects a darker surface. I have 4 vibration motors for corresponding 4 IR sensors. My program is not able to read the values from the sensor. In the serial monitor the values that are read from the sensor is a huge non stopping value. None of my IR sensors is detecting the surface. As a result no vibrations are produced. I am using Arduino Pro Mini and my code is:
#include <EEPROM.h>
// pin numbers
const int irLED = 7; // wire connected to transistor/220 ohm resistor (all on same pin)
const int collectors[] = {A0,A1,A2,A3}; // (with pullup resistors)
const int vibrations[] = {3,5,6,9}; // vibration motors

// thresholds for each finger
int detectionThreshold[] = {940,960,970,975};
int whiteThreshold[] = {600,600,600,600};

// timers (in milliseconds)
int lastVibration[] = {0,0,0,0};
const int numFingers = 4;
int readings[] = {1023, 1023, 1023, 1023, 1023, 1023};
boolean vibrating[] = {false, false, false, false};

void blackLoop()
{
  int now = millis();

  // get the current readings
  for(int i = 0; i < numFingers; i++)
  {
    readings[i] = analogRead(collectors[i]);
    Serial.print(readings[i]);
  }

  // vibrate on black, with minimum vibration time
  for(int i = 0; i < numFingers; i++)
  {
    if(readings[i]<=detectionThreshold && readings[i] >= whiteThreshold[i])
    { Serial.print(readings[i]);
      digitalWrite(vibrations[i], HIGH);
      vibrating[i] = true;
      lastVibration[i] = now;
    }
    else // if(now - lastVibration[i] > vibrationDuration)
    {
      digitalWrite(vibrations[i], LOW);
      vibrating[i] = false;
    }
  }
}
void setup()
{
  // put your setup code here, to run once:
  for(int i=0; i<numFingers; i++)
  {
    digitalWrite(collectors[i], HIGH);  // set pullup
    pinMode(vibrations[i], OUTPUT);
  }

   pinMode(irLED, OUTPUT);
   digitalWrite(irLED, HIGH);
   Serial.begin(9600);
   Serial.println("my sketch has started");

}

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

}

IR may not reflect off your dark and light surfaces in the same way as visible light.  Your IR sensors may not be able to tell the difference between what you perceive with your eyes as dark and light.

In addition, may types of IR receivers are designed to automatically adjust the receiver's gain so as to, for example, mitigate poor performance from randomly located IR transmitters.  IR receivers found in remote controlled TVs or remote controlled Stereos normally auto adjust their own gain.


text:
ESP8266 (ESP-01) Not booting with load on IO pin 2
I'm using an ESP-01 to control a load (SSR), which is connected to IO pin 2. This pin needs to be HIGH at boot time, otherwise the module won't boot. I've tried driving the load with an optocoupler to avoid driving the pin LOW while booting, but it's not working. Do you know of any solution to make it boot correctly without changing the IO pin? (there's only two GPIO pins, both ocuppied, plus serial port pins).

On the 01, you don't have to have GPIO2 pulled high to boot, you just can't have it grounded. I've had to use a diode (instead of a wire) to connect relay modules to pin2. btw: you can use TX as an output and RX as an input; I've driven an RGB LED with one and it works out since the LEDs blinking for  a few ms at boot was ok. All pins on the ESP-01 boot/reset high, so take that into account.

I'm already using the TX to drive the built-in LED as a state indicator, but I'll try with RX instead. But still, I'd like to know how to use GPIO 2 without screwing the booting. :S

just don't let the pin fall under 2.4v and it will boot. it's weakly pulled up internally, so keep it high or disconnected by default. depending on the internals of your SSR, you might be able to simply invert the signal wiring and make gpio2 a ground to activate it; i've done that with a few ssr/relay modules, and i didn't even need the resistor in @Majenko's 2nd sketch for some reason, but results may vary...

@dandavis Yeah, that's what I did to make it work. :D

Simply invert the logic - so that LOW turns the SSR on and HIGH turns it off.
Try something like this:

simulate this circuit – Schematic created using CircuitLab
The P-channel FET will invert the logic. Pull GPIO2 LOW and it will turn on the FET which will enable the SSR. The 10KΩ resistor keeps the GPIO pin (and the gate of the FET) HIGH at other times.
If the GPIO pin can sink enough current to directly drive the SSR you can leave out the FET:

simulate this circuit
Again the logic is inverted. Pull GPIO2 LOW to sink current through the SSR to turn it on. The resistor keeps the GPIO pin held HIGH when booting.

I did something similar to what @Majenko proposed in his answer (as in I inverted the output), but instead of using R1 as a pullup resistor in paralell with the SSR's LED, I'm using it as a normal current limiting resistor. In other words, I just swapped GPIO2 from sourcing the SSR to sinking it. The schematic is like this:


text:
Using dynamic variables in URL
I am trying to upload longitude and latitude data into MySQK using a GPRS shield, Arduino Uno R3 and a GPS module. The idea is to get longitude and latitude data from the GPS and use the GPRS to post the information into my database.
I have to insert the latitude and longitude data into the URL like  this steetalert.co.zw/write_data.php?Longitude=12.124311,Latitude=27,766785. Values for longitude and latitude have to be dynamic not static. How do I go about this?

This isn't really an appropriate place to ask people to write entire programs for you. Post the code you've got so far and explain where you're having trouble.

It looks like you need to know how to create a string that contains:
steetalert.co.zw/write_data.php?Longitude=12.124311,Latitude=27,766785
Its quite easy (I think) try this:
const int cDecimalPlaces(6);
String szLon = String(fLongitude, cDecimalPlaces);
String szLat = String(fLatitude, cDecimalPlaces);
String szUrl = "steetalert.co.zw/write_data.php?Longitude=" + szLon ",Latitude=" + szLat;

Normally I would use sprint or a Format function, but I can't find those in the reference.