DC Motor Pinning the Ada Fruit Moto Shield with the Mega2560 R3 I picked up an AdaFruit Motor Shield V2.3 .  The example on the site shows how to code the DC Motor connection

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2)

What I'm unclear about is how to connect the shield to the mega board.  Which pin on the shield should connect to which pin on the board in order for Motor 1 to run at that speed?

Well because an Arduino Mega2560 is pretty much and UNO with a longer rear end, try seeing the UNO in the MEGA if that makes any sense. Then just put the shield in like a normal shield that you would put on a UNO. Most UNO shields are compatible with MEGAs. Then you just use your shield like if it was on an UNO.


Arduino Mega 2560 and Android USB OTG serial communication currently I am building a little project based on the Arduino Mega 2560.
My goal is to send some data gathered by some sensors to an Android phone.
It has to be as basic as possible.
Buying new hardware is no option.

After some research, I found that it is possible to communicate via USB OTG just with Serial commands.
I downloaded the an app which can do this (Serial Monitor), connected the Arduino via the USB cable to the Android.
Unfortunately, it did not work.

I have an Arduino UNO, too.
Connecting the UNO the same way to the phone works like a charm and does exactly what I want.

I did some more research and found nothing about that.
It seems that everybody is using the Arduino Mega ADK to establish a communication between Arduino and Android.
But I would like to be able to achieve this the same way it works with the UNO.

Can somebody explain me why it does not work?

EDIT
Here is the code I have to test:

Arduino

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

void loop() {
  Serial.println("Test...");
  delay(2000);
}

For Android I use the code from this tutorial.

Any further suggestions?

So I figured it out.

It was the VendorID. I found it and noticed, that the VIDs of the UNO and Mega are different.
I adjusted the code and now everything works as I expect.
So, thank you Chris Startton for the correct hints.

Thank you all.


Matlab to Arduino communication I am doing some computations on Matlab and I need to send those values to an Arduino Leonardo through USB serial connection. I need to send 2 variables which can vary from -400 to +400. I'm saying their values because I was able to do this with small positive values (unsigned byte), but not larger and negative numbers. Please help! Thank you

You cannot send larger values because byte only covers the range from 0-255.

To send larger values, you can break your int variable into 2 byte variables. Here's an example:

// On Arduino
int myVar = -123;
byte myVar_HighByte = myVar>>8; // get the high byte
byte myVar_LowByte = myVar; // get the low byte
// x86 compatible machines are little-endian so we send the low byte first
Serial.write(myVar_LowByte);
Serial.write(myVar_HighByte);

% On MATLAB
s = serial('COM10')
fopen(s)
myVar = fread(s,1,'int16')

Disclaimer: Syntax might not be entirely correct, since I have no MATLAB or Arduino near me when I typed this. But you should get the idea. ;-)

Edit: On second thought, it might be easier to use a pointer.

// On Arduino
float myFloat = 3.14159265359;
byte* ptr = (byte*) (&myFloat);
Serial.write(*ptr++);
Serial.write(*ptr++);
Serial.write(*ptr++);
Serial.write(*ptr);

% On MATLAB
s = serial('COM10')
fopen(s)
myVar = fread(s,1,'float')

Having said that, you will still have to take care of the endianness, if you use a different microcontroller.


Code help in Arduino ( Serial data) I Need a help in this code

I am trying to assign the serial.write(OutData[i]) to byte data[]. Can anyone help me assign it.

Here is my code

#define ECHOPIN 11// Pin to receive echo pulse
#define TRIGPIN 12// Pin to send trigger pulse
int distance=0;
 byte OutData[] = {0x05, 0x03, 0x04, 0x43, 0x65, 0xBA, 0x7D, 0x04, 0xE8};
#include <Crc16.h>
Crc16 crc;
void setup()\
{
  Serial.begin(9600);
 pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
  digitalWrite(ECHOPIN, HIGH);
}
void loop() {
digitalWrite(TRIGPIN, LOW); // Set the trigger pin to low for 2uS
  delayMicroseconds(2);
  digitalWrite(TRIGPIN, HIGH); // Send a 10uS high to trigger ranging
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW); // Send pin low again
  distance = pulseIn(ECHOPIN, HIGH,26000); // Read in times pulse
  distance= distance/58;
  Serial.print(distance, HEX);
   OutData[3] = 0x00;

  OutData[4] = 0x00;

  OutData[5] = 0x41;

  OutData[6] = distance;
for (int i = 0; i <= sizeof(OutData); i++) {

    Serial.write(OutData[i]);

    byte data[] = OutData[i];
    crc.clearCrc();
  for(byte i=0;i<9;i++)
  {
     Serial.print("byte ");
     Serial.print(i);
     Serial.print(" = ");
     Serial.println(data[i]);
     crc.updateCrc(data[i]);
  }
  unsigned short value = crc.getCrc();
  Serial.print("crc = 0x");
  Serial.println(value, HEX);

  Serial.println("The crc Check of the byte array");

  //Modbus
  value = crc.Modbus(data,0,9);
  Serial.print("Modbus crc = 0x");
  Serial.println(value, HEX);

  while(true);
}
int calcrc(char *ptr, int count)
{
    int  crc;
    char i;
    crc = 0;
    while (--count >= 0)
    {
        crc = crc ^ (int) *ptr++ << 8;
        i = 8;
        do
        {
            if (crc & 0x8000)
                crc = crc << 1 ^ 0x1021;
            else
                crc = crc << 1;
        } while(--i);
    }
    return (crc);
}

My Error is :

C:\Users\system3\AppData\Local\Temp\arduino_modified_sketch_307616\sketch_dec13a.ino: In function 'void loop()':

sketch_dec13a:34:25: error: initializer fails to determine size of 'data'

     byte data[] = sizeof(OutData);

                         ^

sketch_dec13a:34:25: error: array must be initialized with a brace-enclosed initializer

sketch_dec13a:60:1: error: a function-definition is not allowed here before '{' token

 {

 ^

sketch_dec13a:77:1: error: expected '}' at end of input

 }

 ^

Multiple libraries were found for "Crc16.h"
 Used: C:\Users\system3\Documents\Arduino\libraries\Crc16-master
exit status 1
initializer fails to determine size of 'data'

The following code block does not make sense:

for (int i = 0; i <= sizeof(OutData); i++) {
    Serial.write(OutData[i]);
    byte data[] = OutData[i];
    crc.clearCrc();
} // I added this bracket for you.

It is formally wrong to create an array this way. The compiler does not have any way to know, how big the array should be. I think the declaration with [] works only, when you initialize the array, but you are simply assigning 1 byte value to it. byte is not the same as array of byte. So this cannot work. To make it formally correct, you can either change data to a simple byte variable (not an array), or define the size of the array via byte data[3]; and then assigning the OutData[i] value to one of it's elements in the next line;
Above I added the closing curly bracket for you after the first for loop. It seems, that you forgot it, thus you would get more errors due to imbalanced brackets.
You are create a variable/array inside your for loop, that is not used anywhere. As soon as the current for loop iteration is finished, the variable/array is out of scope and will vanish. You have to declare it outside of the for loop (either inside the loop() function or globally), so that you can use it in the following code.
It seems, that you try to copy the data from the OutData array into the  data array to output the values in the later code and calculate the CRC value. I don't see, why you are doing this. Is there a reason, why you could not do this directly with the OutData array? I don't see the need for copying the data in an extra array.
The following line can easily be a problem:

OutData[6] = distance;

distance is defined as an int, which is a 16bit/2byte signed number. OutData is defined as an array of byte, which is a 8bit/1byte unsigned number. pulseIn() returns an unsigned long (32bit/4byte unsigned number). Since you have configured a timeout of 26000, you won't get in conflict there, but easily, when trying to assign the distance value to an element of OutData. You can get distance values up to 448, but a byte can only hold numbers between 0 and 255. So you will get an overflow and thus garbled data. You will have to send both bytes of distance to always get the full value. (You can easily google how to get the individual bytes of an int; The Arduino framework even has defines for this, lowByte and highByte, I think).


How to measure the distance between 2 points accurately Does anybody know how i would measure the distance between two points which will be no more than 50mm apart with accuracy to 1mm?

I want to record the distance between the two points in a database over time at frequency of 1 datapoint for every second.

Anybody know what sensors could do this?

want to measure the movement of 2 points on a material surface as it is stretched and released the points move apart and towards one another. The points are real and tangible. This of pins in cloth and we want to measure the distance between the pins.

If the two points can be made then you could use an Ultrasonic range finder. you could have one point be a wall (use balsa wood or something light) then the other could be the range finder. You might have to do a little bit of engineering for attaching the range finder to the pins on the cloth, but I believe it's doable.

heres an amazon link for a generic arduino range finder: http://www.amazon.com/RHX-Ultrasonic-Distance-Measuring-Transducer/dp/B00F6KLLGG/ref=sr_1_2?s=electronics&ie=UTF8&qid=1439459256&sr=1-2&keywords=range+finder+arduino


Reading from EEPROM and writing to addressable LED with limited connections UPDATE
Clock speed code has been tweaked as per the suggestion from @timemage due to inability for Wire library to reduce to below 30304Hz. Unfortunately problems still persist:
Nothing printed out to serial and LED working only after disconnecting and reconnecting the circuit(stops updating after reseting arduino)..
UPDATE
Thanks for all replys. I have left the circuit the same and have used the following code where i have tried to reduce the i2c clock speed to 1khz but unfortunately having no luck.The EEPROM returns nothing and the pixel fails to work initially, only when i disconnect the circuit(this is simple because i am using a magnetic USB connector) it seems to work fine(until i restart the arduino).
If the consensus is that i may have more luck if I alter the library then i may look into it although it sounds a bit out of my depth...
#include <Wire.h>

#define disk1 0x50    //Address of eeprom chip
unsigned int address0 = 0; //address to store the data

#include <Adafruit_NeoPixel.h>

//pixels pin
#define sda_pin A4
#define scl_pin A5

Adafruit_NeoPixel strip(1, sda_pin, NEO_GRB + NEO_KHZ800);

void setup() {

  Serial.begin(9600);

  Wire.begin();

  ////UPDATED CODE TO REDUCE I2C CLOCK SPEED TO 1KHZ////
  TWSR |= 0x03; // chose divide-by-64 prescaler
  TWBR  = 0x80; // closest to 1 kHz from below at 16 MHz with /64 prescaler.

  Serial.println(readEEPROM(disk1, address0), DEC);
  Wire.end();
  pinMode(scl_pin, INPUT);

  strip.begin();           // INITIALIZE NeoPixel strip object (REQUIRED)
  strip.show();            // Turn OFF all pixels ASAP
  strip.setBrightness(100); // Set BRIGHTNESS to about 1/5 (max = 255)

}

void loop() {
  rainbow(10);
}

void rainbow(int wait) {

  static unsigned long timer = 0;
  static long firstPixelHue = 0;

  if (millis() - timer > wait) {
    timer = millis();

    for (int i = 0; i < strip.numPixels(); i++) { // For each pixel in strip...

      int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());

      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
    }
    strip.show(); // Update strip with new contents

    if (firstPixelHue < 5 * 65536) { //incrememnt
      firstPixelHue += 256;
    } else firstPixelHue = 0; //reset

  }
}

byte readEEPROM(int deviceaddress, unsigned int eeaddress )
{
  byte rdata = 0xFF;

  const uint8_t i2c_base_address = 0x50;
  const uint8_t upper_three_eeprom_adress_bits = (eeaddress >> 8) & 0x7;
  const uint8_t i2c_address = i2c_base_address | upper_three_eeprom_adress_bits;
  Wire.beginTransmission(i2c_address);
  Wire.write(eeaddress & 0xFF); // address LSB

  Wire.endTransmission();

  Wire.requestFrom(deviceaddress, 1);

  if (Wire.available()) rdata = Wire.read();

  return rdata;
}

ORIGINAL POST:
I have created a circuit which includes an AT24C16 EEPROM which I only need to read from and an addressable LED (WS2812 IC), which I will be talking to (Using an Arduino Nano).
My original intention was to attach the LED's DIN pin to either SCL or SDA. I thought that since I only needed to read the EEPROM once (and then control the LED), I would be able to share the connection. After creating the circuit, it proved an incorrect assumption.
I am limited to 4 (nets?) total due to the adapter I am using between the Arduino Nano and the rest of the circuit (repurposed magnetic 4 wire USB cable). Could anyone propose a setup which would allow me with only these 4 connections, to read from the EEPROM and write to the LED? As I mentioned, I only need a single read from the EEPROM to identify it and then I will only be writing to the pixel. Many thanks!
Attached is the schematic.

My working details, per-request
Setup
So, the setup is the same as you what you have in its essentials:

The code is your code with the near-1 kHz tweak.  That said, I believe I also tested it at the default rate and that worked as well.  In any case, the images that show the LED changing were taken while that 1 kHz adjustment was made.

The UNO and Nano are functionally identical for this.  They use different serial transceivers which has nothing to do with anything.   The Nano will typically have a lower "5V" than the UNO when USB powered owing to the Nano using a diode where the UNO has a FET.  Which is unlikely to matter either.  They're otherwise the same device so far as the setup goes.

The 24LC02B uses the same pinout and I2C address and command-sequences as your AT24C16.  It is a smaller memory, not that it makes a difference; we're reading from address 0.  I did not find I necessary to add external pull-up resistors and it worked, so it seemed unnecessary to add them to demonstrate that it can work since adding them should only improve it's chances for working correctly.

The LEDs are the Adafruit ADA1643 12 Neopixel Ring. We're both using the first LED of a string, doesn't really matter how long the are.   We're only lighting one "pixel" so I just powered it from USB.  Have no idea what you're doing there.  But for one LED lit, I doubt a difference there would matter much.

You'll see a resistor connecting SDA at the EEPROM to IN on the addressable LED(s).  I put that there in case by some chance the EEPROM could drive SDA low while the addressable LED code was driving the LED data line high. while.  I doubt that can happen, but it was a small thing to do.  For what it's worth, I did run it briefly without it in series, and it also worked fine that way as well.  I'm only telling you this so you have all the information and not because I think it matters; I don't.

Running
It prints out 72.  This is the first value in my EEPROM. The 'H' of "Hello world" basically.  And then it goes on to cycle the first addressable LED of the set through all of the colors.
Configuration Pictures


Digispark Serial Port Communication I am using Digispark ATTiny85 and i need to send and receive data through the serial port of my computer.
Does anyone have an idea as to how do i proceed with sending STRINGS and NUMBERS through the serial port ??

I have read that the ATTINY 85 does not have a serial port.
If that is the case is there any alternative ??

have read that the ATTINY 85 does not have a serial port.

It depends on your definition of serial port.

From a hardware perspective it has a usi. That can be configured as a uart. Whether it fits your need or not is up to your application. Read the datasheet to be sure.


Ping sensor with three or four pins? I bought a Ping Ultrasonic Range Finder. It has four pins that you connect to the Arduino. I see in Internet that they have three pins. What does represent each pin and where to connect it to? I have an Arduino Uno Starter Kit.

You have 4 pins.

Vcc: +5V supply voltage (it stands for Collector Voltage)
GND: Ground.
Trig: Causes an ultrasound pulse to be generated (it stands for Trigger)
Echo: Tells you when an echo has been received.

You can see how to wire and use it here: http://www.instructables.com/id/Easy-ultrasonic-4-pin-sensor-monitoring-hc-sr04/


With the press of a button, I need to play an intro sound file, then one of 50 other sounds in order, each time a button is pressed I need to play an intro file and one of 50 different files after it in order each time the switch is pressed, with a short delay between the intro and next file.

For example let's say the intro is called "intro.wav," and each of the 50 other sound files are just named 01.wav-50.wav.

The logic would be:

TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 01.wav
END

TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 02.wav
END

TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 03.wav
END

and so on, until all 50 files are played, then start over.

The messages are going to be a curated group of words. I'm not sure what the intro will be yet, but it will just be something like:

intro.wav = "The word of the day is"

01.wav = "help"

02.wav = "climb"

03.wav = "think"

I'm looking for some guidance on where to start with this, if an Arduino product would be suitable, and if so, which one.  I've worked with the Adafruit Audio FX Sound Board before, and that can almost do what I need it to do, but not by itself. It looks like I'll need an Arduino of some kind to accomplish this, so I went ahead ordered an Uno.

I'm not married to the idea of having the intro and word files separate either. If I need to create all 50 files to contain the intro and the word, that would be fine, as long as each one is triggered sequentially.

In that scenario, 01.wav could be "The word of the day is ... help" and the button would basically be the "next track" command.  I don't really have a problem with doing that because I'm all about keeping things simple and I don't think I'd run out of space, but I think it would be less time consuming to just dump all the individual word files onto the card.

The important thing is that the track(s) would play once, then stop, and when the button is pressed again, the next one plays.

You will find all the code and thelibrary you need on the Adafruit learn center.
For such a project I would use a DF-robot (clone) MP3 player (~4$), an Uno, a speaker and an SD card. The library for the player includes examples to get you started and the sound project you plan is possible even with low programming skills. Look at the example codes provided and start to program.


Servo starts to shake when I added SIM900.begin(19200); Hello I'm working on this mini project. This project works this way, Whenever someone type wrong password, LCD will display "Access Denied" and send an alert to SMS using GSM module.  I used 2 Arduinos for this project, The 1st Arduino is powered up by my laptop this is where the signal pins are connected the RX/TX of GSM is connected in (pin 10 and 11) respectively and the LCD is in pin (2-9) and Servo to (A4) . The second Arduino I used is powered up with a charger and used it for GSM power source it function well as it blinks every 2 sec. I'm really wondering why my servo is shaking whenever I add the  SIM900.begin(9600); at the setup in Arduino IDE?

This is the code

#include <Keypad.h>
#include <Password.h>
#include <Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#include <SoftwareSerial.h>
SoftwareSerial SIM900(10, 11);

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
Password password = Password( "9999" );
Servo myservo;

const byte ROWS = 4;
const byte COLS = 4;

char keys[ROWS][COLS] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'}
};

byte rowPins[ROWS] = {3, 4, 5, 6};
byte colPins[COLS] = {7, 8, 9, 10};

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
int pos = 0;

void setup(){

  Serial.begin(9600);
  SIM900.begin(9600);

  myservo.attach(13);
  lcd.begin(16, 2);
  lcd.print("Arduino Password");
  lcd.setCursor ( 0, 1 );
  lcd.print (" Door  Lock ");
  delay ( 2000 );
  setup1();

}
void setup1(){

  lcd.clear();
  lcd.home();
  lcd.print("Enter your code:");
  keypad.addEventListener(keypadEvent);
}

void loop(){
  keypad.getKey();
}

//take care of some special events
void keypadEvent(KeypadEvent eKey){
  switch (keypad.getState()){
    case PRESSED:
        Serial.println(eKey);
        switch (eKey){
          case '4': checkPassword(); break;
          case '2': password.reset(); break;
          case '8': lock(); break;
          default: password.append(eKey);
     }
  }
}

void checkPassword(){
  if (password.evaluate()){
    lcd.clear();
    lcd.print("Access granted");
    delay(1000);
    unlock();
  }else{
    lcd.clear();
    lcd.print("Access denied");
    delay(2000);
    sendSMS();
    delay(1000);

  }
  password.reset();
  delay(1000);
  setup1();
}

void unlock(){
  lcd.clear();
  lcd.print("Unlocking...");
  delay(2000);
  pos = 90;
  myservo.write(pos);
  lcd.clear();
  lcd.print("Unlocked! Press");
  lcd.setCursor(0, 1);
  lcd.print("* to lock!");
  delay(1000);
}

void lock(){
  lcd.clear();
  lcd.print("Locking...");
  delay(1000);
  pos = 0;
  myservo.write(pos);
  setup1();
}
void sendSMS() {

  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
  SIM900.print("AT+CMGF=1\r");
  delay(100);
  SIM900.println("AT + CMGS = \"+6XXXXXXXXXX\"");
  delay(100);
  SIM900.println("Wrong password Typed");
  delay(100);
  SIM900.println((char)26);
  delay(100);
  SIM900.println();
  // Give module time to send SMS
  delay(5000);
}

Servo.h use interrupts to generate the control signal. However, SoftwareSerial really messes interrupts up.

You can't use SoftwareSerial with anything that relies on interrupts for timing, like Servo.h.

Solutions:

Use a better Arduino with an unused hardware UART
Use an external hardware PWM controller to drive the servos
Use the internal hardware PWM (you'd need to find a library to do this) to drive the servos.


To connect a simple toy circuit and trigger with an arduino? I have a small circuit from a toy sword that has an LED and a small speaker. It was powered by a couple of small coin cells.

I am trying to figure out how to connect it to my Arduino so I can trigger it.
If I attached the circuit directly to the GND and +3.3V and press the switch in it I get the sound of a sword and flashing LED as desired.

Now I want to somehow get the Arduino to trigger the circuit but am very new to Arduino and quite unsure of how to approach this.

Can anyone advise how best to work with an existing low power circuit that can use the Arduino's power rails but needs the switch integrated?

Sorry for the noob question.

You'll probably want to use a transistor to switch it on/off. You could just use the Arduino's digital pin but they can only supply a limited amount of current. Transistors can work with larger currents. The Arduino switches the transistor and it powers the external circuit.

There are a couple of existing questions that may help you.

How to switch an external circuit with Arduino?
How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino?

jippie's answer in the first link shows an example schematic for hooking up a transistor with a bunch of LEDs but you would replace them with your own circuit:


Arduino timer to turn a serve at a certain time i am working on a project for my school tech class. Our goal is to make a vehicle that will travel along a cable and drop an egg to a target while going down the cable. i am using an arduino to to open a trap door with a servo after a certain amount of time that is set by two push buttons, and a third push button will control when the timer starts.
Here is my circuit

Here is the code:

#include <Servo.h>
#include <LiquidCrystal.h>

int b = 0;
int up = 0;
int down = 0;
int val = 100;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Servo myservo;

int pos = 0;

void setup()
{
  pinMode(b, INPUT);
  pinMode(up, INPUT);
  pinMode(down, INPUT);
  lcd.begin(16, 2);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  digitalRead(down);
  digitalRead(up);
  digitalRead(b);
  lcd.setCursor(0, 0);
  lcd.print("milli seconds:");

  while (b == HIGH)
  {
    digitalRead(down);
    digitalRead(up);
    digitalRead(b);
    lcd.setCursor(0, 1);
    lcd.print(val);
    myservo.write(0);
    if (up == HIGH, down == LOW)
    {
      val + 1;
    }
    if (down == HIGH, up == LOW )
    {
      val - 1;
    }

    delay(val);
    myservo.write(100);
    delay(1000);
  }
}

in setup you are calling

pinMode(b, INPUT);
pinMode(up, INPUT);
pinMode(down, INPUT);

but b, up and down all equal 0 so this is what you are doing is :

pinMode(0, INPUT)
pinMode(0, INPUT)
pinMode(0, INPUT)

This doesn't do what you want at all, these need to be assigned to pins. All you are doing is repeatedly setting arduino digital pin 0 to INPUT 3 times.

secondly

while(b == HIGH)

will never fire since b is 0 and is never set to anything else. so it will never == HIGH

Finally,

digitalRead(down);

doesn't do anything useful; what it does is read from pin down which is set to 0, and then drops the return value on the floor

also, this,

if (up == HIGH, down == LOW)

is just very wrong, sholud be

if (up == HIGH && down == LOW)

anyway based on you scematic, fixing this code:

#include <Servo.h>
#include <LiquidCrystal.h>

const int B = 7;
const int UP = 8;
const int DOWN = 9;
int val = 100;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Servo myservo;

int pos = 0;

void setup()
{
  pinMode(B, INPUT);
  pinMode(UP, INPUT);
  pinMode(DOWN, INPUT);
  lcd.begin(16, 2);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  lcd.setCursor(0, 0);
  lcd.print("milli seconds:");
}

void loop()
{
  // todo: debounce the switches
  int up = digitalRead(UP);
  int down = digitalRead(DOWN);
  int b = digitalRead(B);

  if (up == HIGH && down == LOW)
  {
     val += 1  // todo: handle overflow
  }

  if (down == HIGH && up == LOW )
  {
     val -= 1
  }

  lcd.setCursor(0, 1);
  lcd.print(val);

  if(b == HIGH)
  {
    myservo.write(0);
    delay(val);
    myservo.write(100);
    delay(val);
  }

}

this will do what the origonal code was trying to do, more or less, but the
proper way to do this would be (in psuedo-code):

// Setup pins etc.
// Setup(): pinMode(...) ... etc.
// Loop():
//   debounce buttons
//   handle up/down
//   record milliseconds when button is pressed
//   see how much time has passed
//   trigger servo when timer has passed


NEO GPS 6M connecting to Lilypad Arduino I'm working on a project that has something to do with receiving gps data from the satellites. With this, I've used GPS NEO 6M with an arduino Lilypad for wearable purposes.

I've already tried using the Arduino Mega ADK and it's working with my codes before I used Lilypad.

With pin connections:

Lilypad         GPS
Vcc ----------> Vcc
GND ----------> GND
D4  ----------> TX
D3  ----------> RX

And here is the code I used for it:

  #include "TinyGPS++.h"
  #include "SoftwareSerial.h"

  SoftwareSerial serial_connection(4, 3);
  TinyGPSPlus gps;//This is the GPS object that will pretty much do all the grunt work with the NMEA data
  void setup()
  {
  Serial.begin(9600);//This opens up communications to the Serial monitor in the Arduino IDE
  serial_connection.begin(9600);//This opens up communications to the GPS
  Serial.println("GPS Start");//Just show to the monitor that the sketch has started
  }

  void loop()
  {
  while(serial_connection.available())//While there are characters to come from the GPS
  {
  gps.encode(serial_connection.read());//This feeds the serial NMEA data into the library one char at a time
  }
  if(gps.location.isUpdated())//This will pretty much be fired all the time anyway but will at least reduce it to only after a package of NMEA data comes in
  {
//Get the latest info from the gps object which it derived from the data sent by the GPS unit
  Serial.println("Satellite Count:");
  Serial.println(gps.satellites.value());
  Serial.println("Latitude:");
  Serial.println(gps.location.lat(), 6);
  Serial.println("Longitude:");
  Serial.println(gps.location.lng(), 6);
  Serial.println("Speed MPH:");
  Serial.println(gps.speed.mph());
  Serial.println("Altitude Feet:");
  Serial.println(gps.altitude.feet());
  Serial.println("");
  }
  }

 /*
* $GPRMC,183729,A,3907.356,N,12102.482,W,000.0,360.0,080301,015.5,E*6F
$GPRMB,A,,,,,,,,,,,,V*71
$GPGGA,183730,3907.356,N,12102.482,W,1,05,1.6,646.4,M,-24.1,M,,*75
$GPGSA,A,3,02,,,07,,09,24,26,,,,,1.6,1.6,1.0*3D
$GPGSV,2,1,08,02,43,088,38,04,42,145,00,05,11,291,00,07,60,043,35*71
$GPGSV,2,2,08,08,02,145,00,09,46,303,47,24,16,178,32,26,18,231,43*77
$PGRME,22.0,M,52.9,M,51.0,M*14
$GPGLL,3907.360,N,12102.481,W,183730,A*33
$PGRMZ,2062,f,3*2D
$PGRMM,WGS 84*06
$GPBOD,,T,,M,,*47
$GPRTE,1,1,c,0*07
$GPRMC,183731,A,3907.482,N,12102.436,W,000.0,360.0,080301,015.5,E*67
$GPRMB,A,,,,,,,,,,,,V*71
*/

This code was working when I used the mega ADK. And I concluded now that the program is not the issue why it's not working and receiving any gps data from the satellites above.
Does anybody here have tried working similarly with this project using Lilypad arduino? I kept banging my head figuring out the possible reason why my GPS is not working with the Lilypad.

I hope you can help me with this.

Cheers!

Working code and schematics for Neo 6 and Lilypad.

Try this and, if you still have "not working" situation, please inform problem in more detail.


HTU21 on GY-21 breakout board I2C problem I am interfacing the HTU21D sensor with my nodeMCU v3. All good! I managed to get some readings etc. But when I re-upload my code the device does not respond. If I remove the power supply from the pin and hard reset it, it works again. I have exactly the same problem using the Sparkfun library, so it seems more of a hardware problem. Anyone else had the same problem?
link to the sparkfun library
https://github.com/sparkfun/SparkFun_HTU21D_Breakout_Arduino_Library
for reference, here is my code

   This program interfaces the HTU21 temp/humidity sensor via I2C
*/

#include <Wire.h>
#include <Math.h>

const int HTU21_ADDR = 0x40;
const int Trigger_Temp_Measurement = 0xE3;// hold master
const int Trigger_Hum_Measurement = 0xE5; // hold master
const int Trigger_Temp = 0xF3; //No Hold Master
const int Trigger_Hum = 0xF5; //No Hold Master

int16_t Temp, Hum;//variables to store temp and humidity
int8_t TmpCrc, HumCrC;

void setup() {// put your setup code here, to run once:
  Serial.begin(9600);
  Wire.begin();
  Wire.beginTransmission(HTU21_ADDR);
  Wire.write(0xFE);
  Wire.endTransmission(true);

}

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

}

void TempReading() {

  Wire.beginTransmission(HTU21_ADDR);
  Wire.write(Trigger_Temp_Measurement);
  Wire.endTransmission();

  Wire.requestFrom(HTU21_ADDR, 3, true);
  if (Wire.available() <= 3) {
    Temp = (Wire.read() << 8) | (Wire.read() );
    TmpCrc = Wire.read();
  }
  float TempCalc = -46.85 + (175.72 * ((float)Temp / (pow(2, 16))));
  Serial.print("Temperature \t");
  Serial.print(TempCalc);
  //Serial.println(TmpCrc, HEX);

}

void HumReading() {
  Wire.beginTransmission(HTU21_ADDR);
  Wire.write(Trigger_Hum_Measurement);
  Wire.endTransmission();

  Wire.requestFrom(HTU21_ADDR, 3, true);
  if (Wire.available() <= 3) {
    Hum = (Wire.read() << 8) | (Wire.read());
    HumCrC = Wire.read();
  }

  float HumCalc = -6 + 125 * (Hum / (pow(2, 16)));
  Serial.print("\t Humidity \t");
  Serial.println(HumCalc);
  //Serial.println(HumCrC, HEX);

}```

Yes the setup runs completely. I found out that the bus hangs if I terminate communication by uploading new code to the board. I found a piece of code that releases the bus which works. See below:

#if defined(TWCR) && defined(TWEN)
  TWCR &= ~(_BV(TWEN)); //Disable the Atmel 2-Wire interface so we can control the SDA and SCL pins directly
#endif

  pinMode(SDA, INPUT_PULLUP); // Make SDA (data) and SCL (clock) pins Inputs with pullup.
  pinMode(SCL, INPUT_PULLUP);

  boolean SCL_LOW = (digitalRead(SCL) == LOW); // Check is SCL is Low.
  if (SCL_LOW) { //If it is held low Arduno cannot become the I2C master.
    return 1; //I2C bus error. Could not clear SCL clock line held low
  }

  boolean SDA_LOW = (digitalRead(SDA) == LOW);  // vi. Check SDA input.
  int clockCount = 20; // > 2x9 clock

  while (SDA_LOW && (clockCount > 0)) { //  vii. If SDA is Low,
    clockCount--;
    // Note: I2C bus is open collector so do NOT drive SCL or SDA high.
    pinMode(SCL, INPUT); // release SCL pullup so that when made output it will be LOW
    pinMode(SCL, OUTPUT); // then clock SCL Low
    delayMicroseconds(10); //  for >5uS
    pinMode(SCL, INPUT); // release SCL LOW
    pinMode(SCL, INPUT_PULLUP); // turn on pullup resistors again
    // do not force high as slave may be holding it low for clock stretching.
    delayMicroseconds(10); //  for >5uS
    // The >5uS is so that even the slowest I2C devices are handled.
    SCL_LOW = (digitalRead(SCL) == LOW); // Check if SCL is Low.
    int counter = 20;
    while (SCL_LOW && (counter > 0)) {  //  loop waiting for SCL to become High only wait 2sec.
      counter--;
      delay(100);
      SCL_LOW = (digitalRead(SCL) == LOW);
    }
    if (SCL_LOW) { // still low after 2 sec error
      return 2; // I2C bus error. Could not clear. SCL clock line held low by slave clock stretch for >2sec
    }
    SDA_LOW = (digitalRead(SDA) == LOW); //   and check SDA input again and loop
  }
  if (SDA_LOW) { // still low
    return 3; // I2C bus error. Could not clear. SDA data line held low
  }

  // else pull SDA line low for Start or Repeated Start
  pinMode(SDA, INPUT); // remove pullup.
  pinMode(SDA, OUTPUT);  // and then make it LOW i.e. send an I2C Start or Repeated start control.
  // When there is only one I2C master a Start or Repeat Start has the same function as a Stop and clears the bus.
  /// A Repeat Start is a Start occurring after a Start with no intervening Stop.
  delayMicroseconds(10); // wait >5uS
  pinMode(SDA, INPUT); // remove output low
  pinMode(SDA, INPUT_PULLUP); // and make SDA high i.e. send I2C STOP control.
  delayMicroseconds(10); // x. wait >5uS
  pinMode(SDA, INPUT); // and reset pins as tri-state inputs which is the default state on reset
  pinMode(SCL, INPUT);
  return 0; // all ok
}

Thanks for pointing me in the right direction!


Power Arduino with 12V while using Serial Communication over USB I'm going to build a 8x8x8 Led RGB Cube, therefore I will need a lot of Power which the arduino can't handle, so I'm using a 12V 20A (I know 20A isn't necessary but I had one laying around).

So the question is, is it possible to power the arduino over the Vin Pin with the 12V and program / communicate over serial connection in the same time? Like a real time programmed RGB LED Cube.

simulate this circuit – Schematic created using CircuitLab

How to power an Arduino
Arduino can manage multiple power inputs at the same time while fully operational (incluide Serial - USB connection to the PC).

JAPAN JACK socket: an external source (a power supply, usually) must be connected to this socket, with the positive pole going to the central part of the jack, and the value must be ranging between 6 V and 20 V, even though the range recommended by the manufacturer is 7÷12 V, thus it is not advisable to use voltages that are lower than 7 V or greater than 12 V, if not in the case of a real need; 6 V may not guarantee a proper stabilization on the part of the regulator, it is in fact needed to consider the voltage fall of the protection diode, placed in series at the regulator’s input (whose purpose is to preserve the board from destruction in the case of polarity inversion on the jack); while values above 12 V would create an excessively high drop-out (an electric potential difference between the regulator’s input and output) that would cause a pointless overheating of the regulator, even with low levels of current draw.


Unable to tell if error is from receiving or transmitting end so I am having trouble sending data using software serial's write function.

TX Code:

#include <SoftwareSerial.h>

SoftwareSerial TX(2,3);

void setup() {
  // put your setup code here, to run once:
  TX.begin(1200);
}

void loop() {
    TX.write(60);
}

Is the delay necessary?

RX Code:

#include <SoftwareSerial.h>
SoftwareSerial RX(2,3); //(rx pin, tx pin)
const unsigned int bufferSize = 100;

void setup() {
  Serial.begin(9600);
  RX.begin(1200);

}

void printBuffer(const uint8_t *serialBuffer)
{
  //print contents of buffer
  for (int i = 0; i<100; i++)
    Serial.println(serialBuffer[i], BIN);
}

void processBytes(const uint8_t value)
{
  static uint8_t serialBuffer[bufferSize]; //buffer to hold values
  static unsigned int startPosition=0;

  if(startPosition < bufferSize)
    serialBuffer[startPosition++] = value;

  else
  {
    printBuffer(serialBuffer);
    startPosition = 0;
  }

}//end of processBytes
void loop() {

  //check if data is available in serial buffer
  while(RX.available())
  {
    //process data
    processBytes(RX.read());
  }
}

If i transmit the number 60, it prints 226 constantly for 2-3 seconds, then prints 60 for a short while, then goes back to printing 226. Am I doing something wrong with my code?

FIRST QUESTION: In the case when startPosition (in the process function) equals 100, it will call print. Print will then print 100 integers. Now, when doing that, there could still be data being transmitted from the transmitter. But the read function won't be executed until printBuffer returns, process returns, and the while loop iterates again. So during that time, couldn't some transmitted values potentially not be read?

SECOND QUESTION How come Software serial doesn't synchronize incorrectly more often? How is it being so accurate if the start bit is just a single bit and it's a 0. So for instance, if payload has some 0s, how come one of those 0s aren't being assumed to be the startbit? How does this get resolved? I looked at the software serial library, but I am not able to find out why. Any guidance here?

THIRD QUESTION Other than getting the startbit syncing right, are there other ways to sync the data? I was reading of NRZ encoding, manchester encoding, etc. Can any of these be implemented here? Also, would it be wise to alter the softwareSerial library to have more than one startbit?

Any guidance would be very appreciated! Thank you so much!
This is all being done with wireless RF modules.

void loop() {
  Serial.println("NEW-------------");
  int x;
  int y[100];
  for(int i = 0; i<100; i++){
    x=RX.read();
    y[i] = x;
  }
...
}

You are reading data without checking if there is any data there. That's like watching the TV without checking if it is turned on. Of course you get weird data.

SoftwareSerial RX(0,1); //(rx pin, tx pin)

Pins 0 and 1 are used by HardwareSerial. Why are you using them for SoftwareSerial?

SoftwareSerial RX(0,1); //(rx pin, tx pin)
...

  Serial.begin(9600);
  RX.begin(1200);

So you initialized HardwareSerial, which now controls pins 0 and 1.

Then you try to initialize SoftwareSerial on those same pins! Would you mind explaining why?

Whatever your explanation is, it won't work.

  I've added in the changes you mentioned, but the data still seems to be skewed.

You've changed things, for sure:

 for(int i = 0; i<100; i++){
    if(RX.available())
      x=RX.read();

    y[i] = x;
    }

Let's see. In a loop of 100 iterations you see if anything is available (and if so, put it into x).

Then, regardless of whether or not you got anything you now assign x to y[i]. So, most of the time, y[i] will have garbage in it.

  the data still seems to be skewed

Not surprised. Do it differently. Only write to the array if you have data. In fact you may want a complete rework. Read this:

How to read serial without blocking

  I have posted the amended code. Change: Only add to the array is data is being read from buffer.

  int y[100];
  for(int i = 0; i<100; i++){
    if(RX.available())
    {
      x=RX.read();
      y[i] = x;
    }
  }

 for (int j = 1; j<=64; j++){
    Serial.println(y[j]);
  }

You still have not fixed it. Let me talk you through what it is doing now.

You are making 100 attempts to read some data. One or two may succeed, and they will be put into the buffer y (funny name for a buffer, right?).

So imagine . is garbage and X is good data, after doing that loop of 100 the buffer will look like this:

........X...........X...........X...X......................X.............................................

So your buffer is still 80% unchanged garbage. Then you print the first 64 elements (why 64 and not 100?) and you get a lot of garbage out. Exactly as expected.

You need to think about what you are doing. Draw it out on a bit of paper, perhaps.

Here is some example code from the page I linked for you, more than once. Please compare:

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

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

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

  }  // end of loop


MG2639 CELL AND GPS LIBRARIES I'm using a MG2639 Cell Module with the SMS and GPS functionality.
I have a sketch that sends through SMS the location of the arduino UNO.

This is my code:

#include <SoftwareSerial.h> //to communicate with mg2639 cell module.
#include <SFE_MG2639_CellShield.h> //basic librarie of the module.
#include <AltSoftSerial.h>   //to communicate with the GPS module
#include <TinyGPS++.h>    //to acquire the NMEA codes.

TinyGPSPlus gps;

AltSoftSerial ALTS(9, 8);
char celprim[11]="4423337388";
uint8_t GPStatus=0;
long temp=0;

 void configurado()
{
  sms.start(celprim);
  sms.print("Transmitiendo GPS Tracking....");
  sms.send();
  delay (6000);
}

     void GPSTracking()
{
   do
      {
        if (ALTS.available()>0)
          if (gps.encode(ALTS.read()))
      {
        if (gps.date.isValid() && gps.location.isValid() && gps.time.isValid()){
          sms.start(celprim);
          sms.print("Fecha/Hora/Ubicacion: ");
          sms.print(gps.date.day());
          sms.print("-");
          sms.print (gps.date.month());
          sms.print("-");
          sms.print(gps.date.year());
          sms.print(" ");
          if ((gps.time.hour()-5) < 10) sms.print("0");
          sms.print(gps.time.hour()-5);
          sms.print(":");
          if (gps.time.minute() < 10) sms.print("0");
          sms.print(gps.time.minute());
          sms.print(":");
          if (gps.time.second() < 10) sms.print("0");
          sms.print(gps.time.second());
    sms.print("https://www.google.com.mx/maps/dir/19.4161748,-99.1664011/");
          sms.print(gps.location.lat(), 6);
          sms.print(",");
          sms.print(gps.location.lng(), 6);
          sms.print("/@");
          sms.print(gps.location.lat(), 6);
          sms.print(",");
          sms.print(gps.location.lng(), 6);
          sms.print(",19z");
          sms.send();
          GPStatus=1;
        }
    }
      if ((millis()-temp) > 30000 && GPStatus==0)
      {
        GPStatus=1;
        sms.start(celprim);
        sms.print("Imposible ubicar equipo, intente mas tarde...");
        sms.send();
      }
    }while (GPStatus ==0);
}

void setup()
{
  delay (5000);
  int beginStatus = cell.begin();
  if (beginStatus <= 0)
  {
     while(1)
      ;
  }
  delay (10000);
  sms.setMode(SMS_TEXT_MODE);   //Se pone al modulo en modo de recepción y envio de sms
  ALTS.begin(115200); // Or whatever rate the GPS uses
  configurado();
}

void loop()
{
  if (GPStatus==0)
  {
    temp = millis();
    GPSTracking();
  }
}

Is it possible to use only AltSoftSerial to create 2 serial ports and communicate with both cell and GPS in order to reduce program storage and global variables space? If it's possible, what changes should do in the MG2639 library to make it work?
Or what could i do to reduce space.

Is it possible to use only AltSoftSerial to create 2 serial ports and communicate with both cell and GPS in order to reduce program storage and global variables space?

The question is a little vague.

AltSoftSerial only works on pins 8 & 9, so I thought you were asking if you could connect both the cell and the GPS to pins 8 & 9 (using jumper pads on the back of the board), and use one AltSoftSerial instance to talk to both devices.  If it were possible, this would save RAM (just one instance) and program space (you wouldn't need two link in another software serial class, like SoftwareSerial).  However, this is not possible.  Serial connections are always point-to-point.  Although two "things" can listen to one RX line, the TX line cannot be shared by two devices.

If you were asking if you can have two instances of AltSoftSerial on two separate pairs of pins (e.g., 2/3 and 8/9), the answer is again "No", because... AltSoftSerial only works on pins 8 & 9.  Also, the SparkFun library only uses SoftwareSerial to talk to the cell.

  what could i do to reduce space.

Use NeoGPS instead, and use the F macro around double-quoted strings that you print:

    sms.print( F("Imposible ubicar equipo, intente mas tarde...") );

That will save several hundred bytes of RAM.

Also, you may be sending multiple SMS's per second.  It depends on what sentences the GPS emits.  As it is, your sketch will send one SMS per sentence (i.e., one for each encode).  Even if you don't use NeoGPS, look at the example program NMEAloc.ino et al for the correct program structure.  The Troubleshooting section also contains some tips.


Can I use arduino and mobile phone screen to make a touch board? I'm new to Arduino, I want to use Arduino and a mobile phone screen to make a simple touch board.

This phone screen I mean, is like this:

Can I connect it to Arduino, and when my fingers touch the screen, Arduino can get the events?

First, find a suitable phone screen! Good luck. Most of the touch screens that I have found are resistive, and will never feel like an iPhone. Try googling "Arduino touch screen". Adafruit have a promising one.

Once you find your screen, you will need to interface to it. With luck it will come with a pre-built library. Otherwise you will be up for quite a lot of coding.


TCS230 Low Pulse Length with Arduino My son and I are attempting to connect a TCS230 Color Sensor to an Arduino Nano using the tutorial at TopTechBoy.com (http://www.toptechboy.com/arduino/lesson-15-super-cool-arduino-color-sensor-project/) as guidance.

Everything seems to be working except that the conversion from pulseIn to RGB used on TopTechBoy is expecting a maximum pulse count of 102,400. Instead I am receiving pulseIn readings with a maximum of 2000.

Our Wiring

S0  - GND
 S1  - 5V
 OE  - No Connection (Tried GND)
 GND - GND
 S2  - D8
 S3  - D7
 OUT - D4
 VCC - 5V

Our Code:

int S2 = 8;
int S3 = 7;
int OUT = 4;

void setup() {

Serial.begin(9600);
pinMode (S2, OUTPUT);
pinMode (S3, OUTPUT);
pinMode (OUT, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int red , green, blue;

  red = getRed();
  Serial.print("Red : "); Serial.println(red);
  Serial.println("**********************");
  Serial.println();

  blue = getBlue();
  Serial.print("Blue : "); Serial.println(blue);
  Serial.println("**********************");
  Serial.println();

  green = getGreen();
  Serial.print("Green : "); Serial.println(green);
  Serial.println("**********************");
  Serial.println();

  delay(3000);

}

int getRed(void){ return getColor(0, 0, 19000, 24000); }

int getGreen(void){return getColor(1, 1, 13600, 19200);}

int getBlue(void){return getColor (0, 1, 16400, 21600);}

int getColor(int s2Value, int s3Value , int typicalPulseWidth, int maxPulseWidth){

  long divideForScale = typicalPulseWidth / 255 ;

  digitalWrite(S2, s2Value);
  digitalWrite(S3, s3Value);

  unsigned int pulseWidth = pulseIn(OUT,LOW);

  Serial.print("Pulse Width : "); Serial.println(pulseWidth);

  unsigned int rColor = pulseWidth / divideForScale ; //401.5686274509804
  Serial.print("Response Color - Inverted : "); Serial.println(rColor);

  rColor = 255 - rColor ;
  Serial.print("Response Color - Final : "); Serial.println(rColor);

  delay(500);

  return rColor ;

}

The pulses appear correct, just out of scale. Red items produce short Red pulses and so on.

I tried to correct for the shorter pulses by using the Typical Output Frequency (f0) found on page 4 of the data sheet. I'm not sure if this is the right use of this frequency output spec.

http://www.unihedron.com/projects/darksky/tcs230-e33.pdf

Lowering the max possible pulses per second from 100,400 to around 20,000 gave us a little more variation between RGB values, but still the output is nothing like the expected color.

Can anybody offer some insight as to why the TCS230 pulse count is far fewer than the TTB code expects and what can I do to fix either the pulse count or the scale? Kind regards.

Output from Measuring a Blue RFID Keyfob:
    divideForScale : 74
    Pulse Width : 673
    Response Color - Inverted : 9
    Respponse Color - Final : 246
    Red : 246
    **********************

divideForScale : 64
Pulse Width : 376
Response Color - Inverted : 5
Respponse Color - Final : 250
Blue : 250
**********************

divideForScale : 53
Pulse Width : 737
Response Color - Inverted : 13
Respponse Color - Final : 242
Green : 242
**********************

Connect S0 to 5V to get 100% OUTPUT FREQUENCY SCALING.

Currently, with S0 LOW and S1 HIGH, you get 2% OUTPUT FREQUENCY SCALING. Which would explain the 50 times to low values you get (100% / 2% = 50).


esp8266- how to use GPIO0 as an input? First, my setup:
I have an Arduino Uno with an Adafruit Audio Shield.  I have a Wemos D1 Mini controlling the project.

I need for the D1 to know when a file is playing.

I have a GPIO pin on the Uno programmed to be high when a file is playing.  Low otherwise.  I have two GPIO pins on the Wemos that are unused, D3 and D4 (GPIO0 and GPIO2).  (I use a divider circuit of a 10K over a 20K resistor to bring the 5V from the Uno down to 3v3 for the Wemos). D4 is already a problem because it has to be high to boot and the GPIO from the Uno is normally low. D3 (GPIO0) has to be high to boot and has an internal pullup.

Here's my problem.  How do I turn off the pullup on GPIO0? Even when the Uno GPIO is low (0V), the GPIO0 measures 2.4V, which my sketch sees as a logical 1.

Any tips would be appreciated.  (I thought of reversing the polarity on the Uno so that low=true, but even when the Uno is driving the pin low, the Wemos GPIO0 pin is still at 2.4V, so low-true logic won't work either.).

Don't use the voltage divider and never set the Uno pin HIGH.

Pull io 0 of esp8266 LOW with pinMode of the Uno pin.

pinMode(TO_ESP_IO0, OUTPUT); // sets the pin LOW

pinMode(TO_ESP_IO0, INPUT); // let it to the io0 pull-up resistor


16*2 1602A LCD not displaying any character or contrast, although correct wiring I've used my LCD display with a lot of small projects. Now it doesn't work anymore. Most of the diagrams you find online use resistors and potentiometers. However I never done that, but still got it to work nonetheless.

I tried different schematics, but none of them seem to work. So I'm thinking I broke my LCD somehow.

I'm pretty sure the schematic I'm currently using works. The backlight works but nothing is being printed.

Pictures of the project (Warning!! wire hell)

The LCD component is a blue 16x2 1602A v2.0 display.
All the components come from the official Arduino starter kit, except for the wires. Though I tested every single wire for continuity, to make absolutely sure the problem was not within the wires themselves.
Also, turning the potentiometer doesn't show any blocks, or change anything on the LCD as expected.

Code:

#include <LiquidCrystal.h>
//LiquidCrystal lcd(RS, E, D4, D5, D6, D7);
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  pinMode(6,OUTPUT);
  analogWrite(6,90); //sweetspot for backlight without using a potentiometer.

  lcd.begin(16, 2);
  //lcd.setCursor(0,0);
  lcd.print("hello, world!");
}

void loop() {
}

I'm not sure what's wrong, I tested everything I can think off.

I can upload more (cleaner) pictures if requested, I just didn't want to tear down my other project.

Ok so the problem were the wires.
Although I tested every single wire for continuity I went to the store and bought a brand new (expensive/not-from-aliexpress) pack of jumper wires. I rewired the entire project with the schematic and code that was posted in my question-post and it worked like a charm..

So I'm not sure what exactly caused the problem, but it was in the wire. I thought having continuity in a wire is like a 100% proof that the wire works properly. Maybe someone has an idea what could cause this?

So again, I only replaced the wires, not the schematic nor the code, with brand new ones and it worked perfectly.


Arduino Uno R3 stuck in DFU mode/Port not recognized I have an Arduino Uno R3 that is simultaneously stuck in DFU mode and won't be recognized as a port in the Arduino IDE on my Macbook Pro (El Capitan). Upon receiving power, the Arduino is automatically in DFU mode (I can use dfu-programmer via Terminal to access it, even though the Arduino is not 'recognized'), and by using the process normally reserved for entering DFU mode (connecting the two pins on the left side of the ICSP) the Arduino actually exits DFU mode. However, by neither entering or exiting DFU mode, the Arduino is still not 'recognized' as a port by the Arduino IDE. Prior to this happening, I had been attempting to flash files to the bootloader with success (I got this same predicament in that process previously once, but I do not know what happened differently).

Thanks,
wblegoboy

It sounds like your ATMega16U2 has lost its CDC/ACM firmware and is entering DFU mode by default to allow you to install firmware.

Installing the CDC/ACM firmware using dfu-programmer would get it working again.


Pulse generator with varying width I am trying to generate a square pulse with a fixed delay of 5 second between pulses and varying width of the pulse. The code I wrote so far generates a sequence of pulses every 5 seconds. Is it possible to generate one pulse (with varying width) every 5 seconds instead? Could you please help me with it?

const int pin =  11;

int i  = 0;

void setup() {
    Serial.begin(9600);
    pinMode(pin, OUTPUT);
}

void loop() {
    i = random(0 , 255);
    analogWrite(pin, i); // turn on LED
    delay(5000);
}

Simple but not fully accurate:

Turn on LED
Delay for the amount of pulse width (e.g. 20)
Turn off LED
Delay 5000 ms - pulse width (20) thus 4980 in this example

However, since turn on/off a LED will also take some time, this will take slightly more than 20 + 4980 = 5000 ms.

Thus better is:

Set time to a variable (use millis function).
Turn on LED
Wait until time >= pulse width
Turn off LED
Wait until time >= 5000


WebCam Face detection and tracking tutorial with Arduino Uno R3 and OpenCV 3.0 RC1 in Ubuntu 14.04 I try to make this Arduino Open CV tutorial for webcams. OpenCV 3.0 RC1 is compiled and installed. I also use Code::Blocks 13.12 as IDE. I am a newbie what comes to OpenCV and I do not know too much about Arduino either but here I am learning. Arduino IDE is 1.7.2. The tutorial is made for Windows 7 and software for this OS but I bet it is possible to repeat this in Ubuntu Linux 14.04 also.

So the tutorial is here:

http://duino4projects.com/face-detection-and-tracking-with-arduino-and-opencv/

When I try to compile and run the techbitarFaceDetection.cpp

the Code::Block IDE gives me following error:

  fatal error: Tserial.h: No such file or directory

So please tell me what to do next and how to fix this error.

Forget Tserial.h lib. To solve your problem (for serial communication) I sugest you to use "read/write from/to a file" programming method. The serial ports may be written to just like you are writing in a file. In the facedetect.cpp (OpenCV's example), in the detectAndDraw() function (I'm using OpenCV 3.0) add: unsigned char MSB[1] = {0}; //
    unsigned char LSB[1] = {0}; //
    char serialPortFilename[]="/dev/ttyACM0";
    FILE *serPort = fopen(serialPortFilename, "w"); //

than add:

LSB[0]=r->x & 0xff;//
    MSB[0]=(r->x >>8) & 0xff;//

    fwrite((const void*)MSB,sizeof(unsigned char),sizeof(MSB),serPort);//
fwrite((const void*)LSB,sizeof(unsigned char),sizeof(LSB),serPort);//

LSB[0]=r->y & 0xff;//
    MSB[0]=(r->y >>8) & 0xff;//

    fwrite((const void*)MSB,sizeof(unsigned char),sizeof(MSB),serPort);//
    fwrite((const void*)LSB,sizeof(unsigned char),sizeof(LSB),serPort);//

into the if (0.75 < aspect_ratio && aspect_ratio < 1.3) statement.

Finally don't forget to close the file

fclose(serPort);

Hope this will work for you!


ESPAsyncWebServer how do you escape the % character? % characters are used for template processing but I want it to just send the % through. How do you tell it to do that?

You'd use %% to get a single % as output.

From the source code: double percent sign encountered, this is single percent sign escaped.


parallel communication simulation problem Hi I am trying to send data(1 byte) from one arduino to another using parallel communication(a bus of 8 connections) and not using any library. However, the problem is the data gets corrupt all the time and what I am supposed to receive at receiver arduino is not what I send. The protocol that I made up is similar to uart protocol. There is ES pin and when it is low, transmission is started and when it is high, the transmission is ended. I think the problem could be related to wires that I use to connect two arduinos. There could be some noise induced that could flip bits in wires or the code is problematic. I am posting my code. Maybe you can help me get through this and help me to resolve my problem.
Sender code:
#define ES 8 //enable sampling
#define B0 0 //Bus 0
#define B1 1
#define B2 2
#define B3 3
#define B4 4
#define B5 5
#define B6 6
#define B7 7
const char dataToBeSent = 'C';
bool data_bit;

void setup() {
  pinMode(ES,OUTPUT);
  pinMode(B0,OUTPUT);
  pinMode(B1,OUTPUT);
  pinMode(B2,OUTPUT);
  pinMode(B3,OUTPUT);
  pinMode(B4,OUTPUT);
  pinMode(B5,OUTPUT);
  pinMode(B6,OUTPUT);
  pinMode(B7,OUTPUT);
  digitalWrite(ES,HIGH);
  delay(3000);
}
void loop() {

 digitalWrite(ES,LOW); //transmission is started
 delay(10);

 for(int i = 0 ; i<8 ; i++){
    data_bit = dataToBeSent & (0x80 >> i);
    digitalWrite(i,data_bit);
 }
  delay(10);
  digitalWrite(ES,HIGH); //end transmission
  while(true){}
}

Receiver code:
#define ES 8 //enable sampling
#define B0 0 //Bus 0
#define B1 1
#define B2 2
#define B3 3
#define B4 4
#define B5 5
#define B6 6
#define B7 7

char rx_data;
byte rx_byte= 0;
bool rx_pin;

void setup() {
  Serial.begin(9600);
  pinMode(ES,INPUT);
  pinMode(B0,INPUT);
  pinMode(B1,INPUT);
  pinMode(B2,INPUT);
  pinMode(B3,INPUT);
  pinMode(B4,INPUT);
  pinMode(B5,INPUT);
  pinMode(B6,INPUT);
  pinMode(B7,INPUT);
  delay(1000);

}

void loop() {

  byte rx_byte= 0;

  while(digitalRead(ES) == HIGH){}
  delay(15);

  for(int i = 0 ; i<8 ; i++){
    rx_pin = digitalRead(i);
    Serial.print(rx_pin);
    if(rx_pin == 1){
      rx_byte |= (0x80 >> i);
    }
  }

 rx_data = rx_byte ;

 Serial.print("Received data: ");
 Serial.println(rx_data);

 delay(15);

 while(digitalRead(ES)== HIGH){}

}

You problem is that you are only using one phase of your "ES" clock, when in fact you should be using two.
In the first phase, where ES is high, is where you set the IO pins to represent your transmitted byte. Only once that is done can you then progress to the second phase, where ES is low, to indicate to the receiver that "I have set up my outputs, it's now time for you to read them".
So your transmitted code would flow like:

Set ES HIGH
Set output pins to represent the byte
Set ES LOW
Delay
Set ES HIGH

If you look at any timing diagrams for any protocol there will be places where the data is being written to the bus, and places where the data is considered stable and able to be read by the receiver. It's the job of the clock signal to indicate where these points in the protocol - to synchronise the receiver.
For example, here is the Centronics (parallel port) protocol:

The data changes while nStrobe is HIGH, and only when that data is "settled" is nStrobe brought LOW to tell the receiver it can read the data. Once nStrobe is taken HIGH again the data is changed to the next byte to transmit.


Assembling a float from an array of bytes I would like to convert an array of bytes, received from serial, to a float.

Let's consider this exemple. I'm sending 0.12 byte-wise from an Android application. The conversion from float to array of bytes in the Android side is handled by this function

public static byte [] float2Bytes(float value)
    {
        return ByteBuffer.allocate(4)./*order(ByteOrder.LITTLE_ENDIAN).*/putFloat(value).array();
    }

When bytes arrive, they are stored in an array and the assembled.

hiBytew1 = bufferBytes[9];
//Serial.println(hiBytew1);
loBytew1 = bufferBytes[10];
//Serial.println(loBytew1);
hiBytew2 = bufferBytes[11];
//Serial.println(hiBytew2);
loBytew2 = bufferBytes[12];
//Serial.println(loBytew2);
float conAck = assemble(hiBytew1, loBytew1, hiBytew2,loBytew2);

How can I achieve this kind of conversion assuming that bytes are received in the correct order?

Just cast the pointer.

float conAck = *((float*)(bufferBytes + 9));


Problems with substring loop Hey folks … I was hoping some of you might cast your eye over my code.

It splits up a string read from EEprom into an array of separate strings. Based on String length information stored in a separate array. (tempArray[])

It reads fine … and also seems to process fine (ie. it does turn one long string into separate array items)      for some reason it stops working no the 8th array item?

The splitting code (problem) starts on line 80 and i have included the output above it in comments.

http://pastebin.com/Ax4R6t6J   << Full code also available here.

void reJigFromMemory(){

  Serial.print("Eeprom read 1 :");
  Serial.println(eepromReadOne);
  Serial.print("EEprom read 2 :");
  Serial.println(eepromReadTwo);
  String tempArray[10];

  int charLength=eepromReadOne.length()+1;
  char charBuff[charLength];
  eepromReadOne.toCharArray(charBuff, charLength);

  //// GET MEMORY LOCATIONS
  /*
converts long string of numbers:
   13161717171717252533
   into separate strings:
   13
   16
   17
   17
   17
   17
   17
   25
   25
   33

   And stores them in an array.
   */
  for (int i = 0; i <10 ; i++){
    tempArray[i]+=charBuff[i*2];
    tempArray[i]+=charBuff[(i*2)+1];
    Serial.print("I just translated :");
    Serial.println(tempArray[i]);
  }
  /// GET THE STRINGS USING THE ABOVE ARRAYS
  /*
converts long list of data ie:
   |0|Bingo#999#|1|Retest2#9222#|2|Retest3#92299#|3|Retest4#99339#|4|Retest5#95599#|5|Retest6#96699#|6|Retest7#99119#|7|User Defined eighth#0#|8|User Defined ninth #0#|9|User Defined tenth (last) .#0#

   into individual array strings:

   From Number = :0
   To number : 13
   Record 0 :          |0|Bingo#999#
   From Number = :13
   To number : 29
   Record 1 :          |1|Retest2#9222#
   From Number = :29
   To number : 46
   Record 2 :          |2|Retest3#92299#
   From Number = :46
   To number : 63
   Record 3:           |3|Retest4#99339#
   From Number = :63
   To number : 80
   Record 4:           |4|Retest5#95599#
   From Number = :80
   To number : 97
   Record 5:           |5|Retest6#96699#
   From Number = :97
   To number : 114
   Record 6 :          |6|Retest7#99119#
   From Number = :114
   To number : 139
   Record 7 :               <<<<<< THIS ONE IS MISSING ? WHY?
   From Number = :139
   To number : 164
   Record 8 :               <<<<<< THIS ONE IS MISSING ? WHY?
   From Number = :164
   To number : 197
   Record 9 :               <<<<<< THIS ONE IS MISSING ? WHY?

   */
  String tempArray2[10];
  int fromLocation = 0;
  int toLocation=0;

  for (int i = 0; i <10 ; i++){                 /////// LINE 80

    toLocation += tempArray[i].toInt();

    fromLocation += tempArray[i-1].toInt();
    tempArray2[i]=eepromReadTwo.substring(fromLocation,toLocation);
    Serial.print("From Number = :");
    Serial.println(fromLocation);
    Serial.print("To number : ");
    Serial.println(toLocation);
    Serial.print("I just translated :");
    Serial.println(tempArray2[i]);

  }
}

Your 2nd for loop should look something like this:

int fromLocation = 0;
int toLocation=0;

for (int i = 0; i <10 ; i++)
{                 /////// LINE 80

    toLocation += tempArray[i].toInt();

    tempArray2[i]=eepromReadTwo.substring(fromLocation,toLocation);
    Serial.print("From Number = :");
    Serial.println(fromLocation);
    Serial.print("To number : ");
    Serial.println(toLocation);
    Serial.print("I just translated :");
    Serial.println(tempArray2[i]);
    fromLocation += tempArray[i].toInt();
  }
}

On the first pass through the loop, fromLocation is 0. toLocation starts at 0 and gets the value in tempArray2[0] added to it.

After extracting a string, you add the current array value to fromLocation to advance the pointer to the beginning of the next string.

Note that String objects are very inefficient way to save 2 digit numbers. It would be better use an array of ints, and write code that extracts 2 characters at a time into int values.

With only 20 String objects it's not a huge deal, but bear in mind that String objects take a lot of memory overhead on a memory-starved platform like an Arduino. Better to learn how to use C strings.


esp8266-12e Nodemcu 1.0 board not starting uploaded data sketch from Arduino IDE I've uploaded a sketch from the Arduino IDE to my (Amica) esp8266-12e board with the sketch data upload tool (ESP8266FS). This goes without any errors or problems. However, the code is never executed, it's like that the code isn't even on the board, it does nothing. I've tried flashing the firmware several times but this does not help. Depending on the installed firmware I get different messages on the serial monitor such as

NodeMCU 0.9.5 build 20150318  powered by Lua 5.1.4
lua: cannot open init.lua

or

Ai-Thinker Technology Co.,Ltd.
invalid

So installing different kinds of firmware is not the problem here. What did I do wrong which causes the board to 'ignore' the uploaded data sketch?

It appears that you have not uploaded the Arduino Core Software to your ESP8266 device because you are getting messages from the LUA interpreter which is overwritten when you install the Arduino Core Software.
The pre-requisites for using ESP8266FS to load sketches are here: ESP8266FS


Arduino wont start up and it wasnt succesfully booted in any time it was downloaded I know the title sounds stupid but I never found a question like mine so I wanted to be specific because I downloaded the Arduino IDE to start my first project and I never managed to boot it because nothing happens when I try and I also tried every kind of thing to make it work I could think of. I reinstalled it, downloaded from another link like the zip version and also tried the windows repairtool. I also tried to boot it as admin several times but nothing changed anything. I did all of that yesterday and today when I started the Pc and retried I atleast saw something of a bootingscreen of the app so I thought I just had to restart but then it just went off again and the pain from yesterday began once again.

´´
I own windows 7 64 bit
´´
and tried every download except the one for windows 8.1 and 10

I saw a question about Arduino IDE not starting but this person atleast got any response from the program and the tipp they suggested with the folder in

´´
AppData/Lokal where you delete broken data to reinstall doesnt work too because the arduino folder doesnt even excist in the whole appdata section.
´´

´´
Windows repair tool said the program is not compatible, only in Windows xp (service pack 2) version but in compatibility mode nothing changes
´´

Ok thew this question is really long but I gave my best to explain everything I could about my problem so I really hope somebody could help me on my problem so I didnt waste my 45 Euro and time on tech stuff that I cant use

one thing to meantion I have left is that i bought my stuff from a teacher (Erik Verbene) on the internet

but that doesnt matter because it is your program that is not working so
yeah
hope somebody can help me out on this dilemma

The Arduino IDE is written in Java. It's 100% platform independent, so the version that you download makes no real difference.

The most likely culprit is the version of Java that is installed in your computer.  I am not sure off hand what versions of Java the Arduino IDE works with, but for certain version 8 will be your best bet.  Make sure that you have the latest version of Java 8 installed.  If you have any older version installed you should uninstall it and replace it with Java 8.  I'm not sure how the IDE works with newer versions than 8, but removing anything newer than 8 and installing Java 8 may be a good idea.


Is it possible to make an Arduino send signals to an RC receiver? I have found bunch of information about how to hack an RC car with a PCB; and how to control an Arduino from a receiver. Also how to run a servo from an Arduino, but I'm looking for a way to make an Arduino send signals to a 27 MHz 3 channel receiver, Using three potentiometers to decide servo location.

Is there any information about this somewhere? - I have an old transmitter lying around if needed.

Links, pointers - anything is welcome.

[It does not have to be 27 MHz AM, it is just what I have on the shelve, without investing in new gear]

The easiest way would be to open up the transmitter, desolder the potentiometer used for the stick and solder the cables to Arduino's PWM instead. Then use analogWrite() to simulate stick position. If your TX would use that potentiometer with more than 5 V, you'll not able to use full ppm values. A RC or a RCL filter may be needed between PWM output and RC input to "smooth" the PWM into an analog signal. There are a lot of online calculator to find good R, C and L to polish your signal.

This assuming your TX is using potentiometer like stick; if it is a really cheap one, it may be using buttons. If this is the case, then you connect a transistor in parallel with the button, that way you can keep manual button.

Another way is to program your Arduino to look for ppm signal (normally 50 Hz with high starting value with a period from 500 to 2000 µs) and then look for this signal into the Tx PCB; if found cut the trace of the generator and solder your cable from Arduino. I've seen around a lot of libraries outputting ppm (they are used on drones to mix single ppm channel back to PPM to use only one pin from logic board without having to hack standard RX


I am tying to split a float variable into bytes and then re combine to the original float Here is the code I am currently using, there have been many and various alternatives I have tried all so far without success, this being the latest incarnation sitting within my main program loop (void loop)...
// get temperature from Dallas Temperature Sensor
  sensors.requestTemperatures();
  sen0_data = sensors.getTempC(sensor_0_address);             // read temperature sensor0

// split float
  float f1 = sen0_data;
  byte* fb = (byte*) &f1;

  Serial.println(f1);
  Serial.println(fb[0]);    // Take a look at the bytes
  Serial.println(fb[1]);
  Serial.println(fb[2]);
  Serial.println(fb[3]);

// rebuild float
  temp = (fb[0] << 24) + (fb[1] << 16) + (fb[2] << 8) + (fb[3]);
  Serial.println(temp);

Now for the result as seen in the serial monitor - original float, split byte 0, byte 1, byte 2, byte 3, and finally rebuilt float. What am I doing wrong? as no doubt can be seen from the dirty coding I am a relative newbe
The starting float value -127.00 is because I currently have no temperature sensor connected to the Arduino, but I would still expect the rebuilt float to be the same and not -318.00. Even if I connect a sensor the rebuilt float does not mirror the original...
-127.00
0
0
254
194
-318.00

I look forward to any advice...
Regards,
Simon.

I have been told to be careful about a simple casting of non-byte variables to an array of bytes because there's no guarantee that the memory allocated for certain data types will be contiguous. I.e., the bytes might be spread out to non-adjacent spots in memory. For example, I was encouraged to use a union to convert a unit64_t, which is 8 bytes, to a byte array on an ESP8266. This involves declaring a union type:
union u64_bytes {
  uint64_t u64;
  uint8_t u8[sizeof(uint64_t)];
};

And then you can use this to convert either way, for example:
  uint64_t myNum = 1;
  u64_bytes splitNum;
  splitNum.u64 = myNum;
  // now i can loop thru the bytes
  for(int i=0; i<sizeof(uint64_t); i++) {
      uint8_t myByte = splitNum.u8[i];
      Serial.print("byte ");
      Serial.print(i);
      Serial.print(" is ");
      Serial.println(myByte);
  }
  // or just refer to individual bytes
  uint8_t oneByte = splitNum.u8[0];

  // you can also take bytes and convert the other way
  u64_bytes rebuilt;
  for(int i=0; i<sizeof(splitNum); i++) {
      rebuilt.u8[i] = splitNum.u8[i];
  }

  Serial.print("The rebuilt value is ");
  Serial.println(rebuilt.u64);

EDIT: I added some code to show conversion the other way.
That said, it's probably pretty safe in your case to use the bitwise operators you are using. A float is in all likelihood 4 bytes on your hardware, and most hardware allocates memory these days in four-byte blocks.
HOWEVER you still have to take into account the Endianness of the system when it stores values. The basic idea is that if you have four bytes that represent one number, are the most significant bytes first or are the least significant bytes first?
For example, if you are talking about a four byte unsigned integer the number 1, aka 0x00000001, it would be stored like this in Big-Endian hexadecimal:
0x00 0x00 0x00 0x01

But on little endian hardware (like mine) the order is different. They put the least significant bytes first in memory like so:
0x01 0x00 0x00 0x00

This might be very confusing, but the bottom line is you might have to think twice about what the byte order is for your data. I'd add that floats and signed integers might have some aspects that surprise you, and when you try and communicate any information over a serial line (SPI, I2C, etc.) or over a network then you might have to worry about what sort of conversions are happening. You must have to make sure that you know what order your bytes are and you unpack them in a way that's appropriate to the way you packed them.
Lastly, I would encourage you maybe think about (and possibly elaborate) what you are hoping to accomplish by taking apart a float into bytes? If you don't know about the structure of bits inside a float, you would need to get better acquainted with that before you start monkeying with the bytes inside it.
EDIT 2: here's an example where I use a struct to convert a float:
  union float_bytes {
    float flt;
    uint8_t u8[sizeof(float)];
  };

  float myNum = -127.0;
  float_bytes splitNum;
  splitNum.flt = myNum;
  // now i can loop thru the bytes
  for(int i=0; i<sizeof(splitNum); i++) {
      uint8_t myByte = splitNum.u8[i];
      Serial.print("byte ");
      Serial.print(i);
      Serial.print(" is ");
      Serial.println(myByte);
  }
  // or just refer to individual bytes
  uint8_t oneByte = splitNum.u8[0];

  // you can also take bytes and convert the other way
  float_bytes rebuilt;
  for(int i=0; i<sizeof(splitNum); i++) {
      rebuilt.u8[i] = splitNum.u8[i];
  }

  Serial.print("The rebuilt value is ");
  Serial.println(rebuilt.flt);


Pca9685 & WS2818B, 1 Nano Arduino n00b here. I currently have an Arduino Nano set up to run 6 servos from a PCA9685 board. I'm looking to add 6 switches and 6 LED indicators to switch servo positions. What I'm curious about is how to connect the WS2818B. I know they can be run through I2C, but the Pca9685 is using those wires. Can I run both the pca9685 and the LEDs through I2C or just run each LED through a separate pin?

I was looking at WS2818B datasheet, they do not use i2c. It just needs a single ( dedicated) pin to receive the color/brightness commands.


How many transistors can be connected to Arduino pins? How many TIP122 transistors can I connect to the Arduino digital pins? The Atmega328p datasheet states that the pins can source a total of 200 mA, while other documents state 40 mA per pin.

In the following circuit layout, I connected six TIP122 transistors with 2.2  kΩ  base resistors. I used an LM338 regulator to power the Arduino IC and other functions.

The TIP122 is a 100V, 5A, Hfe at least 1000, darlington NPN transistor. With the base resistor of 2k2, that is about 1 or 2 mA per pin. You don't have to worry about a few mA.

To answer your question: "How many transistor can be connected to arduino pins?", that will be about 100.

Why do you use TIP122 ? They have a voltage drop. Logic level mosfets have a very little voltage drop and thus they stay a lot cooler.
Mosfets leak at a higher voltage. If you need to operate near 100V, there are IGBT transistors for that.

Make sure that the high current through the TIP122 at the emitter does not disturb the GND of the ATmega chip. You have to design your circuit board to avoid such troubles.


A good place to begin with Arduino? So I bought the Arduino starter kit a few weeks ago and I've done a few of the projects in the book supplied with the set. Unfortunately the book is quite poor, with inaccurate explanations and sometimes no explanation behind what they want you to do in the projects.

So I'd like to know what people would reccomend? I found 2 well reviewed books; Arduino for Dummies and Arduino Workshop, but I'm torn which to take. So I'm asking in here in hope that I can save time and money on buying and reading a good book from the start.

I'm a programmer by profession and also know a bit of physics, but have little experience with electronics.

I have read a lot of materials, watched many videos and completed lots of searching to find great stater Arduino lessons. By far the best place I found was

opensourcehardwaregroup.com
Free to start learning Arduino site

Free initial course and if you like the lessons you can pay a small fee to get to the advanced course. You will learn a lot!


Trouble uploading sketch / error in sketch I am following this tutorial of a very basic serial communication between 2 arduino unos.

I have made the connections as given and connected the arduino unos to 2 separate laptops via USB.

Code1:

char mystr[3] = "Hello"; //String data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600);
}

void loop() {
  Serial.write(mystr,5); //Write the serial data
  delay(1000);
}

Code 2:

char mystr[5]; //Initialized variable to store recieved data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600);
}

void loop() {
  Serial.readBytes(mystr,5); //Read the serial data and store in var
  delay(1000);
}

Error on arduino following code 1:

Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

Sketch uses 1602 bytes (4%) of program storage space. Maximum is 32256 bytes.
Global variables use 188 bytes (9%) of dynamic memory, leaving 1860 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Arduino running code 2 is stuck on the uploading and does not fininsh uploading.

The solutions on the internet only talk of the scenarios where the arduino is having trouble communication with the computer and so the solutions given are:

check com port
check that correct board is selected
do not insert the arduinos in usb 3
press reset button

None of these is my problem as I have checked them all. The arduinos themselves are working fine. I have a very strong feeling that there is a problem with the pins 0 and 1, i.e. with serial comm.

Please help.

I am guessing you have connected 2 arduinos together using their hardware serial ports while uploading. This cause uploading to fail as those ports are getting two signals at the same time.

Break this connection before upload and then it should work. You can reconnect them after upload.

If you want to avoid this you can use different pins with software serials for communication.

Also consider using Serial.available() on the reading end to see if there is data to be read.


Necessary sampling rate I'm using an Arduino pro mini to receive the analog signals from three sensors. I was wondering what sampling rate I should sample at in order to properly represent these signals. I know it should be twice the highest analog frequency, but I'm not sure what frequency theses sensors operate in. They're an ECG, a 3 axis accelerometer, and a stretch resistor respectively. To my knowledge, Arduino defaults at a sampling rate of 10kHz, which I believe should be more than enough to quantize the sensor signals. I'm then sending these signals out using bluetooth mate to an android phone. Is there a specific baudrate I should send the data at?

Here is the initialization of my code:

void setup()
{
  Serial.begin(9600);
  bluetooth.begin(115200);
  bluetooth.print("$$$");
  delay(100);
  bluetooth.println("U,9600,N");
  bluetooth.begin(9600);
  setTime(0);
}

Thanks so much

The sampling frequency you are referring to (twice the highest frequency) is for capturing waves, but is not really a concern for the sensors you are using and the types of data they are used to measure.

If you wanted to analyse the magnitude of a 40kHz vibration in a structure, you should worry about sampling rates on your accelerometer; however, if you want to measure the accelerometers current angle to the ground (assuming its not accelerating), you only need to take one sample.

With the ECG, there will be a signal among all the analog voltages you read of a heartbeat (I'm assuming its hooked up to a person). This signal will never get much over 200 beats per minute, or 3.3 Hz. To capture a 3.3Hz signal you need a minimum sampling rate of 6.6Hz, which as still incredibly slow. The same goes for capturing a gait with your accelerometer.

If you capture the analog voltage of your sensors output with analogRead 100 times a second, you should have a very clear and well defined view of the very low frequency signals you are trying to track, and should not have any issues with transferring that much information over serial.

5, 16 bit values can theoretically be sent at 120Hz over 9600 baud, and its very easy to use faster speeds then that if you want more information.


ESP8266MOD does not respond to my Uno (Custom board) AT+RST command This is my very first project with a Uno board and ESP module. I have some experience with 8051 uP. I'd like some guidance in addressing my issue.

Objective:

To connect ESP8266MOD to my wifi network and send a TCP message to my HOME_SERVER whenever required.

Hardware Module:
UNO (Induino R5 Arduino R3 USB Clone Board) --> level shifter  --> ESP8266MOD

As a first step, I am trying to send AT+RST command from the Uno to the connected ESP. But there is no response from the ESP. However, I am able to notice a LED blink on the ESP, whenever there is TXD operation in my Uno.

Hardware Connection:

UNO - Uses USB Power supply from laptop
ESP8266MOD- Uses 3 1.5V AA Batteries

                 ||
    UNO PINS       TXD      RXD     5V GND
                    ||      ||      ||
    LEVELSHIFTER     >>RXI   <<TXO  HV,GND
                        ||      ||
                    RXO<<    TXI>>  LV,GND
                    ||      ||      ||
    ESP8266MOD      RXD     TXD     3.3V,GND

ESP8266MOD Settings:
    CH_PD ->> 3.3V
    GPIO2 ->> 3.3V
    GPIO0 ->> GND
    GPIO15->> GND

Uno Code:

#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  delay(3000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  delay(3000);
  ESP8266.println("AT+RST");
  delay(30);
  String response = "";
  while(ESP8266.available()) {
    char c = ESP8266.read();
    response+=c;
  }
  if(response != "") {
    Serial.println(response);
  } else {
    Serial.println("Empty\r\n");
  }
}

Output Video: Output video view

  -->

If it is a new ESP module, your problem is quite likely a baud rate mismatch, since you are seeing an LED response but getting no reply.

The last batch of ESP-01s I received defaulted to 115200 baud, but that is too fast for SoftwareSerial (SS). You'll need to change it to 9600. My answer to a related question describes one way to change it.

You could also change it with SS. You'd have to start off SS at 115200 baud, which will usually transmit OK; just ignore the apparent garbage that comes back. Then change SS's baud rate to 9600 to match, and you should have solid communication.

These are the three commands you need to send the ESP to accomplish the change:

AT                             # ESP should respond "OK"
AT+RST                         # Resets the ESP
AT+UART_DEF=9600,8,1,0,0       # Sets ESP UART: 9600,N,8,1,no flow ctl

Note: Your module might have been preset to some other rate than 115200, in which case you'll have to try various rates until you can get an intelligible reply. Once you do, set the default rate to 9600.


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

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.


Serial loopback not working with jumper wires connected I'm a beginner to Arduino programming. Before attempting anything more complex I'm trying to get some very basic functionality first, so using some of the sketchbook examples I'm trying to get the most basic serial loopback working. I used the SerialEvent sketch as a reference point to come up with this:

String inputString = "";
bool stringComplete = false;
int inByte = 0;

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // wait for serial port to connect. Needed for native USB port only
  while (!Serial) {
    ;
  }
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
  Serial.println("Hello world\n");
}

void loop() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
  if (stringComplete) {
    Serial.println(inputString);
    inputString = "";
    stringComplete = false;
  }
}

When I flash that image to the Arduino and then open the Serial monitor, everything appears to work fine. As pictured below, whatever I type gets echoed back to me after pressing Enter:

However, it's a different story when I connect the TX and RX pins on the board, as pictured here:

As soon as I do that, the serial communication becomes totally non-responsive. It still prints out "Hello world" at the beginning, but it no longer echoes back the messages that get sent in, as you can see here:

I should say that even when it is no longer echoing messages back, the yellow "RX" light on the board does still briefly light up when I press Enter. But the "TX" light doesn't. Note that both lights light up if I unplug the jumper wire.

It seems to me that what I'm trying to do here is a very simple thing, that really shouldn't be this hard. Is there something obvious I'm missing? Any advice?

I can not comment, it turns out that this example that you are working is not very suitable, since the RX and TX are directly connected to the USB connection (for Arduino UNO), that is, you can only use these pins as long as it is loaded from Sketch uses An external power supply to connect the Arduino, my recommendation is to work if you have a sensor to verify the transmission of data by serial port. Greetings


Reverse DC motor direction every second automatically I have the Arduino Starter Kit and I'm on project 10 Zoetrope. I've removed the switch that changes the direction as I don't want the reverse to happen when I press a switch. I want the reverse to happen based on time.

For example using code, I want the reverse to happen every second (the motor moves clockwise for the first second, counterclockwise for the next second, clockwise for the third second etc.)

I've search for solutions but I haven't found anything yet. I had no luck with the millis function as well.

Consider code of the following form.

// Declare some globals
byte direction=0, second, prev=0;

void loop() {
  second = millis()/1000;
  if (prev != second) {
    prev = second;
    direction = second & 1; // Direction is 0 or 1
    OutputTheNewDirection(direction);
  }

More generally, suppose you want to make a pattern of clockwise for j time units, alternating with counterclockwise for k time units.  Suppose a time unit is m milliseconds long.  You can use code as in the following example, where m is 500, j is 10, and k is 1.

// Declare some globals and constants
byte direction=0, tunit, prev=0;
enum { m=500, j=10, k=1 };

void loop() {
  tunit = (millis()/m) % (j+k);
  if (prev != tunit) {
    prev = tunit;
    direction = tunit < j; // Direction is 0 or 1
    OutputTheNewDirection(direction);
  }


How to make a dynamic menu with a sub-menu ( Arduino mega or Arduino Uno) I have an arduino mega with a LCD shield (from keyestudio KS2056). I am trying to create a menu with a submenu that would have addable and removable strings based on inputs from a RFID scanner(addable) and buttons(to remove selected strings). I am not so sure how I could possibly do this. Any assistance would be great.

I will skip the RFID part, that is unrelated to the menu.

What you can do is creating two variables:

int menuLevel1 = 0;
int menuLevel2 = 0;

Assuming you have 2 levels, if you have more levels consider an array.

Now you can print the screen based on the values of these two variables (use a switch statement for menuLevel1 which calls new functions, each with their own switch statement for menuLevel2.

Note there are more solutions, but this is a rather simple solution.

The RFID scanner just changes the values, so going to a different menu screen.

A slightly different solution is to not use numbers, but an enumeration (or one for the main level, and x for the second level etc). This can add up, so you can also use a single enum value (with one entry per possible menu page).

The last example looks like:

enum EMenuPage
{
   StartPage,
   MainMenu,
   FirstMenu,
   DisplayX,
   SetY,
   …
}

enum EMenuPage _menuPage;

Displaying like:

switch (_menuPage)
{
case StartPage:
   // Fill LCD with start page
   break;

case …

And when an RFID messages comes in:

if (RFID... == Back)
{
  _menuPage = MainMenu;
}
else …


#ifdef / #include CPP issue I'm developing a sketch which I need to run on an Uno (for debug) and a Gemma (as the target).  Adafruit has their own Wire library (TinyWireM) which I was planning on using on the Gemma.  Thus, I was trying to use #if's to automatically include the correct library for the given target board.  However, it appears that the TinyWireM include files is always included even if the AVR_ATtiny85  macro symbol is undefined (I get many undefined symbols reported inside the Arduino\libraries\TinyWireM-master\USI_TWI_Master.cpp file).  If I comment out the TinyWireM.h include statement (inside the #if define statement), then it compiles fine.  Code example below.

So why isn't this include statement being skipped?  I'm at a loss.  Anyone have any thoughts?

Thx all.

Mike

#undef __AVR_ATtiny85__        // Debug only - making sure not defined.

#if defined (__AVR_ATtiny85__)
  #include <TinyWireM.h>    // Seems this file is still being included and
                          // must comment out this line when compiling
                          // code for an UNO.  This should not be necessary
                          // given __AVR_ATtiny85__ is not defined.
#else
  #include <Wire.h>         // This is the Wire library for the Uno.
#endif

void setup() { }

void loop() { }

The Arduino IDE does its own non-standard preprocessing before the C++ preprocessor/compiler is invoked. One of the main purposes for this is to detect #include directives which refer to libraries so it can link them properly.

My guess would be that part of this procedure ends up moving all #include lines to the start of the file. In the code you've posted, that means I think it's being moved outside the whole #if/#else structure.

In most cases, you can avoid the Arduino IDE trickery by moving things into a separate header or source file. Unfortunately though, doing that means it may not link the libraries properly. As such, the easiest solution may be to switch to a 3rd party IDE which has Arduino support (e.g. Eclipse).