text:
Debugging i2C from Mac OSX desktop
I have a raspberryPi and Arduino connected via i2C. On the RPi I have a python script that takes int values and simply sends them to the RPi, which in turn echoes them back. I am trying to debug this, since I am unable to send ints larger than 255.
One thought was that I might be able to connect the arduino slave directly to my Mac, and then use the Arduino serial monitor to help with debugging.
Unfortunately the python script will not run, because I assume i2C can only be run on a Linux kernel.
Am I mistaken?
This is an edited portion of my python code
import smbus
import time
# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

def writeNumber(value):
    bus.write_byte(address, value)
    return -1

def readNumber():
    number = bus.read_byte(address)
    return number

Your Mac probably does not have an i2c interface, unless you want to see if you can misapply one built into a legacy monitor connector (which might require kernel hacking that would be a bit harder than on linux).  How about using a simple USB logic analyzer?  Likely your problem with sending values larger than 255 is a software one - that's the limit for one byte, so you'll need to use multiple bytes to do more.  Can you add your code to the question?

Just plug the arduino into the Pi or your mac, so you can also have the serial connection for debugging. But be careful with the power. You should connect the arduino to both 5v on the Pi and 5v via the usb (mac or pi). If you are powering the arduino using the 3.3v of the Pi you might need some voltage level shifting circuitry to protect the Pi's GPIO pins from 5v (they only accept 3.3v)

No, your Mac doesn't have I2C support. It was pointed out in the comments that there might be some legacy port, but it won't be usable due to driver limitations.
You're getting a few things confused. USB is it's own technology, separate from I2C/UART/SPI. I'm not sure how you would even wire I2C to your Mac. The serial monitor in Arduino is for USB COM ports, not related to I2C.
As far as debugging, there's a few options. First of all, there are a few ways to debug I2C using an oscilloscope. If that's too expensive, you could also get away with a logic analyzer. The one I just linked was at Sparkfun for $150. If that's still too expensive and you're willing to risk $30, you can find cheap ones on eBay (most with little/no documenation).
I don't know your code, so I can't advise you on how to fix it. If you need to debug at such a low level, extra hardware is needed.
It doesn't seem like a maximum of 255 that odd, since that's the maximum number that you can do with one byte. You might have to split data up into multiple bytes with some sort of delimiter character. With some quick mental math, it seems as two bytes can give you numbers up to 65,535 if you combine both bytes (i.e. 10101010 + 01010101 = 1010101001010101).
Edit: this seems like the Arduino code you want:
#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int number = 0;
int num1 = 0;
int num2 = 0;
int state = 0;
boolean secondByte = false;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);         // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);

    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);

    Serial.println("Ready!");
}

void loop() {
    delay(100);
}

// callback for received data
void receiveData(int byteCount){
    while(Wire.available()) {
        if(secondByte) {
            num2 = Wire.read();
            number = (num1 << 8) + num2;

            Serial.print("data received: ");
            Serial.println(number);

            if (number == 1){
                if (state == 0){
                    digitalWrite(13, HIGH); // set the LED on
                    state = 1;
                }
                else{
                    digitalWrite(13, LOW); // set the LED off
                    state = 0;
                }
             }
         } else {
             num1 = Wire.read();
         }
         secondByte != secondByte;
    }
}

// callback for sending data
void sendData(){
    Wire.write(num1);
    Wire.write(num2);
}

The Python code will have to do the similar thing. Note: the first part of the number (reading left to right) will be sent first.

Thanks for the GREAT info. Excuse me , since I am a novice arduino hacker, but would I be better off in using int values, or converting to strings before sending to the arduino via i2C? That really is the first thing I have to get right, have been stumbling for the past few days simply trying to send int values larger than 255. part of my problem is that I cannot 'SEE' what is being recieved by the arduino...feel like a blind man without even being able to see any trace calls. Apologies for the length of this comment.....really trying to get this to work! Feeling only frustration right now :(

This is my 'starter' code which works for simply echoing int values 0-255. http://blog.oscarliang.net/raspberry-pi-arduino-connected-i2c/But 2 problems. Can't send values larger than 255 AND can't stream data in realtime. My goal is to send MouseXY coordinates in realtime...

@eco_bach I might be overlooking something, but I can't find your code that you use to send/receive. Also, I don't really know what you need help with... it might give you more answers if I move it to another SE site. Can you please clarify exactly what you want (i.e. need help with Python, need help with Arduino code, etc.) and I'll try to help you and/or get this question in the right place. Thanks!

Thanks. Need help on BOTH Python and Arduino side, sending-receiving int values larger than 255. linking slightly incorrect please see http://blog.oscarliang.net/raspberry-pi-arduino-connected-i2c/

@eco_bach is the edit what you want?

Thanks! Will test. One missing piece in my understanding, would I be better off converting to string values BEFORE sending over serial?

@eco_bash no: to send 250 bit by bit, you'd need one byte. If you sent as a string, you'd need three bytes.

I hesitate to ask since you have been such a tremendous help already, but need a bit of assistance on the Python end. Please see revised question above

@eco_bach can't totally write your code but, without knowing much Python, you're going to need to split convert the number into a binary as a string, split that string (make sure to have 0s on the front of the string!) and convert that to two numbers. You're going to have to write BOTH numbers. For reading, it'll be a similar process (convert to binary strings, combine, convert back to an integer). I don't know much Python so I can't help you.

Wow! didn't realize it would involve that much! There MUST be existing Python modules-code that already does this...will have to research more.

I am getting close, see http://arduino.stackexchange.com/questions/3387/receiving-2byte-int-values-over-serial, so just need to edit your sample arduino code..right now it keeps dropping the i2c bus


text:
Using Leonardo and getting absolute x,y Mouse values
Trying to modify the native mouse methods so that it can use absolute, rather than the relative values it currently uses. This is so it can function as a touch screen pointer, and NOT a mouse.
Am using this modified HID.cpp file here
https://github.com/nospam2000/Arduino/commit/7b77d1e84d7b80819f049e5fd6e7bafa0d06521f#diff-0dd97502971c8a55546092b93abd32caR349
Mostly works, but the author has mapped to the maximum and minimum possible int values, (-32768 to 32767) and no matter what permutation of values I use with the native map method, I can't get it to work properly.
Has anyone wrestled with this problem and has a solution?
Since posting found another possible solution http://forum.arduino.cc/index.php/topic,94140.0.html
However with this solution the mouse movements are WAY too coarse for any monitor with a resolution above 100x100. Tried changing the LOGICAL_MAXIMUM value in HID.cpp but that alone doesn't work. Any C++ gurus possibly able to have a look?
Going back to the first solution this is the map method calls I am using, which should theoretically work!. TAR_WIDTH is the horizontal display resolution of my target monitor. TAR_HEIGHT is the vertical display resolution
xPos2= map(xPos, 0, TAR_WIDTH, -32768, 32767);
yPos2= map(yPos, 0, TAR_HEIGHT, -32768, 32767);

What happens is that when the x value is roughly -2800 or less than, I've reached the left edge of my monitor
Ditto for y, when less than or equal to -2800, I've reached the top.
Moving to the right and or down, once I reach roughly a value of 5000, x, OR y, the mouse wraps back to the left or top edge.
This value of 5000 represents only about 2/3 the width of my target monitor so I'm never able to fully map my mouse movement. Make sense?
So in summary, if I use solution1, I need to figure out how to fully map to my monitor. If solution 2, the movement is too coarse(and the mouseclick doesn't work).

You need to explain the nature of the failure.  What is your source of data and what is it's range?  What is this plugged into, and what range of values does that see?

Modified my question, found an alternative mod, but the problem now is that the movement is WAY too coarse for any monitor with a resolution greater than 100x100 pixels

You still need to tell us what the sensor is and what its unscaled output values are.  Perhaps you should make an ordinary (USB-serial) arduino sketch which just logs the raw (and perhaps also mapped) values to the serial console so you can play with the sensor and see what raw values it generates and if that is scaling to what you want.  Then once you have nice numbers you can switch back to the HID program.

The input values aren't the problem. Its how the absolute Mouse Move hack of HID.cpp is handling these values. I'm feeding in via i2c from a RPi. Input values are accurate.

source: Stack Exchange

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

sort: votes


text:
Proxying streaming i2c data(int values) to serial
The following code works correctly in reading single int values. It also works correctly for 3-4 seconds if I 'stream' the values in constantly (Mouse move coordinates) before I get an IO error and the i2C bus connection is dropped. I assume this is some sort of buffer overrun...or? Can anyone get me on the right track here? What changes do I need to make so that I can constantly stream in serial data?
    #include <Wire.h>

#define SLAVE_ADDRESS 0x04
int zeroByte;
int state = 0;
int receivedValue = 0;

int numBytes = 0;

bool newData = false;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);         // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);

    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);

    Serial.println("Ready!");
}

void loop() {
    delay(100);
    if(newData){

      Serial.println(receivedValue);
      newData=false;
    }
}

// callback for received data
void receiveData(int byteCount){

    while(Wire.available()) {
        newData = true;
        zeroByte = Wire.read();

         if(Wire.available() == 2)
  {
    receivedValue = Wire.read() | Wire.read() << 8;

  }

     }
}

// callback for sending data
void sendData(){

    Wire.write(receivedValue);
}

Please specify which arduino board you are using and where you see the I2C io error.

Your I2C bus is operating at 100 kHz. Your serial connection is set to 9600 baud. In case you are sending coordinates at a pace faster than the serial interface can keep up, the buffer will fill up. I assume you are using hardware serial (uno, mega, etc). Once the buffer is filled up Serial.write (which is called by Serial.println) will block until the buffer has free space. But the serial transmission depends on interrupts, and you are calling Serial.write inside an interrupt routine. By defult interrupt routines block other interrupts from happening. So your program gets stuck there and locks up both the serial transmission and the I2C interface.
It would be a good idea to put the serial write outside the interrupt routine, in the loop. Make a global variable bool newData = false; and set it true in the receiveData function. In your loop check the flag and transmit the data. Then set the flag to false.
You will still experience data loss if the serial interface can't keep up, but your application wont lock up. To solve the data loss simply use a higher baud rate, eg. 115200.

brilliant answer! will test and provide feedback. Thanks

I've made you're suggested changes (see above) but I'm only seeing the 2nd receivedValue(y value) in my println statement. Could you possibly suggest what changes I need to make and I will approve your answer. Thanks again.

You need to remove the delay from loop(). Also consider using Serial.begin(115200) if you don't want data loss.

Works!.....But how do I separate out my x,y coordinates in my main loop? Serial.println(receivedValue);

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


text:
Read Multiple Sensors Data from a text file located in SD Card in Arduino/ESP32
I am working on a small home project 'glucose meter' via non invasive techniques. I am using four sensors like RGB color sensor, two multi-wavelength photo diodes (A & B) and temperature sensor (K-Type Thermocouple). I am using Multi Regression algorithm to estimate Glucose level in human body by calculate all four readings from sensors.

I am using ESP32 and I am saving all my sensors data in a CSV file (or text) after taking more than 20 calibration data from my family and friends. I can read this file after writing but I am facing a problem in reading all calibration data from this text/CSV file in the following particular manner.
Y,Sensor1,Sensor2,Sensor3,Sensor4
92,103,25,65,9875
91,104,26,62,9805
105,92,30,66,9600
150,60,40,75,9233
...,...,...,.....

Above pattern indicates 'Y' values (Blood Sugar value mg/dl) and corresponding sensors value on that time.
I am facing problem in reading these object like:
Y1 = 92, S1 = 103, S2 = 25, S3 = 65, S4 = 9875
Y2 = 91, S1 = 104, S2 = 26, S3 = 62, S4 = 9805
....................AND so forth..............
Y1000 = XX, S1 = XX, S2 = XX, S3 = XX, S4 = XX

Can any one help me how would I read and categorize each sensor values from the text/CSV File?
Thanks.

Let's say you want to read this line from the file.
92,103,25,65,9875

code is
String one_line_data = file.readStringUntill("\n");
int y,s1, s2, s3, s4;
sscanf(one_line_data.c_str(), "%d,%d,%d,%d,%d", &y, &s1, &s2, &s3, &s4);

this way to read the one line of data from file you can expand to multiple line based on application.

Function file.parseInt(), will skip non numeric characters and then parse the number stopping on non numering character. So you need only call file.parseInt() for every value in row, process the data and then loop to next row.
Y1 = file.parseInt();
S1 = file.parseInt();
S2 = file.parseInt();
S3 = file.parseInt();
S4 = file.parseInt();

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


text:
Sketch with multiple classes (.h and .cpp) - how to interconnect classes
I wanted to move most functionality of my sketch into different classes, to keep things better organized. One class worked just fine, but when I had to use multiple classes and pass information between then things stopped working.
I have two classes, my main Remote class, and my RemoteDisplay class. The main class takes care of fx, measuring battery voltage and I want to display this through the RemoteDisplay class. To do so I initiate the Display class with a pointer to the Remote class, so I can access the voltage function. This, however, doesn't work, even though I forward declare the Remote class in the Display class.
Remote.ino
#include "Remote.h"

Remote Remote;

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

void loop() {
  Remote.display.showBattery();
}

Remote.h
#include "RemoteDisplay.h"
class Remote
{

public:

  RemoteDisplay display;

  Remote( void );

  float voltage;

};

Remote.cpp
#include "Remote.h"

Remote::Remote(void)
{
  display.initiate(this);
}

RemoteDisplay.h
class Remote;

class RemoteDisplay
{

public:

  RemoteDisplay(void);

  void initiate( Remote * _pointer );

  void showBattery( void );

private:

  /* Reference to the remote class */
  Remote * pointer;
};

RemoteDisplay.cpp
#include "RemoteDisplay.h"

void RemoteDisplay::initiate( Remote * _pointer )
{
  pointer = _pointer;
}

void RemoteDisplay::showBattery( void )
{
  Serial.println( pointer->voltage );
}

I get the errors:
error: invalid use of incomplete type 'class Remote'
showBattery( pointer->voltage() );

note: forward declaration of 'class Remote'
class Remote;

Why is it so? Any help is much appreciated.

In RemoteDisplay.cc you are using Remote in the Initiate method.
Also, since you use the voltage property, you need to include "Remote.h" within (as first line normally) in RemoteDisplay.cpp.
Also it is advised to use within every header file the following pattern (example for RemoteDisplay.h):
#ifndef REMOTE_DISPLAY_H
#define REMOTE_DISPLAY_H
...
...
#endif // REMOTE_DISPLAY_H

This prevents problems that two include header files forever include each other.

I see, thanks! It was the #inlcude "Remote.h" in the display class that did the trick. And yeah good idea with the #ifndef etc.

Good luck with your project (and great you try to keep your software organized).

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


text:
ESP8266-12F accelstepper wont boot
If I use 9, 10, 7, 6 , 8, 11 pins for accelstepper, ESP8266 wont boot
If I use other pins, all good.
What is the problem?
I use accelstepper and Arduino latest versions.
sketch which won't boot -
    #include <AccelStepper.h>
#include <MultiStepper.h>

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

const char* ssid = "wiflya";
const char* password = ".........";

#define HALFSTEP 8

// Определение пинов для управления двигателем
#define motorPin1  13 // IN1 на 1-м драйвере ULN2003
#define motorPin2  12 // IN2 на 1-м драйвере ULN2003
#define motorPin3  14 // IN3 на 1-м драйвере ULN2003
#define motorPin4  16 // IN4 на 1-м драйвере ULN2003

// Определение пинов для управления двигателем
#define motor2Pin1  6 // IN1 на 2-м драйвере ULN2003
#define motor2Pin2  3 // IN2 на 2-м драйвере ULN2003
#define motor2Pin3  5 // IN3 на 2-м драйвере ULN2003
#define motor2Pin4  4 // IN4 на 2-м драйвере ULN2003

// Инициализируемся с последовательностью выводов IN1-IN3-IN2-IN4
// для использования AccelStepper с 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
AccelStepper stepper2(HALFSTEP, motor2Pin1, motor2Pin3, motor2Pin2, motor2Pin4);

void setup() {
  //Serial.begin(115200);
  //Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    //Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  stepper1.setMaxSpeed(1300.0);
  stepper1.setAcceleration(400.0);
  stepper1.setSpeed(1300.0);

  stepper2.setMaxSpeed(1300.0);
  stepper2.setAcceleration(400.0);
  stepper2.setSpeed(1300.0);

  //stepper1.moveTo(20000);

  // Port defaults to 8266
  // ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  // ArduinoOTA.setHostname("myesp8266");

  // No authentication by default
  // ArduinoOTA.setPassword("admin");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.begin();
}

void loop() {
    // Изменяем направление, если шаговик достигает заданного положения
  //if(stepper1.distanceToGo()==0)
  //  stepper1.moveTo(-stepper1.currentPosition());
  stepper2.runSpeed();
  stepper1.runSpeed();
  //stepper2.runSpeed();

  ArduinoOTA.handle();
}

Pins 6 to 11 of the esp8266 are QIO SPI pins connected to flash memory of the esp8266. You can't use them.

Thank. I'm finding more info about this. can't use 6-11 pins, cant use gpio1 - if i'm connect to uln2003 - esp wont boot.. cant use gpio0 - wont boot if i'm connect to uln2003.   And what we have - only 3,5,4,12,13,14,16 i'm can use (with uln2003) and cant connect two bipolar motor - so very bad.

this is for NodeMcu, but it applies https://electronics.stackexchange.com/questions/402066/esp8266-free-gpios-for-relay-switching/404845#404845

or here https://tttapa.github.io/ESP8266/Chap04%20-%20Microcontroller.html


text:
Nextion Dual State Button
I am having an issue with my Nextion display. I have uploaded the following code via Arduino IDE to my Arduino MEGA 2560.
My Nextion Editor shows the button as ID:9 on page0 named floor. I am not entirely sure if the code below is correct. I had one issue where the upload from the laptop to the Mega wouldn't finish, but I managed to bypass that issue by disconnecting the Nextion and swapping RX and TX cables from Nextion while the upload was in progress. Not sure how else I would fix that issue? (If anyone has any ideas haha)
All that is meant to happen is when the dual button state is changed, the onboard LED_BUILTIN is set to HIGH and if in its second state, is set to LOW.
CODE
#include "Nextion.h"

NexDSButton bt0 = NexDSButton(0, 9, "floor");

int ledPin = LED_BUILTIN;

char buffer[100] = {0};

NexTouch *nex_listen_list[] =
{
    &bt0,
    NULL
};

void bt0PopCallback(void *ptr)
{
    uint32_t dual_state;
    NexDSButton *btn = (NexDSButton *)ptr;
    dbSerialPrintln("b0PopCallback");
    dbSerialPrint("ptr=");
    dbSerialPrintln((uint32_t)ptr);
    memset(buffer, 0, sizeof(buffer));

    if(dual_state)
    {
        digitalWrite(ledPin, HIGH);
    }
    else
    {
        digitalWrite(ledPin, LOW);
    }
}

void setup(void)
{
    nexInit();

    bt0.attachPop(bt0PopCallback, &bt0);

    dbSerialPrintln("setup done");
    pinMode(ledPin, OUTPUT);
}

void loop(void)
{
    nexLoop(nex_listen_list);
}

My issue is that the MEGA is identifying the touch event (as the TX LED on the MEGA flashes) however it is not turning on the MEGA's onboard built-in LED.
Any help would be greatly appreciated!

Did you select a hardware serial port for nexSerial? Do you see the text "setup done"? Do you see the text "b0PopCallback"? Did you enable the event in the nextion editor? Please update your initial question with more information.

I have done no coding in the Nextion editor as I thought Arduino IDE handles all the coding. How would I go about enabling the event in Nextion?

I will admit that I did load this code from a sample sketch provided by Nextion, however I ONLY used the code and never looked into the .HMI file. I might browse over that and try and understand what you mean by enabling the event in Nextion :)

In the callback, where does it assign a value to dual_state?

This is part of the code I have been using for an extraction fan, The button text is tested and if the button matches the command the fan is turned on or off and the button text is changed accordingly. Hope this helps.
void b19PopCallback(void *ptr) //Extraction Fan
{
  NexButton *btn = (NexButton *)ptr;
  memset(buffer, 0, sizeof(buffer));
  btn->getText(buffer, sizeof(buffer));

  if (strcmp(buffer, "ON"))
  {
    //COMES BACK AS A FALSE (0) IF BOTH STRINGS MATCH
    digitalWrite(b_motor, LOW);
    strcpy(buffer, "ON");
    btn->setText(buffer);
  }

  else
  {
    digitalWrite(b_motor, HIGH);
    strcpy(buffer, "OFF");
    btn->setText(buffer);
  }

}

strcmp doesn't return true or false so your comment about it returning FALSE if both strings match is a bit misleading. See strcmp - strcmp is designed to return a number < 0 if string1 is less than string2, 0 if they are the same, and > 0 if string1 is greater than string2 (in the collating sequence).

Regardless of the failure in describing the return type of strcmp, I believe that is indeed what the OP is missing.  The code in OP never checks the string and assign any value to dual_state.

You can try int ledPin=13 instead of led_builtin . Led builtin connected 13 pin. Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO it is attached to digital pin 13 .  Try  this one.
#include "Nextion.h"
int ledPin = 13;
NexDSButton bt0 = NexDSButton(0, 1, "bt0");
uint32_t dual_state=0;

void setup(){
nexInit();
pinMode(ledPin, OUTPUT);
}
void loop(){
bt0.getValue(&dual_state);
delay(200);

if(dual_state==1) //When pressed dual state button dual_state =1
  {
    digitalWrite(ledPin, HIGH);
  }
  else if(dual_state==0)
  {
    digitalWrite(ledPin,LOW );
  }

}


text:
How to use different device address for MCP23017 so I can use multiple chips?
I want to use more than 3 MCP23017-E/SP DIP28 chips so I can use many digital pins. I use Adafruit-MCP23017-Arduino-Library. I tried this solution but only device address with 0x00 is working.
The question is what device address should I use for additional chip?

#include "Adafruit_MCP23017.h"
Adafruit_MCP23017 mcp1;
#define addr1 0 // tested 1,2,3,4,5, 0x01, 0x02, 0x20, 0x21 but only 0 and 0x00 is working.
void setup()
  {
    mcp1.begin(addr1);
    mcp1.pinMode(0, INPUT); //pin 21 on chip
    Serial.begin(9600);
  }

  void loop()
  {
      if(mcp1.digitalRead(0)== HIGH )
      Serial.println("HIGH");
  }

I share my solution with 7 MCP23017 chip , 7x14 pins=98 pins using adafruit library.
Connections:
addr 0 = A2 low , A1 low , A0 low  000
addr 1 = A2 low , A1 low , A0 high 001
addr 2 = A2 low , A1 high , A0 low  010
addr 3 = A2 low , A1 high , A0 high  011
addr 4 = A2 high , A1 low , A0 low  100
addr 5 = A2 high , A1 low , A0 high  101
addr 6 = A2 high , A1 high , A0 low  110
addr 7 = A2 high, A1 high, A0 high 111

Connect pin #12 of the expander to Analog 5 (i2c clock)
Connect pin #13 of the expander to Analog 4 (i2c data)
Connect pins #15, 16 and 17 of the expander to ground (address selection)
Connect pin #9 of the expander to 5V (power) // operation voltage is 1.8 to 5.5
Connect pin #10 of the expander to ground (common ground)
Connect pin #18 through a ~10kohm resistor to 5V (reset pin, active low)

Input #0 is on pin 21 so connect a button or switch from there to ground

Code:
#include <Adafruit_MCP23017.h>

Adafruit_MCP23017 mcp1; // chip 1
Adafruit_MCP23017 mcp2; // chip 2

#define addr1 7 // 7 = A2 high, A1 high, A0 high
#define addr2 0 // 0 = A2 high, A1 high, A0 high
void setup()
  {
    Serial.begin(9600);
    mcp1.begin(addr1);
    mcp2.begin(addr2);

    mcp1.pinMode(0, INPUT); //pin 21 on chip
    mcp2.pinMode(0, INPUT); //pin 21 on chip

  }

  void loop()
  {
      if(mcp1.digitalRead(0)== HIGH )
      Serial.println("HIGH");
      delay(1000);

      if(mcp2.digitalRead(0)== HIGH )
      Serial.println("HIGH 2");
      delay(1000);
  }


text:
Connect USB cable to GPIO pins on an Arduino Uno
Electronics Newbie!!
I want to connect a USB cable to my Uno's GPIO pins (and then connect it to a USB port on my computer). I have chopped off a USB cable from a keyboard, I read this and I'm hoping that the wires will be in the correct order (the keyboard was made by Dell). I'm a little confused about which wires go where.

What are you trying to achieve? The link is about power on a USB cable.

What is the purpose of doing that? Using 5v signals on the USB data lines isn't allowed in the USB-specification. You at least need to use a multi-meter to measure which wire, is connected to which pin on the USB socket, as the color-coding isn't always the same.

Take some help from attiny designs with USB; http://electronics.stackexchange.com/questions/84663/firmware-circuit-of-attiny45-direct-usb-2-0-connection

The reason you are confused about which wires go where is simply because the Uno has no connection on it for a USB cable's wires.
You cannot directly interface an Uno to a USB port without extra hardware.  What hardware you require depends on exactly what it is you think you are trying to achieve.
(There have been some attempts to create a USB device interface purely in software, but personally I wouldn't touch it with a barge pole - the GPIO of the Arduino is not electrically compatible with USB.)


text:
Convert Bitstring to Textstring
I have an Arduino Uno which is going to receive a long binary string.  I know that this string will correspond to English when decoded.  How can I convert the incoming binary string to text, so that I can read it in the Serial Monitor?
Bonus Points: This string will almost definitely have random noise digits.  How would I noise-proof the string, or how could I have the code detect and ignore noise?
UPDATE: It might help if I mention my end goal.  So I have this contained clean space that is locked up to avoid contamination.  It is quite small, and used for growing silicon crystals.  I want to be able to take a greyscale image every hour, and transmit it to a receiver on the other end of the room, through a window.  The window is two half inch panes of glass with an inch of space between them.  I have on hand 2x Arduino Uno, 1x Arduino Beetle, and 1x Raspberry Pi.  The whole text string thing is just for testing purposes so that I can understand what I'm doing.  From what I've read on the subject previously, I need to take the image, convert it to Hex, convert that to binary, transmit it, receive it, convert back to Hex, convert back to an image.  I have 0 experience with Arduino or Raspberry, have a limited idea of how to execute this, and appreciate all the help I can get!

Can you define 'binary string'? And can you explain 'read it in the serial monitor'? You want to receive it by RX or print it to the serial monitor? Or receive it by typing it in the serial monitor? You can noise-proof it by adding CRC data.

So, I'm using the transmitter and receiver pair from here.  The transmitter is transmitting the string corresponding to "Hello World", where the string is generated by converting each ASCII character into its 8-bit binary string.  The string received by the receiver ought to be one long line of binary generated by the conversion code, but with noise.  What I mean by "read into serial monitor" is that I want to decode it from binary back into "Hello World", and print it out to the serial monitor so that I can verify it worked.

Can you run a wire out of the clean space?  Eg, put camera inside, and wire to RPI outside?   ¶ If electronics are inside sealed space, is it at atmospheric pressure and room temperature?  Ordinary Arduino and RPI boards will outgas below atm.   ¶  Might also look into power line modulation to piggyback signals out of sealed space. ¶ If you have to use RF, put receiver a few inches from the transmitter and use wire to get the rest of the way across the room.   ¶ Can you transmit light through the glass?  Eg, put an LED on system inside space, and a phototransistor just outside, etc.

I cannot run a wire out.  We want to have complete containment, and not fiddle with making a hole in the setup, feeding a wire, and sealing the hole.  It will be standard Earth atmosphere and ranging from room temp to a really hot day (~95-100 F).  Due to equipment and room setup, the closest the receiver can be is 30'8".  Light cannot propagate through the glass.  I do like where your head is with using the LED as an Aldis lamp, but that won't work, because all receiver stuff needs to be at least 30'8" away from the containment unit, and that signal could easily be interrupted at such a range

Perhaps you have asked the wrong question. Because there is a library for those cheap 433MHz modules: RadioHead.
Use the RH_ASK mode, and try the 'ask' examples
You might see VirtualWire used a lot with those 433MHz modules. That is the same as RadioHead. The RadioHead is newer and has a few bugs fixed, but it uses also more memory.
The RadioHead library uses a far more superior protocol than anything else, that makes the range better than with other libraries. It also has a (simple) CRC checksum in the protocol. That means that when you receive something, you can be (almost 100%) sure that the data is correct.
Other protocols require that a message is transmitted 10 times, to be sure that it will be received. With the RadioHead library, sending a message just once is good enough.
Those cheap 433MHz modules have a disadvantage: they can only be turned on and off (ASK modulation) en you need a library for the protocol. That means that if the Arduino is doing more things that uses interrupts or code that disables interrupts, then the protocol is disturbed and it will not work very well.
The RF transceiver modules have a chip on the module itself that takes care of the protocol, that is so much better. Sparkfun has a Wireless Buying Guide and Adafruit uses the RFM69 a lot.
Those cheap modules require an antenna, or else the range could be less than the size of the table they are on. Solder a 16cm piece of wire to the antenna pin. Any piece of wire of any length is better than no antenna.

So, I'm actually using VirtualWire already.  I looked into using RadioHead, but I don't think that my project will allow me to have enough memory to use it.  My primary concern is space, because my final physical build needs to fit a theoretical space of 25mm X 25mm X 30mm.  I don't think I'd have room for an antenna, so I should look into a different transmitter.  I'm still not sure how to write a program to convert the incoming binary string to text (or in my case, Hexadecimal, then an image).

With VirtualWire or RadioHead you will receive the same bytes as what you have sent. There is no need to convert something. The typical data transfer rate for those cheap 433MHz modules is about 10 to 100 bytes per second. It is not for transmitting an image.

Oh, I thought they could do images.  Do you have any ideas on what would be the best method for transmitting an image at range?

A string is also a 8-bit 'binary' string ... so I don't think you need to do anything special... if you can read byte by byte, you might have to construct a string adding the characters, or print it directly to the serial monitor (last is even better because you don't have to think about memory).
If the 8-bit binary string does not contain ASCII data (which I doubt), print out the byte values as number and see how it should be converted to a textual character.
Noise is a bit more tricky .. afaik it is possible with some libraries (for the RF) to automatically resend. If that is not good enough, you have to make your own CRC ... calculate a CRC, send it (maybe a few times to be sure there is no noise in the CRC) and check it against the received string; if not received correctly, send it again.
If you have only 1 directional transmitting, than it is more tricky. You can add extra bits to 'fix' noise, or using special schemes for it.
See for more info wikipedia

So, would I just tell it to constantly receive data, and every eighth digit attempt to convert the 8-bit string to a char?

You will get bytes, not bits, and one byte is one character ... so the data you sent with the Wire library (or another) will be the same that you receive on the other end, assuming the connection quality is good enough.

you're welcome (please upvote if the answer helped you)

I did, but I'm <15 rep, so it doesn't show

No problem, you always can do it for all your answers you received when your reputation rises :-)


text:
Not able to read the product ID from ADIS16260 Gyroscope Sensor
I have interfaced a ADIS1620 sensor to the Arduino UNO using SPI.I am having a bit of trouble here to read the product ID information from the ADIS1620.According to the datasheet here,
on page 11, it is said that to perform a read operation, 2 16bit transactions are to be done with a minimum stall time of 9 us. The first 16 bit consists of the register address to read from i.e. 0x5600 and the second transaction is to read the product ID information. However, I always get the read data as '0' or as '0xFFFF'.I have done the hardware interfacing as per the connections mentioned below:
/* SPI Connections as per pg No.10 in
   the Datasheet (Note: Not using IRQ)
 */

 ADIS1620                 UNO
  (DIN)3                11 - MOSI
  (DOUT)2               12 - MISO
  (SCLK)1               13 - SCK
  (SS)4                 10 - CS
  16                    5V
  18                    GND

Below is .h file,
#ifndef ADIS16260_H
#define ADIS16260_H

/* Register Addresses */
#define LOT_ID1_ADDR          0x5200
#define LOT_ID2_ADDR          0x5400
#define PROD_ID_ADDR          0x5600
#define SERIAL_NUM_ADDR       0x5800

/* Timings */
#define STALL_TIME_US         10

#endif /* ADIS16260_H */

I doubt the problem is to do anything with the code as such, but still, just in case, here is the .ino file,
/* Lib's Include */
#include <SPI.h>

/* Custom Lib's Include */
#include "adis16260.h"

/* MACRO's */
#define CS  10

/* Globals */
char incomingByte;
unsigned int prod_info_data;

/* Definitions */
typedef enum
{
  LOT_ID1,
  LOT_ID2,
  PROD_ID,
  SERIAL_NUM
} Prod_InfoT;

/* Function Prototypes */
void SPI_Init();
unsigned int Get_Product_Info(Prod_InfoT get_adis16260_info);

void setup()
{
  Serial.begin(115200);
  SPI_Init();
  Serial.println("SPI Initialized");

}

void loop()
{
  if (Serial.available() > 0)
  {
    // read the incoming byte:
    incomingByte = Serial.read();
    if (incomingByte == 'a')
    {
      prod_info_data = Get_Product_Info(PROD_ID);
      Serial.println(prod_info_data, HEX);
    }
  }
}

/********************************************************************************
   Function Name    : SPI_Init
   Description      : Initialize the SPI module in the MCU
   Returns          : None
 * *****************************************************************************/
void SPI_Init()
{
  /* configure the line as output */
  pinMode(CS, OUTPUT);

  /* Initialize the CS line to HIGH */
  digitalWrite(CS, HIGH);

  /* Initialize the SPI module--> configures the MOSI, MISO and CLOCK lines */
  SPI.begin();

  /*
    Configure the SPI bus as follows
      1. SPI bus speed  = 1 MHz
      2. Data Out     = From MSB bit ---> To LSB bit
      3. Data Mode    = SPI MODE3
  */
  SPI.beginTransaction(SPISettings(100000, MSBFIRST, SPI_MODE3));
}

/********************************************************************************
   Function Name    : Get_Product_Info
   Description      : Get Prod ID, Lot ID1, Lot ID2 and Serial Num.
   Returns          : None
 * *****************************************************************************/
unsigned int Get_Product_Info(Prod_InfoT get_adis16260_info)
{
  unsigned int get_data = 0;

  switch (get_adis16260_info)
  {
    case PROD_ID:
      Serial.println("Reading Product ID...");
      digitalWrite(CS, LOW);
      SPI.transfer16(PROD_ID_ADDR);
      digitalWrite(CS, HIGH);
      delayMicroseconds(STALL_TIME_US);
      digitalWrite(CS, LOW);
      get_data = SPI.transfer16(0x00);
      digitalWrite(CS, HIGH);
      break;

    case SERIAL_NUM:
      Serial.println("Reading Serial Number...");
      digitalWrite(CS, LOW);
      SPI.transfer16(SERIAL_NUM_ADDR);
      digitalWrite(CS, HIGH);
      delayMicroseconds(STALL_TIME_US);
      digitalWrite(CS, LOW);
      get_data = SPI.transfer16(0x00);
      digitalWrite(CS, HIGH);
      break;

    default:
      Serial.println("Invalid Arguement");
      break;
  }
  return (get_data);
}

Edit: Added screen shot of the SPI lines:

Any support with this would be helpful. Thanks.

Does you code return the serial number?

@Code Gorilla, I have tried reading the serial number as well, the same issue happens i.e. Reads 0 or 0xFFFF.

Good, that means its not a fault with the device.  Should the first param of SPISettings be 1 million or 100,000?   I've never used SPI, but doesn't the SPI object handle the CS pin?

@CodeGorilla, the SPI bus speed is set to 100 KHz i.e. 100000. No, the chip select line needs to be handled manually.

Reading all 0xFFFF suggests the gryo is not driving MISO, either as it is not operational or has not received a valid read command or been selected.  You need to show the wiring of your gyro chip.  Who soldered the QFN?  QFN's are notorious for having metalizations look connected when they actually are not.  For your software, do you have another SPI peripheral you can run a quick test against?  Investing in a scope or even a cheap USB fifo based logic analyzer will be very useful for investigating this type of problem.

@ChrisStratton, while reading,  most of the time I receive '0' and sometimes in between I receive '0xFFFF'(So it means that the gyro is responding with a 0x00? and sometimes 0xFFFF due to some connection issues??), need to check this. The QFN was soldered by a hardware engineer. I have a USB logic analyzer, I will prob the signals and check if the SPI lines are working fine.

Sounds like you need to get that hardware engineer involved.  Both bus traffic analysis, and inspecting the QFN fillets under high magnification from an angle would be appropriate (I usually raise the microscope so I can hold the board in my hand and tilt it to the best angle)

@ChrisStratton, unfortunately the hardware engineer had left 2 months ago. Between, I guess the SPI signals look good, what do you think? (have attached the image). Before concluding for a hardware check to my boss, I want to make sure that there's nothing wrong being done on the firmware side. And, do I need to do a full fledge timing analysis w.r.t the timing requirements that needs to be met for the ADIS16260?

Try putting a pullup resistor on MISO so you can see if it is undriven or stuck.  Check the data sheet for the gyro - many chips will clock out some sort of status word even from the first byte of SPI access.  If you can find any other SPI peripheral, it may be worth experimenting with that and trying to adapt your software to it, as in so doing you may realize some oversight.  Finally there are other gyros out there pre-soldered on modules with Arduino libraries already in existence - if you get really stuck maybe you can use one of those, at least until you get a hardware engineer.

@ChrisStratton, just to get it right, you mean to say that I need to test the Arduino UNO's SPI interface with another device that uses SPI interface? or a different MCU itself  SPI to communicate with the Gyro?

I was proposing you use another SPI peripheral to gain some hands-on experience and validate (an adapted version of) your SPI code.  But trying another MCU with the gyro could be an option too, if you have something that is a substantially different implementation.


text:
SPI slave ISR not being called randomly
So I am trying to have a full-duplex high-speed(I'll be reducing the delay to microseconds once the below problem is solved) comm. between two Arduino Unos. Here is the code below:
Master:
volatile uint8_t rdata;

#define SCK   13  // D13 = pin19 = PortB.5
#define MISO  12  // D12 = pin18 = PortB.4
#define MOSI  11  // D11 = pin17 = PortB.3
#define SS    10  // D10 = pin16 = PortB.2

void SPI_MasterInit(void)
{
  /* Set MOSI and SCK output, all others input */
  //DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
  pinMode(MOSI, OUTPUT);
  pinMode(MISO, INPUT);
  pinMode(SCK, OUTPUT);
  pinMode(SS, OUTPUT);
  /* Enable SPI, Master, set clock rate fck/4 */
  SPCR = (1 << SPE) | (1 << MSTR) | (0 << SPI2X) | (0 << SPR1) | (0 << SPR0) ;
  SPCR |= _BV(CPOL);
  //SPCR |= _BV(CPHA);

}

void SPI_MasterTransmit(uint8_t data) {
  PORTB &= ~(1<<2);
  SPDR = data;
  //asm volatile("nop");
  while (!(SPSR & (1 << SPIF)));
  rdata = SPDR;
  PORTB |= 1 << 2;
  Serial.print("data "); Serial.print(data); Serial.print(" rdata "); Serial.println (rdata);

}

void setup (void)
{
  Serial.begin(115200);
  PORTB |= 1 << 2; //digitalWrite(SS, HIGH);
  SPI_MasterInit();
}

void loop (void)
{

  for (byte i = 0; i < 10; i++) {

    SPI_MasterTransmit(i);

    //Serial.print(m);
    delay(100);

  }
}

Slave:
volatile boolean process_it;
volatile byte indx = 129, c = 0;

#define SCK   13  // D13 = pin19 = PortB.5
#define MISO 12  // D12 = pin18 = PortB.4
#define MOSI 11  // D11 = pin17 = PortB.3
#define SS    10  // D10 = pin16 = PortB.2

void SPI_SlaveInit(void)
{
  /* Set MISO output, all others input */
  //DDR_SPI = (1<<DD_MISO);
  pinMode(MOSI, INPUT);
  pinMode(MISO, OUTPUT);
  pinMode(SCK, INPUT);
  pinMode(SS, INPUT);
  /* Enable SPI */
  SPCR |= _BV(SPE); // SPI Enable, sets this Arduino to Slave
  SPCR |= _BV(SPIE); // SPI interrupt enabled
  SPCR |= _BV(CPOL);
  //SPCR |= _BV(CPHA);
}

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

  SPI_SlaveInit();

}

// SPI interrupt routine
ISR (SPI_STC_vect)
{

  SPDR = indx;
  indx--;
  if (indx < 121)
    indx = 129;
  c = SPDR;
  process_it = true;

}

void loop (void)
{
  if (process_it) {

    Serial.println (c);

    process_it = false;

  }

}

Below output shows the o/p of the master on the left and slave one the right:

The master prints the data it has sent(to the slave, "data" variable) followed by the data it has received (from the slave, "rdata" variable). The slave simply prints the received data (from the master).
If you look carefully at the pic you would see that the master sometimes gets the same data (in the next cycle)  it has sent (in the current cycle) (0 and 4 in the pic). At the same time, the slave fails to receive exactly that data (0,4). Also, you can the value of 'indx' is not decremented and the master receives the decremented value in the next cycle. These two things prove that the Slave ISR is not being called randomly (hence the data in the SPDR is not read which is then echoed back to the master plus the index variable is not decremented). Is there a solution to this? I would be really grateful if someone could help me with this.
Edit: I face the exact same problem with the default arduino SPI library, here is the code:
Master:
#include <SPI.h>
volatile byte m=0;
void setup (void)
{
    pinMode(MOSI, OUTPUT);
    pinMode(MISO, INPUT);
    pinMode(SCK, OUTPUT);
    pinMode(SS, OUTPUT);

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

  digitalWrite(SS, HIGH);

  SPI.begin ();

  SPI.setClockDivider(SPI_CLOCK_DIV4);
}

void loop (void)
{
for(byte i=0; i<10; i++){
  digitalWrite(SS, LOW);
  m = SPI.transfer (i);
  digitalWrite(SS, HIGH);
      Serial.print("data "); Serial.print(i); Serial.print(" rdata "); Serial.println (m);
  delay(100);
}
}

Slave:
#include<SPI.h>

volatile byte c = 0, indx =129;
volatile boolean process_it = false;
void setup (void)
{
  pinMode(MOSI, INPUT);
  pinMode(SCK, INPUT);
  pinMode(SS, INPUT);

  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);
  Serial.begin (115200);

 SPI.attachInterrupt();

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{

      SPDR = indx;
      indx--;
      if (indx < 121)
        indx = 129;
      c = SPDR;
      process_it = true;

}  // end of interrupt service routine (ISR) SPI_STC_vect

 void loop (void)
    {
      if (process_it) {

        Serial.println (c);

        process_it = false;

      }

    }

Why not use the SPI library that does all this for you and has examples that are known to work?

@Majenko Two reasons, I have observed the exact same problem with the SPI library and I need a C implementation instead of C++;

Can I suggest, then, for our benefit, that you show us the SPI library based variant (since it's easier for us to follow)? If the two show the same problem it's not your code as such, it's your methodology that is flawed.  Also showing what you expect the outputs to show would help.

@Majenko I have added the SPI equivalent code. The thing is since the SPI interrupt is not getting called sometimes, you can see that the slave is missing data byte from the master (the master is receiving its own data after a cycle since the slave is not clearing/writing the SPDR register). I would like the slave to receive all the data that is being transmitted by the master and vice versa. I wouldn't want the master to receive its own data.

The part where you write indx to SPDR before reading SPDR and put in c, looks odd to me. It probably works because it's internally buffered, but it looks very wrong to me. I can't see anything in the datasheet that suggests this would work. I'd try putting c=SPDR before SPDR=indx

@Gerben I have tried that as well. It doesn't change the situation at all. I am still missing ISR calls at random on the slave side.

I'm stumped. Try using a different Arduino board. Or swapping them.


text:
How to automatically reset the nrf24l01+ with code?
I have two separate nrf24l01+ connected to two different Arduino UNOs, one as TX and the other as RX. The problem is the connection stops after a while between them.
On the Arduino COM screen I have noticed these things:
TX Side: Completely Frozen (Transmission Stops).
RX Side: Continuously receives the last data repeatedly.
The problem is solved temporarily when the TX MCU (hence the nrf) is restarted .Sometimes even after restarting the TX MCU the RX stops responding and I have to restart the RX as well. Therefore I am trying to find a way to reset my nrfs automatically using software when this situation occurs.

What is connected on pin9 and pin10 ?

I found the problem occurs because the transmitter is expecting acknowledgment from the receiver which is getting lost somehow, while transmission and the transmitter still waits for ack for the last transmitted data (which it never gets) so it keeps on transmitting the last packet again and again. I saw on forums that its because of the TX buffer getting full after 3 retries or something. I don't exactly know why it happens.
I first tried resetting just the transmitter through code but it was not enough (as already mentioned in the question). So I now reset both the TX and RX using the below code. I have a separate 1 byte reset-counter in the first byte of the array (you may use a single byte variable) which acts as an id for the packet (you may use the internal PID as well).
The below code resets  the TX if transmission fails by checking the return value of write function and resets the RX when it receives the same ack or packet (with the same reset-counter value) more than 2 times (I use a condition to check if the last counter value is different from the current one or not). To reset it using code I use the below algorithm :

Power Down the NRF using powerDown() function.
Re-initialize the nrf for the MCU.
Power Up the NRF using powerUp() function.

Note: I am using TMRH20 RF24 Library.
TX Code
void radio1_init()
{
  pinMode(9, OUTPUT);
  digitalWrite(9, HIGH);
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  myRadio1.begin();
  delay(100);
  myRadio1.setChannel(96);
  myRadio1.setPALevel(POWERLEVEL);
  myRadio1.setDataRate(DATARATE);
  myRadio1.setAutoAck(1);
  myRadio1.enableAckPayload();
  myRadio1.enableDynamicPayloads();
  myRadio1.setRetries(2, 10);
  myRadio1.setCRCLength(RF24_CRC_8);
  myRadio1.openWritingPipe( addresses1[0]);
}

void loop()
{
  dataTransmitted[0]++;
  if ( myRadio1.write( &dataTransmitted, sizeof(dataTransmitted)))
  {

    if (myRadio1.isAckPayloadAvailable())
    {
      myRadio1.read(&ack, sizeof(ack));
    }
  }
  else
  {
    myRadio1.powerDown();
    \\Serial.println(" 1 Tx1 problem end");
    radio1_init();
    myRadio1.powerUp();
  }
}

RX Code
void radio2_init()
{
  pinMode(9, OUTPUT);
  digitalWrite(9, HIGH);
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  myRadio2.begin();
  delay(100);
  myRadio2.setChannel(96);
  myRadio2.setPALevel(POWERLEVEL);
  myRadio2.setDataRate(DATARATE);
  myRadio2.setAutoAck(1);
  myRadio2.enableAckPayload();
  myRadio2.enableDynamicPayloads();
  myRadio2.setRetries(10, 10);
  myRadio2.setCRCLength(RF24_CRC_8);
  myRadio2.openReadingPipe(1, addresses2[0]);
  myRadio2.startListening();
}

void loop()
{
      if (myRadio2.available())
      {
        myRadio2.read( &dataReceived, sizeof(dataReceived));
        myRadio2.writeAckPayload(1, &ack2, sizeof(ack2));
        if (prevack2 == dataReceived[0])
        {
          \\Serial.println("RX 2 problem");
          c2++;
        }
        prevack2 = dataReceived[0];
        if (c2 > 2)
        {
          myRadio2.powerDown();
          radio2_init();
          myRadio2.powerUp();
          c2 = 0;
        }
      }
}

If you use standard arduino pin cables, then they do not provide stable connectivity for NRF24L01+. Try to solder pins instead (not kidding).
Another reason could be that one of your modules has bad power supply. Power it with perfect 3.3 volts (from another power source, not from Arduino), or use "base module" for the NRF24L01+ (connect this "base module" to 5V pin on Arduino)
http://www.yourduino.com/sunshop/index.php?l=product_detail&p=467

If the NRF24L01 truly locks up, as can happen with an inadequate power supply, then the powerDown(), init(), powerUp() method wont work as the NRF wont receive SPI commands.
In this situation, which seems to be the most common form of lockup, a physical power cycle is the only option.


text:
ESP8266: #include <Keyboard.h> causes fatal error: HID.h: No such file or directory
OS: Mac
Arduino: 1.8.13
Keyboard Library: 1.0.2

I have a generic ESP8266 board, and I have the following code
void setup() {
  // put your setup code here, to run once:
  pinMode(LED_BUILTIN, OUTPUT);
  Keyboard.begin();
}

void loop() {}

However I get the following ouput:

In file included from /Users/quba/Sandbox/sketch_feb07a/sketch_feb07a.ino:1:0:
/Applications/Arduino.app/Contents/Java/libraries/Keyboard/src/Keyboard.h:25:17: fatal error: HID.h: No such file or directory
#include "HID.h"
                          ^
compilation terminated.
exit status 1
Error compiling for board Generic ESP8266 Module.
Could not find boards.txt in /Users/quba/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.7. Is it pre-1.5?

The Keyboard library is for Arduino ATMega32U4 based Arduinos (and other similar ones with USB) only. The ESP8266 does not have USB, so how can it possibly use the Keyboard library?

I have added a picture so you can see the TX and RX pins, as well as the USB

The keyboard library is meant for devices that can talk DIRECTLY to the USB bus, like the AVR ATMega32u4. The ESP8266 on the NodeMCU you show in your picture does not have that capability but it has a separate Serial-to-USB chip that's able to talk to a PC via USB. Even then, it can only act as a peripheral to a PC and not as a USB "Master" that's able to control its own USB peripherals (like a keyboard).


text:
Assembled redboard PTH kit, when I turn it on the led flashes increasingly fast and stops
I assembled the following sparkfun redboard: https://www.sparkfun.com/products/retired/10776
When I plug the board in it start to blink but increasingly fast until the LED stops.
I'm very new to this and not sure what could be the issue or what to look. Any tips on how to debut this?
Here are images of the assembled board:

Adding a Picture of your board that you put together would be useful for others to see if there is a problem. Also compare yours to the sparkfuns one.

Just added images of the assembled board

The board seems to be working. After I plugged in an ftdi connector (adafruit FTDI friend) and uploaded blink to it, it started blinking every second instead of really fast.
The documentation was a bit confusing as it implied that blink was pre-loaded on the device but instead it would just blink extremely fast until it went all the way on and then turn off the green led.


text:
How can I simulate an accelerometer?
I am new to Arduino. I want to simulate a circuit which uses an accelerometer ADXL335 and a DC motor. If any deviation observed in the accelerometer readings, I want the motor to rotate. Is there any way I can simulate its working in software without implementing it?

Your sensor supplies an analog signal, ranging from 0V for -3g to 3.3V for +3g.
This means you have a signal averaging at "338" when read using Arduino's analogRead() function, with spikes in either direction when acceleration changes.
You would want some code which gives you a variable hovering around "338", with random acceleration spikes injected in either direction. This could look something like this:
int16_t num_zerog = (3.3 / 5) * 512;
int16_t num_xaxis = num_zerog;
uint8_t num_random = 0;

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

void loop() {
  // put your main code here, to run repeatedly:
  num_random = random(256);
  if (num_random == 255) {
    num_xaxis += 200;
  }
  else if (num_random == 0) {
    num_xaxis -= 200;
  }
  else if (num_random < 100) {
    num_xaxis += 1;
  }
  else if (num_random > 155) {
    num_xaxis += 1;
  }
  else {
    num_xaxis += (num_zerog - num_xaxis) / 4;
  }
  if(num_xaxis < 0 || num_xaxis > 675) {
    num_xaxis = num_zerog;
  }
  Serial.println(num_xaxis);
  delay(10);
}

Explanation: First, the value for 0g is determined from the voltage difference.
A random value is generated, ranging from 0 to 255.
If the random value is 0, a negative value is added to your "signal". If it's 255, a positive spike is added.
If any other value is obtained, it goes back to it's 0g level with 1/4th of the difference between the current value and the 0g value per loop.
The serial commands only serve to let you watch the result in Arduino IDE's serial plotter.
If you need the spike to occur less frequently, adjust the delay(), or let the counter run to higher numbers.
If the CPU-blocking delay() command is an issue in your project, you could run the randomization code using a timer and an interrupt.
Please note that real acceleration sensors exhibit a lot more noise than this. This could be implemented by adding smaller spikes at a broader range of random values (like -1 if num_random is below 100 and +1 if it is above 155).

An input voltage of 1.65 V (half of 3.3 V) should give you a reading of (1.65 V ÷ 5 V) × 1024 ≈ 338.

You're right of course, I forgot that analogRead() defaults to 10 bit. Thank you, post corrected.


text:
HTTP get request using Arduino Uno and ESP8266
I have an Arduino Uno and an ESP8266 and I want to send a HTTP get request to google.com and print the response.
Please help me thanks.

if you have AT firmware in esp8266, use AT commands or WiFiEsp library. the library has examples. for AT commands you can google may examples.

You can use ESP8266Wifi Arduino Library.
Here an example:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void setup () {

  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);
    Serial.print("Connecting..");

  }

}

void loop() {

  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

    HTTPClient http;  //Declare an object of class HTTPClient

    http.begin("http://www.google.com");  //Specify request destination
    int httpCode = http.GET();     //Send the request

    if (httpCode > 0) { //Check the returning code

      String payload = http.getString();   //Get the request response payload
      Serial.println(payload);                     //Print the response payload

    }

    http.end();   //Close connection

  }

  delay(30000);    //Send a request every 30 seconds

}

but this is for coding directly on esp8266 I want to upload the code to arduino uno

Ok, do you want to use AT commands? See this post: https://arduino.stackexchange.com/questions/32567/get-data-from-website-with-esp8266-using-at-commands


text:
Using an OV7670, Arduino Uno, ESP8266 and SD card
I am planning to create a project which will take a picture with OV7670 and Arduino Uno with SD card and send it to server with ESP8266.
is it possible to use Arduino Uno(it has only 2k RAM memory)?

you now you can buy an IP camera?

I think if you want to save and deploy more than just simple still images in rather big time distances you won't get lucky with the Uno. All the data would have to go through the Uno, which is not a trivial task. Though it may be possible, you should consider using a more capable board.

And why do you want to use the Uno? The ESP is way more powerful (it's not just the wifi functionality)


text:
How to program an Arduino pro mini using native serial port (on my mainboard)
How can I program my Pro Mini using the native RS232 Serial port on my Mainboard (aka com1).
Google-ing did not really help and a quick search here for "pro mini programming com1" did not deliver any results.
I already have a MAX232 module connected between the Pro Mini and the PC.
I have already tested the com1 port for function by sending stuff to an Arduino mega via its usb-to-serial port and echo-ing that to com1.
Which succeeded (at least sort-of [receiving some random clutter in between characters or missing some characters at all])
I did try the obvious (i.e. selecting pro mini from the board menu and then selecting the com1 port and hit upload).
But that did just produce a timeout-error…
An Option to set the programmer to simple Serial Connection or something similar does not exist to my knowledge (well it does but only if we're talking about STM32 based boards like the blue pill).

please break the word "clump" into separate sentences

you must reset the board in the moment of Upload. the USB chip on Uno or Mega does the reset

Or connect the DTR signal (conditioned by the MAX232) through a 100nF capacitor to the RESET pin.

@Majenko the module does not offer dtr to the outside world and does not even offer the second channel of the ic …

Then you will have to do a manual reset at just the right moment. Good luck.

or can one define a custom upload method like its done with the stm32 based boards...

alternative is ISP flashing over the ICSP header with a programmer or other board as programmer.

To upload a hex file to Arduino over Serial interface, the bootloader must be active. The bootloader is active after reset. It waits a short time if a new application is uploaded. If not, it jumps to existing application.
To reset the MCU on Arduino boards with independent USB chip a circuit connected to DTR line of serial is used.
On a board like the Pro Mini there is no chip for USB neither an auto reset circuit. You must reset the board with the reset button right before avrdude sends the hex file. avrdude tries ten times, so you have 10 chances to time it right after you hit the Upload button.
Some USB-to-TTL-Serial adapters (or RS232 adapters) have the DTR line and it can be used to reset the board.
Or use ISP flashing over the ICSP header with a programmer or other board as programmer.

my module does not offer that line. damn that the ide does not print when avrdude does its attemps to make an estimation on when to press the button. i guess i simply asked for something that sounded great in theory and just not works in practise due to some minor detail...

just found that it does print w/ some flag set in the preferences

do not think i do get the Timing Right but it helps in the manner that i know i just wanted the impossible... gonna close this thread

Open the IDE, select File:Preferences and turn on Verbose Outputs.
Press & Hold Reset on the Promini.
Start the download. At the end of compilation you will see something like

Sketch uses 960 bytes (2%) of program storage space. Maximum is 32256 bytes.

Then the IDE will try and download 3 times.
Release Reset when you see the line above - it may take a few tries to get the release timing correct.


text:
How do I get more than 64 characters of message from serial
I am trying to make a moving message board using an Arduino Uno, HC-05 Bluetooth module and DMD board.
Sending message to the DMD through the Bluetooth module can only give a not more than 62 character message.
I need help in what to do to get up to 200 or more. Thanks.

You need to read the serial data before the buffer fills up. Do not use the serial's buffer in place of your own.

What about reading the serial buffer into a ring buffer larger that 64 bytes?

I got to access the HardwareSerial through program files> arduino, till i got to it, but find it hard to implement a change, am a newbie in this stuff.

The point is, that you don't really have a good reason to modify the HardwareSerial library. You are a beginner, so start with using the library correctly by constantly reading the bytes from the internal buffer to your own big buffer in your code. You do not need to modify the library for this

First: There is no such concept of a message on the Serial bus, unless you implement it yourself. On hardware level only individual bytes are transmitted, and you don't even know, when each byte will be transmitted exactly. Since there are only individual bytes in the first place, there is no limitation on how many bytes can be transmitted.
Yes, the Serial library has a limited buffer of 64 bytes, but as Majenko wrote it is not intended for buffering all bytes for one of your messages. It should only buffer the bytes, until the main sketch can read them from the buffer. On reading the bytes will be removed from the buffer, leasing buffer space for new characters.
The buffer size of the Serial library can be increased by changing the numbers in HardwareSerial.h in the following lines
#define SERIAL_TX_BUFFER_SIZE 64

#define SERIAL_RX_BUFFER_SIZE 64

But this is not really the solution to your problem. When first filling the buffer and then read the whole message you just arbitrarly
constrain yourself to a insufficient solution.
Instead of waiting for all the messages bytes (and finally filling up the buffer) you should steadily check, if new bytes are available and then load them into your own buffer. You can use a delimiter byte to mark the end of a message, mostly "\n" (newline character) is used for this. Copy the bytes into your own buffer, until you read the delimiter byte. Then use the message as a whole for your application. Don't forget to clear your buffer afterwards.
The examples for the Serial library, especially the SerialEvent example show how to do this in your code.

It gets even worse.  There's no concept of a message in a serial line, but there often is in an application.  Further, a serial link proxied over Bluetooth will be bunched into packets and tend to arrive in bursts.  But those bursts often won't align with the boundaries between application messages!

The software from the transmitter can break the text you want to send into pieces of 62 characters in length and send them one by one. The receiver will save the most recent piece in a String and join it with a another String which will be storing the whole message. If you don't mind it being a little bit slower, then this is the solution for you


text:
How can you have two blinking leds and a fading one
I am trying to make a alarm and I have two blinking leds (red and blue). They work fine but I want two more that fade in and out.
I have a buzzer on it too.
I am very new to programming. By the way, the code below runs with no errors; just does not do what its intended to.
int led = 9;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  delay(200);
  digitalWrite(11, LOW);
  delay(200);

  digitalWrite(12, HIGH);
  delay(200);
  digitalWrite(12, LOW);
  delay(200);

 digitalWrite(led, brightness);

 brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 delay(30);
}

see the BlinkWithoutDelay example in IDE

ive done that i cant find anything wrong with my code

your code has delays

Delay = The execution of the program STOP during the delay time! So to continue to execute it is recommended to use 'millis();' as described in the BlinkWithoutDelay!

While there are better ways to do this, as pointed out by other posters, for what you're trying to learn right now, your program (almost!) works just fine. You'll need the more advanced techniques as you progress to more complex programs. But for now, I made a couple of edits to your program to get you going:

The most important one was to use analogWrite() for the PWM LED (LED 9). That makes it fade in and out instead of turn on and off (with a long period).
I turned one LED on and one off at the same time, getting rid of the dark periods and 400ms of combined delay.
I doubled the fadeAmount to fade in and out a little faster; it wasn't very visible with an increment of 5.

Here it is with those changes:
int led = 9;
int brightness = 0;
int fadeAmount = 10;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
  delay(200);
  digitalWrite(11, LOW);
  digitalWrite(12, HIGH);
  delay(200);

 analogWrite(led, brightness);

 brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 delay(30);

}
Update:

what if i wanted to add a a second led

I'm assuming you mean a fading LED, that it's pretty clear where you'd a blinking one?
Blinking in-phase is easy - write the same brightness to both. To fade them out of phase, you'll need a second brightness-variable (and possibly a second fade-amount), and an increment/decrement and limit test for each LED.
But note how your code starts getting more complex as you add components and try to manage them in a single loop, with delay()s? That's when you'll want to try the Blink Without Delay example, and compare adding new LEDs that way, to adding new LEDs to your current program.

so if i just delete my old program and copy this is in theory it should work or just change the other values

It did, on my board. Though, you might want to run my code in a new sketch and save yours to compare the two.

what if i wanted to add a a second led

You have 2 problems:

You are using digitalWrite() with an analog value. digitalWrite() will interpret a value of 0 as LOW and any other value as HIGH. So the LED will mostly be on and only off in the time, when the brightness value becomes zero. You will have to use analogWrite() to get a fading effect.
Currently your fading effect will be very very slow, since the value is only updated once every 830 ms. You should ditch all the delay() calls and instead use the principle, that is shown in the BlinkWithoutDelay example of the Arduino IDE. Think of the blinking as being like baking a pizza. When you want to bake a pizza in your oven, you wouldn't want to sit in front of the oven, staring at the pizza and waiting for it to be ready. This is basically, what you are doing with LED blinking in your sketch. With the pizza you would look at the clock, when you put the pizza in. Then you would go away doing other things and regularly check the clock for how much time has gone by. And then, when it is finally the time to take the pizza out, you would go back to the oven. There are plenty explanations and tutorials on the web, what exactly is done there.

Here at the Arduino documentation you can find the example with explaining text.


text:
Stacking adc's when making an midi controller ( lots of potmeters)
I'm making a midi controller with the Arduino uno. It contains approximately 50 analog inputs with potentiometers. I have enough MCP3008 adc's here but I have no idea how I connect 2 or more adc's to the Arduino so that I can read 50. How do you stack adc's?

Also asked at: http://forum.arduino.cc/index.php?topic=569402 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

why would you use potentiometers?  ..... digital encoders would make so much more sense

These ADC's use the SPI protocol. Luckily the Arduino has one onboard.
With each ADC you get 8 channels (thus inputs). Since you need more than one SPI device (ADC in your case).
With SPI you can chain multiple SPI devices to your SPI port of the Arduino. To select which is active you use the Chip/Slave select signal. This is a separate GPIO you can define yourself. Read more about SPI to read details.
For 50 inputs you need 50 / 8, rounded up is 7 ADCs. This means also 7 CS pins. Thus in total you need 3 (for SPI) + 7 = 10 pins. I hope you have that many left.
About 'stacking', just put the ADC's on a breadboard and wire them according to the SPI protocol.
See also Arduino Reference SPI

Note that with a large number of devices on a SPI bus like this you may need to reduce the communication speed or include a line driver to overcome the increased capacitance on the bus.

Reduced speed will be built in due to the max clock speed of 3.6 MHz with the MCP3008 - thus SPI clock speed of 2 MHz with a 16 MHz Arduino.

With SPI the SCK, MISO, MOSI are connected in parallel to all devices. The device with the active low Chip Select pin is the one that receives a command and then sends data, the others ignore what is happening.  You can also load data into a shift register to create the chip selects, thus only 4 pins are needed: SCK (13), MISO (12), MOSI (11), to all the devices, and use D10, the SS pin, as the latch pin (SRCK) into a 74HC595 for the 7 chip selects out to the MCP3008s.
The code to loop can be pretty simple.
for (pin = 0; pin <7; pin = pin +1){
  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address] = SPI.transfer(addressByte [address]); // send out address, read in D9, D8
  lowerBits[pin + address] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+1] = SPI.transfer(addressByte [address+1]); // send out address, read in D9, D8
  lowerBits[pin + address+1] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+2] = SPI.transfer(addressByte [address+2]); // send out address, read in D9, D8
  lowerBits[pin + address+2] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+3] = SPI.transfer(addressByte [address+3]); // send out address, read in D9, D8
  lowerBits[pin + address+3] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+4] = SPI.transfer(addressByte [address+4]); // send out address, read in D9, D8
  lowerBits[pin + address+4] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+5] = SPI.transfer(addressByte [address+5]); // send out address, read in D9, D8
  lowerBits[pin + address+5] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+6] = SPI.transfer(addressByte [address+6]); // send out address, read in D9, D8
  lowerBits[pin + address+6] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

  digitalWrite (csPin[pin], LOW); // select a device
  SPI.transfer(startByte); // send out start byte
  upperBits[pin + address+7] = SPI.transfer(addressByte [address+7]); // send out address, read in D9, D8
  lowerBits[pin + address+7] = SPI.transfer(0);  // send out don't care read in D7-D0
  digitalWrite (csPin [pin), HIGH); // deselect a device

}

The end result are two 56 byte arrays, upperBits[] and lowerBits[], combine a byte from each for a reading per channel.
I do have a lot of duplicate code there that could likely be reduced to a loop within a loop to remove the redundancy.
'address' could come from an array also, as the data needs to be 0b10000000, 0b10010000, 0b10100000, 0b10110000, 0b11000000, 0b11010000, 0b11100000, 0b11110000
or start with address = 0x80 and add 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70
That code has to integrate to drive the shift register, which I forgot about, so instead of
digitalWrite (csPin[pin], LOW);
and
digitalWrite (csPin[pin], HIGH);

you'd have
digitalWrite (shiftRegisterLatch, LOW); // first MCP3008 CS low
SPI.transfer(0b11111110);
digitalWrite (shiftRegisterLatch, HIGH); //first MCP3008 CS low
// read from ADC0 on first MCP3008 using SPI.transfers above
digitalWrite (shiftRegisterLatch, LOW); // first MCP3008 CS high
SPI.transfer(0b11111111);
digitalWrite (shiftRegisterLatch, HIGH); //first MCP3008 CS high

Repeat for channels ADC1 to ADC7
Then go to the next device:
digitalWrite (shiftRegisterLatch, LOW); // 2nd MCP3008 CS low
SPI.transfer(0b11111101);
digitalWrite (shiftRegisterLatch, HIGH); //2nd MCP3008 CS low
// read from ADC0 on second MCP3008 using SPI.transfers above
digitalWrite (shiftRegisterLatch, LOW); // 2nd MCP3008 CS high
SPI.transfer(0b11111111);
digitalWrite (shiftRegisterLatch, HIGH); //2nd MCP3008 CS high

So the data could be in an array as well: 0b11111110, 0b11111101, 0b11111011, 0b11110111, 0b11101111, 0b11011111, 0b10111111, with 0b11111111 to turn off CS
I'd be using direct port manipulation as well instead of digitalWrite() to speed up latching data into the shift register.


text:
I can't upload sketches to my Arduino 101
When connected to USB green Power LED on but doesn't upload sketch(that says press master reset therefore i've pressed several time but timeout). And main thing is device doesn't show in device manager.(I'm working on windows10).

Have I "bricked" it?
What steps can I take to work out what is wrong?
What can I do to fix it?

I've search in many sites but doesn't give me detail about hardware repairing guide for arduino 101.
I've checked working usb cable and another laptop but not work.I think hardware problem.Once arduino getting hot near usb.

Simply replace it because it has a 1 year warranty outside the US.

It's considered rude to post things in all caps online. I have fixed this for you but please don't do it again. Please add some more details to your answer to make it more helpful: What kind of process was required for the replacement? How did you contact customer service How prompt was their response? Did you have to return the Arduino 101 to get your replacement? If so, were return shipping charges paid by Arduino and was the return address in your country? What sort of restrictions are there for people in the US who need a replacement?

It's hard to tell, but you can try a lot of options:

Use another USB port
Use another USB cable
Reinstall the Arduino IDE
Remove the device in the device manager and try reinstalling the Arduino IDE again
Try another Arduino (to see if the USB/install is ok)
Try on a different computer/laptop

I've also checked all this but i think it's hardware problem.

If you checked all of the above as Michel Keijzers mentioned then it might be a hardware problem. Actually, your usb cable might not fitting correctly to the usb port.


text:
Need Help with Switch Case commands/receiver and lcd screen project?
I am doing a project with a receiver and transmitter and i am trying to get a message to print onto the screen. If anybody has any experience with this could you please help! I am trying to use a switch case command and it's not working.
Edit:
`
#include <LiquidCrystal.h>
#include <VirtualWire.h>
LiquidCrystal lcd(12, 8, 5, 4, 3, 2);
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
void setup()
{
  Serial.begin(9600);
  Serial.println("Device is ready");

  // Initialize the IO and ISR
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  lcd.begin(16, 2);

  // Print a message to the LCD.
}

void loop()
{
  if (vw_get_message(message, &messageLength)) // Non-blocking
  {
    switch(message[1])
    {
    case 0:
      lcd.setCursor(0, 1);
      lcd.print("O.O");
      break;
    case 1 :
      lcd.setCursor(0, 1);
      lcd.print("Hi! :)");
      break;
    }
    {
      Serial.print("Received: ");
      for (int i = 0; i < messageLength; i++)
      {
        Serial.write(message[i]);
      }
      Serial.println();
    }
  }
}

Show what you've tried.

Ive changed my code so many times so far, but at this moment it is:

Okay! I finally got my code to post correctly!

Please read How do I ask a good question?. You have described what you want. Now tell us what happens, and compare that to what you expected to happen.

Too many pieces of the puzzle are missing for us to venture a guess on what is going wrong:

The output you get (both in the LCD and the serial console)
The message sent

One thing that strikes me as a potential problem is the
switch(message[1])

line. If you want to check the first character received, it should be
switch(message[0])

That said, it would perhaps help you if you tried to split the program into pieces and make sure each one works before advancing to the next. Are you sure the LCD pin connections and initialisation line match? (I know from experience it is very easy to mess up and put the pin numbers in the wrong order). It would help to put the following code right after the lcd.begin line (in your setup() function):
  lcd.setCursor(0, 0);
  lcd.print("Initialised!");

Now if this line doesn't display correctly, you will know it is the lcd connection/initialisation code that is at fault. Otherwise, you will concentrate on your communication code.
Give us more information and we 'll be able to help more.


text:
I²C between 2 Arduinos sends additional receive event
I hooked up two Arduino Nanos with I²C, using 3 wires between GND <-> GND, A4 <-> A4, A5 <-> A5Ω and 1kΩ pull-up resistors on A4 & A5.
When I use the following code to communicate between them I get a weird empty receive event.
master.cpp
#include <Arduino.h>
#include <Wire.h>

#define SERIAL_BAUD 9600

#define I2C_SLAVE_ADDRESS 8

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

void getFromState (unsigned char state) {
    Wire.beginTransmission(I2C_SLAVE_ADDRESS);
    Serial.print("s");
    Serial.print(Wire.write(state));
    Serial.print("e");
    Serial.print(Wire.endTransmission());
    delay(5000);
    Wire.requestFrom(I2C_SLAVE_ADDRESS, 2);
    int c = (unsigned char) Wire.read();
    Wire.flush();
    Serial.print("r");
    Serial.println(c);
    Wire.endTransmission();
}

void loop () {
    Serial.println("loop");
    getFromState(0);
    delay(10000);
    getFromState(1);
    delay(10000);
}

slave.cpp
#include <Arduino.h>
#include <Wire.h>

#define SERIAL_BAUD 9600

#define I2C_ADDRESS 8

unsigned char state = 0;

void requestEvent () {
    Serial.print("Request ");
    Serial.println(state);
    Wire.write(state);
}

void receiveEvent (int amount) {
    Serial.print("a");
    Serial.print(amount);
    Serial.print("r");
    state = (unsigned char) Wire.read();
    Serial.println(state);
}

void setup() {
    Serial.begin(SERIAL_BAUD);
    Wire.begin(I2C_ADDRESS);
    Wire.onRequest(requestEvent);
    Wire.onReceive(receiveEvent);
}

void loop() {
    delay(10);
}

Serial Output Master After 1.5 Loops
loop
s1e0r0
s1e0r1
loop
s1e0r0
s1e0

Serial Output Slave After 1.5 Loops
a1r0
Request 0
a0r255
a1r1
Request 0
a0r255
a1r0
Request 0
a0r255
a1r1

Question
Why is there an empty receive event a0r255 after every request? Is that normal? Am I doing something wrong? Is this some sort of hardware issue?
EDIT: I opensourced this project here, take a look if you want to!

The main culprit that is causing your problem is the second
Wire.endTransmission();

after your requestFrom.  That causes the previous startTransmission() to be repeated with no data in it - thus giving you a second receiveEvent call with no data.

That's a quite weird behavior, but sounds like it could truly be the reason this happens. Will have to check this out tomorrow moring since it's quite late in Germany already. :(

It's late here in the UK too, but I'm still firing on all cylinders ;)

yeah I know that feel, I sometimes try not to stay up that long, today is one of these days where I may get a reasonable bedtime.

Thanks, this actually was the reason I was seeing the empty packets. Accepting this answer, since it is more tailored towards the actual problem. Doesn't mean I don't appreciate the other one a lot, but this solved & explained the "real" issue.

Your code has several issues:
For the master:

Your I2C transactions should be quick and not delayed with Serial.print()s like in getFromState()
You requested 2 bytes from the slave but you are reading only one from the buffer. Wire.flush() flushes the outgoing buffer, not the receive buffer. Use while (Wire.read() != -1); instead.
Its also advised that you use Wire.available() to iterate through the receive buffer when read()ing; its how you check if anything was received at all and how many bytes were received.
After using requestFrom(), you shouldn't call endTransmission(). Its self-contained.

For the slave:

You should never call Serial.print() or delay() in requestEvent() or receiveEvent(); both functions are called from within ISRs and ISRs are meant to execute quickly and return.
You are requesting 2 bytes from the slave in your master code, whereas your slave's requestEvent() writes only one byte.
In receiveEvent(), again its best to use either Wire.available() to iterate through the RX buffer or you use the variable amount. This way, you read everything in the buffer; you can also flush the RX buffer like I showed you before.

Finally those delays are rather long; 10ms would do, if they are even needed at all.

Most of these issues are in the code for debugging purposes (serial and ultra long delays so I can actually see whats happening) The thing with 2 bytes is: as soon as I set it to one, it doesn't work anymore, it just stops. The endTransmission is an accident/leftover from code I previously used, will check if any of this changes anything tomorrow morning. I literally tried to debug this code for hours, so I tested a lot of things, one initial issue actually was that I needed the pull ups because otherwise the slave couldn't send anything to the master (except. somehow ACK bits).

Accepted the other answer, because it had a better explanation and was more precisely addressing the actual problem. Thanks for your input nevertheless, if possible I'd accept yours too. :(


text:
I²C only works when I short-circuit my Arduino
I'm trying to connect an Arduino Nano with a Raspberry Pi 3 via I²C.
This is the small test-program I found and used for I²C.
#include <Arduino.h>
#include <Wire.h>

void setup() {
  Wire.begin(4);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

After compiling and uploading, I ssh-ed into my Pi and executed sudo i2cdetect -y 1 which prints an empty I²C table.
Here are images of how I connected the two devices, as far as I know the connection itself is okay. I also tested the cables with a multimeter.

Now the strange thing is, when I short-circuit my Arduino for a brief moment between GND and VIN I²C works, but Serial via USB with my PC stops working. Also the chip gets very hot and stays hot even though it isn't short-circuited anymore.
Any ideas what I'm doing wrong? I don't think the Arduinos are broken, since I tested it with 2 different ones. (while testing I accidentally short-circuited one and it worked)
EDIT: I tested I²C between the two Arduinos and it works flawlessly, but still doesn't want to work with my Pi. :(

Any ideas what I'm doing wrong?

Apart from deliberately shorting +5V to ground? Sheesh!

Get, or make, a level-shifter. You can't pump 5V from the Nano to the Pi and expect things to work. Example schematic:

In this example the low voltage (3.3V) side is marked LV, and the high voltage (5V) side is marked HV.

You can use a level shifter with I²C but you don't need one. The Pi has pullup to 3.3V. Provided there are no other pullup it works. I routinely do this.

The important phrase there is "Provided there are no other pullup".
Wire.begin() enables the pull-ups. So make sure that on the Nano side you disable them again:
  Wire.begin (4);
  // disable internal pullups for twi.
  digitalWrite(SDA, LOW);
  digitalWrite(SCL, LOW);

To be fair, I didn't do it intentionally the first time, that was an accident. Then I had to verify my findings. :)
Also does it have to be a 2N7000?

No it doesn't. Many logic-level N-channel enhancement MOSFETs should do. Read Bi-directional level shifter for I²C-bus and other systems - PDF. And you can buy them on boards, eg. 4-channel I2C-safe Bi-directional Logic Level Converter - BSS138

@Dodekeract You can use a level shifter with I²C but you don't need one. The Pi has pullup to 3.3V. Provided there are no other pullup it works. I routinely do this.

@Milliways what am I doing wrong then? I attached the cables on my Pi and on my Arduino. Didn't add any resistors.

Edited answer to incorporate this suggestion.

On the Atmega328P running at 5V Vcc, a HIGH value is 3V and above. 3.3V is only marginally above this. Plus with weak pull-ups it may take a while to reach that. You may be better off adding 4.7k resistor pull-ups to both SDA and SCL to 3.3V (not 5V).

@Dodekeract Frankly I can't tell from your images exactly what you have connected. See http://blog.oscarliang.net/raspberry-pi-arduino-connected-i2c/ NOTE the hardware is still OK, but Pi software is no longer relevent.

@NickGammon The Pi has 1.8kΩ pullups on board. I was unaware the Wire.begin() enables pullups. Is this documented? Even if these are enabled the effect to the 1.8kΩ to 3.3V would minimise any overvoltage. It is not widely discussed but the Pi (like most IC) would be tolerant of overvoltage which is less than a diode forward drop. A diode clamp to 3.3V is a standard engineering solution to protecting digital inputs.

It's not documented here.

There is not enough information in your question to know for sure, but remember that the rpi is three volt and the arduino is five volt. Given the heat you are seeing you have something miswired.

The heat only starts when I intentionally for a short moment connect GND to VIN. Before I do that once I²C doesn't work, afterwards it does, but serial stops working. Also: What kind of information do you need? I can try to get it.

@Dodekeract - As hildred says, the Nano is 5V. You would be better off using an Arduino Micro Pro 3V, en lieu of a Nano.

Yes, but a Nano is what he has to hand. A couple of transistors will be cheaper than a new Arduino. However you can never have too many Arduinos. :)


text:
How do I clear sim800L buffer?
Let's say that I've tried sending an SMS directly from serial monitor or any kind of terminal. For whatever reason (syntax error, etc), my attempt fails. Now, I try sending it again, but this time by code (as seen on this site):
#include <SoftwareSerial.h>

//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 8

//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7

//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup() {
  //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(9600);
  delay(1000);

  Serial.println("Setup Complete!");
  Serial.println("Sending SMS...");

  //Set SMS format to ASCII
  serialSIM800.write("AT+CMGF=1\r\n");
  delay(1000);

  //Send new SMS command and message number
  serialSIM800.write("AT+CMGS=\"07194XXXXX\"\r\n");
  delay(1000);

  //Send SMS content
  serialSIM800.write("TEST");
  delay(1000);

  //Send Ctrl+Z / ESC to denote SMS message is complete
  serialSIM800.write((char)26);
  delay(1000);

  Serial.println("SMS Sent!");
}

void loop() {
}

The code sends not only the SMS within the code ("TEST"), but also the unwanted junk / remains of the previously unsuccessful sending attempt.
Is there a way to clear the module's buffer before sending a new message?
I guess I could restart the module before sending messages, but I was wondering whether there's a cleaner solution.
P.S. I apologize for the slightly misleading and irrelevant tags, but I can not use the nonexistent sim800L, which would be better suited for my question.

Do you get "TEST[...AT COMMANDS...]TEST" in your SMS? I.e., does it appear that the previous SMS doesn't get terminated and everything sent for the second SMS gets appended to it and then sent?

Yes, that's exactly what I receive. Since the attempt fails, the AT commands and previous text stay, and I don't even get to send CTRL-Z, in order to denote message end. And everything that stays, gets picked up on the next try.

According to the SIM800 AT Command Set you can terminate the sending of an SMS part way through by sending ESC (character 27).
So you can begin your sketch by first sending a number of ESC to ensure that any pre-existing text input for an earlier SMS is abandoned.
serialSIM800.write(27);
serialSIM800.write(27);
serialSIM800.write(27);

Only one should be needed, but it is best to repeat it a couple of times in case the first one isn't taken. You should then do a CR/LF to make sure it's ready for the next command.
serialSIM800.print("\r\n");

However, your method of controlling the modem is crude at best and not particularly reliable. The modem sends back responses from all the commands you send it. You should be reading in those responses and checking that the commands you sent actually worked. That way you can know if a command hasn't been accepted because it is in SMS reading mode (no response within 1 second, say), and you can force an escape.

Works fine, thanks. I can't believe I didn't try that. In regards to the code, it is indeed crude. I've yet to define or implement any kind of error catching, and devise a proper response to it.