texts: ESP8266 compilation error: "previous declaration of 'HTTPMethod HTTP_HEAD'"

texts:
I have an ESP8266 program that used to work but is now failing to compile with this error:

C:\...\Arduino\libraries\WiFiManager/WiFiManager.h:25:24: note: in expansion of macro 'PROGMEM'

 const char HTTP_HEAD[] PROGMEM            = "<!DOCTYPE html><html lang=\"en\"><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/><title>{v}</title>";

                        ^

In file included from C:\...\MyEsp.ino:14:0:

C:\...AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WebServer\src/ESP8266WebServer.h:33:39: error: previous declaration of 'HTTPMethod HTTP_HEAD'

 enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };
                                   ^

I don't recall changing anything, except maybe updating some libraries. Any ideas what could be causing this?  Here are my includes from the ESP8266 program:

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

#include <DNSServer.h>            //Local DNS Server used for redirecting all requests to the configuration portal
#include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager WiFi Configuration Magic

#define SERIAL_BUFFER_SIZE 256


texts: AVRdude + Arduino leonardo: can't flash over bootloader, not in sync: resp=0x3f

texts:
I would like to program an arduino leonardo board with atmega32u4 on win8.1 x64.
I have the latest AVRdude.
I installed the necessary drivers, after reset it can be enter programming mode, and I can program with arduino studio.
But now, the avrude gives this:

    C:\>avrdude -carduino -P COM5 -n -p m32u4 -b19200 -v

avrdude: Version 6.1-svn-20131205, compiled on Dec  5 2013 at 17:34:22
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "c:\GNU_GCC_ARM\bin\avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x3f

avrdude done.  Thank you.

I tried also with 57600 baud.
Any idea? Thanks.


texts: FastLED Rainbow Wheel Fade on an 8 Pin RGB Matrix

texts:
So, I have an RGB matrix (using PL9823 LEDs) that's 32 x 8 that I'm trying to run a circular spinning rainbow pattern across in a continuous loop. Now, there's lots of code online for different ways to do this with a traditional daisy chained matrix, but I have mine set up to where each of the 8 rows of LEDs goes to a different pin on my Teensy 3.2 controller (pins 4-11) and I have no idea how to get this (or any) rainbow effect working on it. I'm using the FastLED library and this is how I have the program set up to address individual pins as the different rows of LEDs:

#include "FastLED.h"
#define LED_TYPE PL9823
#define NUM_STRIPS 8
#define NUM_LEDS_PER_STRIP 64
#define NUM_LEDS NUM_LEDS_PER_STRIP * NUM_STRIPS

#define COLOR_ORDER GRB

uint8_t hue = 0;

CRGB leds[NUM_STRIPS * NUM_LEDS_PER_STRIP];
CRGB row_1[64];
CRGB row_2[64];
CRGB row_3[64];
CRGB row_4[64];
CRGB row_5[64];
CRGB row_6[64];
CRGB row_7[64];
CRGB row_8[64];

void setup() {
  FastLED.addLeds<PL9823, 4>(row_1, 0, NUM_LEDS_PER_STRIP);
  FastLED.addLeds<PL9823, 5>(row_2, 0, NUM_LEDS_PER_STRIP);
  FastLED.addLeds<PL9823, 6>(row_3, 0, NUM_LEDS_PER_STRIP);
  FastLED.addLeds<PL9823, 7>(row_4, 0, NUM_LEDS_PER_STRIP);
  FastLED.addLeds<PL9823, 8>(row_5, 0, NUM_LEDS_PER_STRIP);
  FastLED.addLeds<PL9823, 9>(row_6, 0, NUM_LEDS_PER_STRIP);
  FastLED.addLeds<PL9823, 10>(row_7, 0, NUM_LEDS_PER_STRIP);
  FastLED.addLeds<PL9823, 11>(row_8, 0, NUM_LEDS_PER_STRIP);

}

Does anyone know how I can make this setup run a spinning wheel of fading color values in the form of a spinning rainbow? I'm hoping to use suggestions as a place to start to build other patterns with and without rainbows as well and I'm a bit of a noob, so an explanation is appreciated.


texts: Do we really need to upload Arduino bootloader for new Atmega IC

texts:
I am using Atmega328p in my circuit. I will be programming this IC using Arduino. But because this is a PCB, so I will programming using USBasp programmer. So before uploading code as upload using programmer, I will select my arduino board in board select menu and then I will select USBasp as my programmer. But I want to know that is it really necessary to burn bootloader on a new Atmega328p IC. On some page, they say you do not require it. But some say, its necessary because you will be using Arduino functions like Serial.Begin() etc.

So I want to know what does this bootloader contains. Do I really need it. Can I directly upload my code using programmer. Can anyone please explain this to me.?


texts: MCU Recommendations for Audio Pitch Shifting

texts:
I'm looking to use a MCU for audio sampling. I want to sample incoming audio and pitch shift it (without speeding it up/slowing it down). A bit about the build. I'm planning to make a circuit board that can take in a single audio source and output three or four different pitch-shifted sounds in real time, with each output being its own pitch-shifted sound. If possible, I would like to have a potentiometer for each output that could in effect change how pitch shifted each output is, sort've of like a tuning knob. These outputs will eventually get summed together to produce a chord-like sound.
I'm not quite sure what exact requirements are needed for this, just that the sampling rate should be around 44KHz (standard audio sampling rate). Of course, I would like the outputs to replicate the original sound as much as possible, just pitch-shifted. I am assuming as well that the way I pitch-shift and sample could affect the requirements. Also, I would like to avoid SMT if I can.
Given these requirements, what do you suggest the best MCU to use is? I would like to use Arduino to program the MCU. I really only need the chip itself (I think?), as I plan to create a separate circuit board for this (although would I need an Arduino board to initially program the chip?)
I'm fairly new to the Arduino world, so apologies in advance if I miss something obvious or mess up terminology. I do come from a background in analog circuitry and programming though. Just looking for as much help as I can get from people who know more than me but am eager to learn about this all.
Thanks!


texts: Arduino Comms disrupted, prevents program loading (catch 22)

texts:
I have written some software which, when loaded onto an Arduino Micro, blocks communications for some reason. Lets stipulate that there is something wrong with it.

Using the Ardiono IDE on Windows 10, and (ex internet) pressing the board's reset button twice within 5 seconds of power-up, then (device manager) a comms port comes into existence for 2 seconds, presumably under control of the micro-controller's bootstrap program.

In the IDE, you can only select an existing comms port. As above, a comms port comes into existence for 2 seconds.

The download button causes compilation and downloading to the comms port - typically taking 8 seconds.

Thus, one can only replace the duff program by selecting the briefly available comms port, compiling and downloading to it, which takes longer that the port availability window.

And so replacing the duff code with anything is impossible. Have I missed something here? Does anyone have some "emergency" code that waits for a port to appear and immediately loads something innocuous?

BTW the Tags restriction is preventing me from using meaningful tags.


texts: i am not able to figure out the problem due to which i can't upload my sketch to nano

texts:
this is the error code (it is new from the previous time i posted)
i am using the hourly build for this and not the Beta
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x6e

this is the info of the loader and board i am using


texts: Why is Serial.write() slower than memcpy()?

texts:
I use Serial.write() to transmit 53 bytes to PC. For the time measurement I use micros() (before and after the write function). There is a delay of 1s after each transmission.

The time of the Serial.write() function is 532 us with 1000000 baud rate, and 360 us with 9600 baud rate.

The Serial.write() function is clearly asynchronous because the transmission of 53 bytes with 9600 baud rate is 53*8/9600*1e6 = 44167 us. (By the way, in the case of 1000000 baud rate, it is not so obvious that the function is asynchronous.)

I use Serial.availableForWrite() before Serial.write() to confirm that there is enough space in the buffer (this returns 63 each time, the buffer size is default 64).

I don't understand these numbers. Using memcpy() to copy the 53 bytes only takes 32 us. Is copying to the serial buffer not the same as the memcpy() function? And why is there a difference in the copy times when the baud rate is different? Serial.write() is even slower with higher baud rates according to the results. Why does Serial.availableForWrite() return 63 while the buffer size is 64 (according to SERIAL_TX_BUFFER_SIZE)?

Update:
Thanks for all of your answers.

I have tried another library for serial communication: https://github.com/greiman/SerialPort

It seems to be faster than the original one.
I use 2 time measurements and a delay in the code, these 3 deltaTimes represents the whole step as follows:

writeTime + memcpyTime + delaymicros = computedTime != realTime

The first 2 times are measured, the delaymicros is the theoretical delay (900 us), I can compute the step time from these. This computed step time is different from realTime (the measured step time, I measure the whole step too). It seems that the additional time can be found in the delay.

SerialPort library:
100 + 30 + 900 = 1030 != 1350

writeReal = 100 + 1350 - 1030 = 430

Arduino Serial:
570 + 30 + 900 = 1500 != 1520

writeReal = 570 + 1520 - 1500 = 590

Then I measured the delaymicros time (which is 900 us in theory), the missing time can be found there. I programmed 900 us delay, but the real delay was around 1200 in the first, and 920 in the second test.

These measurements can prove the existence of the interrupts, because measuring only the write functions doesn't give all of the writing time (especially with the downloaded serial library).
The downloaded library can work faster, but requires bigger tx buffer because of errors (256 works properly instead of 64).

Here is the code: I use a checkSum in the sendig function (which is 570-532 = 38 us). I use Simulink to receive and process the data.

struct sendMsg1 {
  byte errorCheck;//1

  unsigned long dT1;//4
  unsigned long dT2;//4
  unsigned long t;//4
  unsigned long plus[10];//40
};//53

sendMsg1 msg1;
byte copyMsg1[53];

unsigned long time1;
unsigned long time2;
unsigned long time3;
unsigned long time4;

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

void loop() {
  sensorRead();
  sendMsg1_f();

  //time3 = micros();
  delayMicroseconds(900);
  //time4 = micros();
}

void sensorRead() {
  time3 = micros();

  msg1.t = micros();
  for (unsigned long i = 0; i < 1; i++) {
    memcpy((void*)&(copyMsg1[i*sizeof(sendMsg1)]), (void*)&msg1, sizeof(sendMsg1));
  }

  time4 = micros();
  msg1.dT2 = time4 - time3;
}

void sendMsg1_f() {
  time1 = micros();

  msg1.errorCheck = 0;
  for (int i = 0; i < sizeof(sendMsg1) - 1; i++) {
    msg1.errorCheck += ((byte*)&msg1)[i];
  }
  Serial.write((byte*)&msg1,sizeof(sendMsg1));

  time2 = micros();
  msg1.dT1 = time2 - time1;
}


texts: How to chooce SDA/SCL pair on Arduino Due ?

texts: On Arduino Due, there is two pairs of pins SDA/SCL that I can use for I2C. There is SDA0 and SCL0  at, respectively, pins 20 and 21  and an another near AREF. How do I choose which one of them  I use ? I also read that 20 and 21 has built-in pull-up resistor, is that true ?


texts:
Is there a way to set an Arduino pin as being both an input, and an output?

I was looking at tristates, I'm not sure if that is related, or if there is some other method.

Perhaps I can try switching states rapidly. on one pin. I'm just not familiar with how to do it, and I don't see anything about it on the Arduino site.

This is a function of other microcontrollers, such as PICs, but I'm not sure about AVRs and Arduino types.


texts: Arduino Serial and myserial clarification. How to print out rx output?

texts:
I currently have a camera I am trying to run off an Arduino. I am new to Arduino and I have had trouble figuring out what serial and myserial really do. I also don't understand why, when I have something like serial.write(0x56) I will get the output in the serial monitor to be V in hex, but If I have the Arduino also connected to an oscilloscope, I won't be able to see the signal.

Yet if I have myserial.write(0x56), I won't see anything in the serial monitor, but will see the bits on my oscilloscope.

Also, if I send a command to my camera, my camera should send back some hex values if the write command is sent. I understand I can send commands via myserial.write(0x56), but how would I read the hex values the camera would send back?


texts: DB:NO RESP Using inet.httpPOST on loop()

texts:
I'm using SIM900 module + arduino uno + gsmlib.org library.

I'd like to send a string to endpoint on my API , and it worked correctly for the first time when I using inet.httpPOST function in setup(), but... in loop(), when I call that function again, it doesn't work. On serial monitor I get:

ATT: ERROR
RIC:
ERROR
DB:STARTING NEW CONNECTION
ATT: SHUT OK
RIC:
SHUT OK
DB:SHUTTED OK
ATT: OK
RIC:
OK
DB:APN OK
ATT: OK
RIC:
OK
DB:CONNECTION OK
ATT: ERROR
RIC:
xxx.xxx.xxx.xxx

DB:ASSIGNED AN IP
status=ATTACHED

http://api.com.br/mystring

ATT: OK
RIC:
OK
DB:RECVD CMD
ATT: CONNECT OK
RIC:
OK
ATT: OK
RIC:
CONNECT OK
DB:OK TCP
ATT: >
RIC:
>
DB:>
ATT: SEND OK
RIC:
SEND OK

DB:SENT

http://api.com.br/mystring

ATT: OK
RIC:
xxx.xxx.xxx.xxx
ERROR
ALREADY CONNECT
DB:NOT CONN
ATT: OK
RIC:
ERROR

ALREADY CONNECT
DB:NOT CONN
ATT: OK
RIC:
ERROR

ALREADY CONNECT
DB:NOT CONN

How can I send data to my API continuously on loop() Could someone help me?

Following is my code (SOLVED):

#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <inetGSM.h>

InetGSM inet;
TinyGPSPlus gps;
SoftwareSerial serialGps(11, 10);

/**
    setup
*/
void setup() {
  // Serial connection.
  Serial.begin(19200);
  Serial.println(F("Starting App Arduino"));

  // Turn on GPRS
  powerUpGprs();

  // Start configuration of shield SIM900 with baudrate and  connect to internet.
  if (gsm.begin(9600)) {
    Serial.println(F("\nstatus=READY"));

  // Start configuration of shield GPS NEO-6M with baudrate.
  serialGps.begin(9600);

  // Mensure and show memory usage
  Serial.println(F("\nMemory usage"));
  Serial.print(freeRam());
}

/**
   loop
*/
 void loop() {
  serialGps.listen();
  while (serialGps.available() > 0)  {
    if (gps.encode(serialGps.read())) {
      // Get GPS position and send To API
      gsm.listen();
      // if sim900 started, connect to internet
      Serial.print(F("\r\n"));
      Serial.print(F(" CONNECT TO INTERNET \r\n"));

      // GPRS attach, put in order APN, username and password.
      if (inet.attachGPRS("zap.com.br", "zap", "zap"))
        Serial.println("status=ATTACHED");
      else Serial.println("status=ERROR");
      delay(1000);
      // Read IP address.
      gsm.SimpleWriteln("AT+CIFSR");

      Serial.print(F("\r\n\r\n"));
      Serial.print(F(" GET GEOLOCATION & SEND TO API \r\n"));
      // get geolocation
      String geo;
      geo.concat("lat=" + String(gps.location.lat(), 6));
      geo.concat("&lng=" + String(gps.location.lng(), 6));
      geo.concat("&spd=" + String(gps.speed.kmph()));
      geo.concat("&gps.uuid=1");
      // send2Api
      Serial.println(geo.c_str());
      Serial.print(F("\n"));
      gsm.SimpleWriteln("AT+CIFSR");
      inet.httpPOST("api.com.br", 80, "/geolocations", geo.c_str(), "", 100);
    }
  }
}

/**
   mensure memory usage
*/
int freeRam() {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

/**
   Power up
*/
void powerUpGprs() {
  pinMode(9, OUTPUT);
  delay(100);
  digitalWrite(9, HIGH);
  Serial.println(F("\nPower Up SIM900!"));
}

Thank You!!!


texts:
I am as new to Arduino as it can get. To start off, I am trying to build a DAC using an Arduino Leonardo. I have a digital signal coming from my dual differential comparator. I want to convert this to an analog signal.

First, I will read the digital signal in a digital pin (can someone point me which is good? There are so many of them. I was overwhelmed). Then I send out a PWM signal (confused with the pin again). Then I use a simple RC circuit to filter out the PWM signal to produce a simple sine wave.

Am I going towards the correct direction? If not, please any suggestion would be helpful.


texts: Serial communication between an Uno and an Esplora by connecting their usb ports together

texts:
I’m trying to send a character message from an arduino uno to an esplora by connecting their usb ports together.  The esplora has a micro usb port, while the uno uses a usb B port.  To hooked them up, I connected a micro usb to usb A cable to a usb A to usb B cable using a female to female usb A connector.  I even hooked up the uno and esplora grounds together.  But the two boards just don’t seem to communicate.  Ordinarily when hooking up the esplora to my computer, the tx light flashes whenever sending the message and the message appears as expected on the serial monitor.  I’ve also tested sending character messages from the computer to the uno and they seem to be read as expected.  But when connecting the esplora to the uno without going through the computer, those tx lights on the esplora do not seem light up at all and the uno rx lights don’t flash either.

Any idea what could be the issue here?


texts: Serial Connection from Matlab to Arduino

texts:
I'm trying to send data from matlab to arduino via serail port using this code in Matlab:

 Arduino= serial ('COM4','BaudRate',9600);
 fopen(Arduino);
while 1
    [x]=FunctionX();
    fprintf(Arduino,x)
end

and this in Arduino IDE:

int incoming;
void setup() {
  Serial.begin(9600);
}
void loop() {
  if (Serial.available()) {
    incoming = Serial.read();
    Serial.print("I received: ");
    Serial.println(incoming, DEC);
  }}

I've connected my Arduino Uno. "seriallist"  command on matlab says:

ans =
    "COM4"

I'm getting this error in matlab:

  Error using serial/fopen (line 72) Open failed: Port: COM4 is not
  available. No ports are available. Use INSTRFIND to determine if other
  instrument objects are connected to the requested device.

What's wrong with the serial port? Why matlab can't open it?


texts:
Could someone help me with some suggestions please?
Using ESP8266 and MEGA2560 on UART interface i want to display the message received on the mega serial to the LCD connected to it on i2c. The problem is that the LCD shows some strange unknown character and the serial monitor corresponding to mega shows this :

LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on

when it should display this:

LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF

the code for ESP is this:

int pinLed = 16;
void setup()
{

 Serial.begin(115200);
 Serial.begin(115200);
 pinMode(16,OUTPUT);
 delay(500);
}

void loop()
{

digitalWrite(16,HIGH);
Serial.print("LED on\n");
delay(5000);

digitalWrite(16,LOW);
Serial.print("LED OFF\n");
delay(5000);

}

the code for mega is this:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include<SoftwareSerial.h>
LiquidCrystal_I2C lcd(0x3F,20,4);

void setup()
{

  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  while (!Serial)
  {

    Serial.print("Attempting to connect! ");
    Serial.print("Trying again...");
  }
}

  void loop()
{

  if (Serial.available()>0)

  {
    char c = Serial.write(Serial.read());
    Serial.print(c);
    lcd.print(c);
  }
}


texts: What is the difference between Nano 328p-au and 328p-mu? Does it have to do with the updated bootloader or is it just a different board design? I want to make sure I order the correct one and I could not find a proper answer so far. Thanks.


texts: Will Setting Interrupt Pin High Damage Bluetooth Module?

texts:
I want my HC05 Bluetooth Module to trigger an interrupt when it receives a signal. So I've followed suggestions from the Arduino Forum and connected the Bluetooth TXD pin to the Arduino RX Pin and the Interrupt Pin (2), which I set to high. It is set to detect a FALLING voltage, presumably when BT transfers data. When I connected it this way a funny thing happens. I can clearly see that the interrupt is being called because power consumptions goes way up when Android sends a message to BT module, meaning the device wakes up. However the serial port no longer appears to work on the Nano. I think I narrowed down the possible cause to me damaging the board by removing lineage regulator or damaging serial port somehow with the interrupt. Is the way I wired up the interrupt pin as described correct? Your help would really help me narrow down my problem.
#include <avr/sleep.h>

#define ledPin 7
#define intPin 3
int state = 0;
int stateData = 0;
int ultraPin = 10;
int trigPin = 11;    // Trigger
int echoPin = 12;    // Echo
long duration, cm;
unsigned char inches;
unsigned long timer;

void setup() {
  pinMode(ultraPin, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(intPin, INPUT);
  digitalWrite(intPin, HIGH);
  attachInterrupt(digitalPinToInterrupt(intPin), interrupt, FALLING);
  digitalWrite(ultraPin, LOW);
  Serial.begin(9600); // Default communication rate of the Bluetooth module
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_cpu();
}

void interrupt(){
  Serial.println("interrupted");
  sleep_disable();
  Serial.write(50);
  delay(500);
  timer = millis();
  digitalWrite(ultraPin, HIGH);
  while (true){
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      pinMode(echoPin, INPUT);
      duration = pulseIn(echoPin, HIGH);
      cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
      inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
      Serial.write(inches);
      delay(50);
      stateData = Serial.read();
      if (stateData != 49){
        // receipt from android
        unsigned long timeElapse = millis() - timer;
        if (timeElapse > 5000) {
          break; // exit and SLEEP
        }
      }
      else {
          // reset the timer
          timer = millis();
        }
      }
    sleep_enable();
    sleep_cpu();
}

void loop() {

}


texts: Bridge */arduino/analog/2 returns a blank page

texts:
Had some start up difficulties. But updated the YUN and IDE to the latest version.

Using  * "/arduino/digital/13/1" works as supposed (turns on the LED) - it's just a bit slow. But I can't see why the analogs shouldn't work. I tried to connect it to 5V or GND, so it wasn't floating. But it still returns no reading.

Don't know if this is the cause. But when I connect to my router I can't the the YUN in the list of DHCP Clients...


texts: Arduino with multiple buttons - will power be an issue?

texts:
I have a spare Arduino Uno lying around, which I figured I could attempt to turn into a game controller. First clear issue, that immediately popped up, was that there are not enough digital input pins on the board, but I think I can get around that by using analog pins with appropriate external resistors (is that actually a possibility?).

Another one, more severe, is that I'm not sure how I would need to go around wiring microswitch buttons with the board. Assuming they short the circuit when pushed (SPST), I could simply wire one contact to an input pin, set to INPUT_PULLUP mode, and connect the other to ground. However, since I know little about how such circuits work, I'm immediately in doubt about two things. Considering the board would be used as a controller, an external power source is out of question and I'd only want to rely on the USB power. Since I want to use plenty of buttons (up to fifteen), out of caution I'm worried that shorting this many input pins to the ground at once could overload the... regulator I think?

So my question is this: is it safe to use multiple, potentially simultaneously pressed, buttons connected to input pins on an Arduino Uno board, powered solely from a USB port? Additionally, just to be clear, is it normal to connect them all to a common ground on the board?


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

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

into the arduino 1.8.2 IDE, followed these instructions:

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

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

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

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


texts: Multiple VL6180X distance sensors interactive problem

texts:
I am trying to use a VL6180X distance sensor and an Arduino Uno board for individual sensor doing individual distance sensing. This sensor follows the I2C protocol. Since for the same type of sensor, the I2C protocol says that they would all have the same address, I am thinking about using the chip enable pin (GPIO00) on the sensor chip to toggle sensor when doing the distance measuring.

I am able to update the address of the sensor group now. But I think to obtain individual results from different sensors on the Arduino serial monitor, right now I can only do one time setup sensor thing (like I couldn't update and toggle around different sensors). Once I started to do that, the results from the serial monitor were wrong. Any advice how I can continue to toggle around the sensor and make them work using the GPIO00 pin?

The code I'm using is:

#include <Wire.h>
#include <VL6180X.h>
#define Address1 0x20
#define Address2 0x22
#define Address3 0x24

VL6180X sensor;

int pin2 = 2;
int pin3 = 3;
int pin4 = 4;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  pinMode(pin2,OUTPUT);
  pinMode(pin3,OUTPUT);
  pinMode(pin4,OUTPUT);
  digitalWrite(pin2,HIGH);
  digitalWrite(pin3,HIGH);
  digitalWrite(pin4,HIGH);
  sensor.init();
  sensor.configureDefault();
  sensor.writeReg(VL6180X::SYSRANGE__MAX_CONVERGENCE_TIME, 30);
  sensor.writeReg16Bit(VL6180X::SYSALS__INTEGRATION_PERIOD, 50);
  sensor.writeReg16Bit(VL6180X::INTERLEAVED_MODE__ENABLE,0);
  sensor.setTimeout(500);
  sensor.stopContinuous();
  delay(300);
  sensor.startInterleavedContinuous(100);
}

void loop() {
  hello2();
  delay(1000);
}

void hello1(){
  sensor.setAddress(0x29);
  Serial.println(sensor.readReg(0x212),HEX);
  sensor.setAddress(Address1);
  sensor.writeReg(0x212,Address1);
  Serial.println(sensor.readReg(0x212),HEX);
  Serial.println();
  digitalWrite(pin2,HIGH);
  digitalWrite(pin3,LOW);
  digitalWrite(pin4,LOW);
  Serial.print("Ambient 1: ");
  Serial.print(sensor.readAmbientContinuous());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.print("\tRange 1: ");
  Serial.print(sensor.readRangeContinuousMillimeters());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.println();
  sensor.writeReg(0x212,0x52);
  digitalWrite(pin2,HIGH);
  digitalWrite(pin3,HIGH);
  digitalWrite(pin4,HIGH);
}

void hello2(){
  sensor.setAddress(0x52);
  Serial.println(sensor.readReg(0x212),HEX);
  sensor.setAddress(Address2);
  sensor.writeReg(0x212,Address2);
  Serial.println(sensor.readReg(0x212),HEX);
  Serial.println();
  digitalWrite(pin2,LOW);
  digitalWrite(pin3,HIGH);
  digitalWrite(pin4,LOW);
  Serial.print("Ambient 2: ");
  Serial.print(sensor.readAmbientContinuous());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.print("\tRange 2: ");
  Serial.print(sensor.readRangeContinuousMillimeters());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.println();
  sensor.writeReg(0x212,0x52);
}

void hello3(){
  sensor.setAddress(0x52);
  Serial.println(sensor.readReg(0x212),HEX);
  sensor.setAddress(Address3);
  sensor.writeReg(0x212,Address3);
  Serial.println(sensor.readReg(0x212),HEX);
  Serial.println();
  digitalWrite(pin2,LOW);
  digitalWrite(pin3,LOW);
  digitalWrite(pin4,HIGH);
  Serial.print("Ambient 3: ");
  Serial.print(sensor.readAmbientContinuous());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.print("\tRange 3: ");
  Serial.print(sensor.readRangeContinuousMillimeters());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.println();
  sensor.writeReg(0x212,0x52);
}

Any help would be appreciated!


texts: Arduino IDE unable to see serial connection on OS X El Capitan

texts:
For some reason the Arduino IDE is unable to see my Arduino Uno even though it is connected. I have reinstalled the Arduino software, but no luck come of it. I connected the Arduino to my friends mac, who's could see it.. I am very confused and greatly appreciate any help.

Thanks,
Shaun


texts:
I have been using an Arduino Uno for a year now, and I bought a WEMOS D1 Mini and a NodeMCU. I want to select WEMOS or NodeMCU from the Arduino Web Editor but it doesn't appear on the list:

I think I need to install a driver but it's only for the Arduino desktop editor (not for the web editor).


texts: How to solve the white blocks on LCD keypad display?

texts:
I have just bought my first Arduino (a Mega 2560 R3 clone by ELEGOO), and I got a cheap LCD display to go with it. I cannot for the life of me get it to display anything other than a row of white blocks (although I uploaded a different sketch that I change the numbers of one of the ports and now it shows the top 3 blocks of the second row as white as well).

When I read the notes on the example LCD sketch "Display" it says the following:

The circuit:

LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
LCD R/W pin to ground
LCD VSS pin to ground
LCD VCC pin to 5V
10K resistor:
ends to +5V and ground
wiper to LCD VO pin (pin 3)

However, when I plug my display into the Arduino the pins don't seem to go into the same ports and there is no other way of fitting it in. For reference my pins go:

LCD - Mega2560

 VSS - AREF,
 VDD - GND,
 V0 - 13,
 RS - 12,
 RW - 11,
 E - 10,
 D0 - 9,
 D1 - 8,
 D2 - 7,
 D3 - 6,
 D4 - 5,
 D6 - 4,
 D7 - 3,
 D8 - 2,
 A - 1-TX,
 K - 0-RX,

 RST - RESET,
 5V - 5V,
 VIN - VIN,
 A0 - A0,
 A1 - A1,
 A2 - A2,
 A3 - A3,
 A4 - A4,
 A5 - A5,

I am not sure what to do any assistance you can provide would be greatly appreciated.

Liam


texts:
I am trying to send numeric data using ESP8266 to local network python server. Before that I am collecting data from sensors using Arduino UNO and then send it to ESP using hardware serial.

ESP8266 code:

#include <ESP8266WiFi.h>

const char* ssid     = "ssid";
const char* password = "pass";

const char* host = "192.168.1.103";

String serial_data;

WiFiClient client;

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

  // We start by connecting to a WiFi network

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

  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

   delay(5000);

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections

  const int port = 8888;
  if (!client.connect(host, port))
  {
    Serial.println("connection failed");
    return;
  }

}

void loop() {

  delay(200);

  while(Serial.available() <= 0)
  {
    //wait for arduino serial data
  }

  if(Serial.available()>0)
  {
    // This will send data to client via TCP
    Serial.println("Sent..");
    serial_data = String(Serial.read());
    client.print(serial_data);
  }
}

Python Server code:

import socket
import sys
from thread import *
from peewee import *

db = SqliteDatabase("data.db")

class post(Model):
    timestamp = DateTimeField()
    current = TextField()

    class Meta:
        database = db

#connecting to database
def initialize_db():
    db.connect()
    db.create_tables([post], safe = True)

initialize_db()

HOST = '192.168.1.103'
PORT = 8888 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

s.listen(10)
print 'Socket now listening'

#keep talking with the client
#Function for handling connections. This will be used to create threads
def clientthread(conn):
    #Sending message to connected client
    conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

    #infinite loop so that function do not terminate and thread do not end.
    while True:

        #Receiving from client
        data = conn.recv(1024)
        print data

        #send data to database
        post.create(
            current = data
        )

        reply = 'OK ->' + data
        if not data:
            break

        conn.sendall(reply)

    #came out of loop
    conn.close()

#keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])

    start_new_thread(clientthread ,(conn,))

s.close()

After powering up ESP it successfully connects to server and then simulating arduino esp serial communication I am using serial monitor to send some numbers. Before I send anything server outputs number 240:

Connected with 192.168.1.100:26137
240

Then I am sending number 1 but on server terminal I get numbers 49 and 13. Sending numbers some 2 - 3 times and no more data are outputted to server terminal. Should I parse data received from serial to some form I can transmit it via TCP or data should be processed on server side?


texts:
I need to read an analog signal at about 500-1000Hz for at least 5 seconds.

I've a battery powered microphone wired into an analog and ground pin on my arduino and am trying to measure the frequency (and amplitude) of sound coming from a rijke tube

To accurately represent the sound waves I need to take samples with a frequency at least twice that of the sound I'm studying, hence the frequency above. I plan to next do FFT to find the frequencies associated with the sound sample

Having stripped down every other part of my code, I could still only get at the most 107 readings a second, as shown below

#define VOLT_CAL 269
#define CURRENT_CAL 60
unsigned long time;

EnergyMonitor emon1;             // Create an instance

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

  Serial.println("CLEARDATE");
  Serial.println("LABEL, DATE, TIME,Wall Voltage,Wall Current, Mic Voltage, Time Elapsed");
}

void loop()
{
  int sensorValue = analogRead(A4);

   time = millis();

  Serial.print(sensorValue);
  Serial.print(",");
  Serial.println(time); //prints time since program started
}

can anyone tell me what I'm doing wrong/how I can increase the sample rate?

I've also tried to use a for loop to take my readings first, only printing them at the end but also maxed out at only 100 readings a second with the next attempt.

I've read also about preclocking, but the example codes were too complex for me to understand. A starting point in this direction would also be very much appreciated.


texts: Arduino stops loop randomly whenever a button is pressed

texts:
I'm having a problem with this Arduino code.

So whenever I press the "button" in port 11, which is supposed to either reset the burglar alarm or stop it, the whole program stops (the void loop() function stops). The wiring is most likely not the problem, because I've tested it on multiple occasions with different codes. The button, too, works perfectly well as a button with different codes.

In the Serial port, it keeps printing "78005", which it should before the button is pressed, until when I press the button, at which it randomly breaks off printing (resulting in 78, 780, 7, 7800, or 78005 as the last line printed).

Can anyone explain why the arduino will behave in this way?

Thank you so much.

int button = 11;
int receiver = 12;
int buzzer = 13;
int frequency = 1000; // frequency of buzzer

bool keepAlerting = false; // toggles Alarm regardless of detected charge
int receiverVal = LOW; // value from port 12
int buttonVal = LOW; // value from button
int oldButtonVal = LOW;

int setupTime = 5000; // time the user has to close the box after toggling alarm

bool alarmOn;
int buttonMode = 0;
const int resetButton = 1;
const int stopButton = 2;
int buttonModeDecider = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(buzzer, OUTPUT);
  pinMode(receiver, INPUT);
  pinMode(button, INPUT);
  Serial.begin(9600);

  noTone(buzzer);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print("7");
  receiverVal = digitalRead(receiver);
  buttonVal = digitalRead(button);
  Serial.print("8");

  if(alarmOn == true){
    Serial.print("6");
    setAlarm();
  }

  Serial.print(buttonVal);
  Serial.print(oldButtonVal);

  if(buttonVal == HIGH && oldButtonVal == LOW){
    buttonModeDecider = 1 - buttonModeDecider;
    Serial.print("Toggled");

    if(buttonModeDecider == 1){
      buttonMode = resetButton;
      Serial.print("1");
    } else {
      buttonMode = stopButton;
      Serial.print("2");
    }

    switch(buttonMode) {
      case resetButton:
      {
        delay(setupTime);
        alarmOn = true;
        break;
        Serial.print("3");
      }
      case stopButton:
      {
        alarmOn = false;
        Serial.print("4");
      }
    }
  }
  Serial.println("5");
  oldButtonVal = buttonVal;
}

void setAlarm() {
  if(receiverVal == LOW || keepAlerting == true) {
    tone(buzzer, frequency);
    keepAlerting = true;
  }
}


texts: Flashing ESP8266 over WiFi whith samrtphone?

texts:
I'm working on a project in which an ESP8266 is the brain of the device. I want to add new features to the device controller later but this requires that the user open the controller and reprogram the ESP8266.

I want the user to be able to update the firmware with his smartphone (maybe through an application). How can I do that? Is this possible with this chip?


texts:
I'm using a supplied library which uses a number of (non-sequential) outputs to latch a multiplexer. The code looks (in part) like this:

 digitalWrite(_S0, (chan & 1));
 digitalWrite(_S1, (chan & 3)>>1);
 digitalWrite(_S2, (chan & 7)>>2);
 digitalWrite(_S3, (chan & 15)>>3);

Those masks seem a little odd, but it would work. More natural to me would be:

 digitalWrite(_S0, (chan & 1));
 digitalWrite(_S1, (chan & 2)>>1);
 digitalWrite(_S2, (chan & 4)>>2);
 digitalWrite(_S3, (chan & 8)>>3);

But overall, would it be more efficient to do this?

 digitalWrite(_S0,       (chan & 1));
 digitalWrite(_S1, (bool)(chan & 2));
 digitalWrite(_S2, (bool)(chan & 4));
 digitalWrite(_S3, (bool)(chan & 8));

...or is shifting already pretty efficient?

I've actually re-written the code to build a mask and use PORTx to latch it all at once, so this is really an academic question, but I'm still curious.


texts:
I was hoping to create a cheap security system by connecting an Arduino to the phone line output of a base station.

Since the base station should call a phone number if the alarm is tripped I wouldn't have to do much hardware hacking so long as I can read/parse the output from the base station.

My question is can I read serial output from a phone line like this?


texts: Arduino Uno cannot upload any sketch: avrdude: stk500_recv(): programmer is not responding

texts:
I'm newbie in Arduino Dev

I got Arduino Uno R3, at first it just worked fine.
I tried to upload my whole project sketch which almost up to the max size of arduino memory.

Then suddenly the upload failed, and i can upload any other sketch even an empty or simple sketch.

I already remove all cables connected, still failed to upload.

I really dont know how to fix this.


texts: How to create custom bootloader with accompanying program loader for ATMega2560

texts:
Just for some context, I have created a custom board based on the ATMega2560. I currently have the original Arduino Bootloader for the ATMega2560 and have no problems uploading code via the USB Port on TX0 and RX0.

What I am hoping to achieve is creating a custom Bootloader that allows me to upload my .hex binaries to flash but in a proprietary way, so that any program cannot be uploaded to it with the standard Wiring Protocol used by Arduino IDE. In addition, I will need a custom PC based program that can upload the code via the USB port.

The reason why I need this is that I will have this device out in areas where I would not want someone taking the device and uploading their own program to it and screw it up. I know it sounds paranoid, however, it would be preferred to have this feature so I can update the firmware via the USB Port without using the Wiring protocol.

Has anyone accomplished this before?

TL;DR

Want to upload custom Bootloader to Arduino Mega so that I can upload my firmware with a proprietary programmer via the USB Port on TX0 and RX0 because I am paranoid.


texts: How to stop program while Servo is rotating

texts:
If I code like this:

motor.write(0);
Serial.println("Before");
motor.write(180);
Serial.println("After");

Both "Before" and "After" is instantly printed, while the motor is still rotating.
I want "After" or whatever statement to be executed AFTER the motor
reaches 180 degree.
How can I implement this? Is it possible to read Servo's statement?

Btw, I don't want to put delay after write(), so other than that strategy.


texts: Creating WebServer with 5000 port with AT command(ESP-01f)

texts:
I'm setting webserver with toggle led. I want to create global webserver. I`m mean hat use server with global ip. For it I must use port too. global ip/local ip:port.
I want to create on 5000 port. I'm used for ESP-01f and connect it arduino. Communicating by SoftwareSerial. I used AT+CIPSTA for static ip. When I used AT+CIPSERVER=1,5000 it worked. But when I connect to it, it works, but in second connection it doesn't want to connect itor when I use digitalWrite it doesn't connect to this server. How can I solute this problem?

code:

#include <SoftwareSerial.h>

SoftwareSerial softSerial(10, 11);
String ssid = "ssid";
String ip = "staticip";
String gateway="gateway";
String sub="submask;
String password = "password";
String _response = "";
#define DEBUG true
void setup()
{

  Serial.begin(115200);

pinMode(2,OUTPUT);

  softSerial.begin(115200);
  connectWifi();
}

void connectWifi() {

  do {

    sendData("AT+RESTORE\r\n", 5000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT\r\n", 2000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT+CWMODE=1\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"\r\n", 5000, DEBUG);
  } while (softSerial.find("OK"));
   do {

    sendData("AT+CIPSTA=\"" + ip + "\",\"" + gateway +"\",\"" + sub + "\"\r\n", 2000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT+CIFSR\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT+CIPMUX=1\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT+CIPSERVER=1,5000\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));

}

String sendData(String command, const int timeout, boolean debug)
{

  String response = "";

  softSerial.print(command);        long int time = millis();
  while ((time + timeout) > millis())
  {
    while (softSerial.available())
    {

      char c = softSerial.read();
      response += c;
    }
  }

  if (debug)
  {
    Serial.print(response);
  }

  return response;
}

void loop()
{

if(softSerial.available()){
  if(softSerial.find("+IPD,"){
   int connectionId = softSerial.read()-48;
softSerial.find("pin/");
int pin = softSerial.read()-48;

String htmlCode = "<label>"+String(pin)+"</label>";
digitalWrite(pin,HIGH);
sendData("AT+CIPSEND="+String(connectionId)+","+htmlCode.length()+"\r\n",1000,DEBUG);
sendData(htmlCode+"\r\n",1000,DEBUG);

sendData("AT+CIPCLOSE="+String(connectionId),3000,DEBUG);

  }
}
}


texts: How to get a character from a serial Parsed http response?

texts:
I am a web developer and I am struggling with C code on Arduino. So this is What I have:

I have a backend written on PHP that returns a 0 or 1 depending of wether a pin should be high or low. I have an Arduino UNO with a W5100 Ethernet shield mounted, and I'm currently connecting correctly to my server, this is my Arduino code:

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.api-qa1.enerzoo.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /api/DeviceState/1 HTTP/1.1");
    client.println("Host: www.api-qa1.enerzoo.com");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

And this is the response it outputs:

connecting...
connected
HTTP/1.1 200 OK
Server: nginx/1.10.3 (Ubuntu)
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With
Cache-Control: no-cache
Date: Fri, 17 Nov 2017 23:36:14 GMT
Set-Cookie: laravel_session=eyJpdiI6ImIzTDJzQk1BUm1qY1BuZ1BJXC83Mk5BPT0iLCJ2YWx1ZSI6IlwvNjlmXC9FZWxDSW9vbGNcL1JZUU5tbTFvOVVXVjcxV0hHaDRKUzVGVVZCSmFCM1BcLzlSR2x5MmN4cnZ1ZHRvZmlcLzNSUWMrZEFDMTQzR05ORTk5R3dBUGc9PSIsIm1hYyI6IjM4ZjVhY2IxOWVmZTMzMGY2OGE1MTNmZWY0NzczNGVhNWJhZjVkYzlkYzY4ODg3ZGI0OWVhNDYwOTkwYjgxYTAifQ%3D%3D; expires=Sat, 18-Nov-2017 01:36:14 GMT; Max-Age=7200; path=/; HttpOnly

1a
||0||
0

disconnecting.

I need to get that zero that is enclosed between the double pipes

  ||0||

Any help would be really appreciated


texts: Can I convert 3.7V to 5V's using 3.3v to 5v converter

texts:
THe product: (https://www.sparkfun.com/products/12009)

So guys, here' s a pretty simple but important question for me:
Can I convert 3.7V (li-po battery's voltage level) to 5V's (I do have arduino pro mini running on 5 volts) using 3.3v to 5v converter (picture shown above...) ??

Thanks already...


texts:
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.


texts:
Trying to setup a server on Arduino to support multiple clients,
I am able to support one but I don't want to flush that client to make another connection.

#include <ESP8266WiFi.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

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

  // prepare GPIO2
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

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

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();

  // Match the request
  int val;
  if (req.indexOf("/gpio/0") != -1)
    val = 0;
  else if (req.indexOf("/gpio/1") != -1)
    val = 1;
  else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  // Set GPIO2 according to the request
  digitalWrite(2, val);

  client.flush();

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
  s += (val)?"high":"low";
  s += "</html>\n";

  // Send the response to the client
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

  // The client will actually be disconnected
  // when the function returns and 'client' object is detroyed
}

Using this code, the server handles only one client at a time, but I need to connect multiple clents simultaneously.


texts: Is there a way to power off external devices during deep sleep

texts:
I am looking to work with deep sleeping, particularly with the ESP8266 but this question applies to most all micros. I am interested in running the device off of battery power for as long as possible. My solution would be something like a weather station where you know you only want to take a measurement every x minutes. So, I would like to sleep as much as possible in between measurements to extend battery life as much as possible. However, sleeping the microcontroller is one thing. How about when you have some sensors that piggyback off of the battery too. No need for those to be powered while the micro is sleeping and not taking a measurement.

Similar to this, I was thinking about reading the battery level. There are plenty of examples on how to do this online using a voltage divider (if necessary) and running the battery into analog input. This also draws from the battery while sleeping.

So, is there a way I can run all of these external sensors/devices through a transistor or something with low power draw when off and turn it all one when the device wakes up from sleep?

Thanks!


texts: ATTiny85, how to fix overwritten clock pins?

texts:
I'm using an ATTiny85 with an external 16MHz clock. I accidentally set pins 3 and 4 to output using pinMode() in a program and uploaded it, and now I'm getting an invalid device signature (the signature is 0) error when I try to upload a sketch.

How can I go about fixing this (if possible)?

I am using an Arduino UNO as ISP, with an external 16MHz clock and capacitors connected to pins 3 and 4, and have rechecked my wire setup multiple times.


texts: How to send RPM data as analog input from arduino to Xbee

texts:
I am new to arduino and Xbee these stuff.
Trying to send RPM (obtained and calculated by arduino using puulse function) data from arduino to Xbee as analog input to xbee series1.

It seems XBee analog input read a range of 0 volts to 1.2 volts.
However, not quite sure how to implement and write the corret code.
Following are Arduino code and schematic circuit.
Any idea?
I really appreciate your help.

int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val;
float rps;
float read_rpm;
int pin_out=10;

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

void loop()
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

analogWrite(pin_out,(int)rpm);

Serial.print("RPM=\t");

Serial.print(rpm);

Serial.print("\t rps= \t");

Serial.print(rps);

Serial.print("\t dt=\t");

Serial.println(val);

}


texts: How can I control blinking of LED while in timer function?

texts:
When I am in the 30-second standby function, I want to turn the LED on and off at 5-second intervals.
How can I do what I want using the read_counter() function?
The problem here is that I am already in the timer function with the read_counter() function.
void wait_function() {
  timer_init();
  while(read_counter()<30000) { //30 second wait
    // A LED blinking at 1 second intervals ???
  }
}

Note: The read_counter() function increases every 1 millisecond with ISR COMPA vector. I tried many times and couldn't find a stable solution. Example:
if (read_counter() % 1000) PORTB^=(1<<LED);
Update: My new code :
while((TIFR1 & (1 << OCF1A))==0) //4secondIf I do this cycle 8 times, it
                                 //makes 32 seconds.
            {
                if(TCNT1%15624==0) //per 15624=1 second,
                PORTA^=(1<<0);
                 //led_blink_1s
            }

But,it doesn't work.Should I use util delay function?


texts: Arduino scrolling text program freeze after some time

texts:
I use a 16x2 character lcd to display some text. What I want is first line will stay, but the second line should scroll text.

I wrote a program which works fine but the problem is after some time arduino does not respond. I suspect there might be a bug or memory leak in the code.

The relevant code is like this.

void scrollTextFromRight(int line, char text[])
{
    const char space[16] = "                ";
    char screen[16];
    char * longText;

    longText = malloc(sizeof(char) * (sizeof(text) + 17));

    memset(longText, '\0', sizeof(char) * (sizeof(text) + 17));
    memset(screen, '\0', sizeof(screen));

    for (int i = 0; i < 16; ++i)
    {
        longText[i] = space[i];
    }

    for (int j = 0; j < sizeof(text) + 17; ++j)
    {
        longText[16+j] = text[j];
    }

    for (int i = 0; i < sizeof(text) + 17; ++i)
    {

        lcd.setCursor(0, line);
        strncpy(screen, longText + i, 17 );
        lcd.print(screen);
        delay(350);
    }
}

I call this function from main program like this:

scrollTextFromRight(1, "Scrolling text");


texts: Reading incoming/outgoing bytes from SIM card / ATR

texts:
I am trying to read data from a two-way I/O uart pin of a sim card on Arduino. It is attached to the GPRS Arduino shield (with SIM900 modem). I believe I have a baud rate issue.

I am supposed to receive ATR (Answer to Reset) bytes which should be easily recongnized but all I get is a almost-random stream of bytes.

I soldered a wire on the SIM I/O pin and attached it to arduino's software serial RX, I set the baud rate to the same baud rate of the modem which goes up to 115,2K and read. Here's my code

#include <SoftwareSerial.h>
SoftwareSerial IO(9, 10);
void setup() {
Serial.begin(115200);
IO.begin(115200); // my said wire on SIM card's I/O    enter code here
}
void loop() {
if (IO.available())
Serial.print(IO.read(),HEX);
}

and here's the output after a cold reset :

I also tried other baud rate within the SIM900 range of baud rates, still almost same.

Any idea why it's not showing bytes correctly? I appreciate it if anyone could help.


texts:
I am facing the same issue with my motor driver. Initially I ran the code and connected the L298N with Arduino and it worked fine. At that time motors were running absolutely fine. But when I ran it sometimes later then the motors are not running. However the motors are getting power but I think thy are getting very less power from the Motor Driver.

I directly ran motors from Arduino +5V pin and the motors were running fine. Is there something wrong with my L298N motor driver?

One more thing I checked the power for all the pins for L298N motor Driver and all pins are working fine.

Here is my complete program:

const int MOTOR_RIGHT = 1;
const int MOTOR_LEFT =  2;
const int MR_CONTROL_PIN_A = 8;
const int MR_CONTROL_PIN_B = 9;
const int ML_CONTROL_PIN_A = 10;
const int ML_CONTROL_PIN_B = 11;

void setup() {
  // These two pins will act as output pin

  pinMode(MR_CONTROL_PIN_A,OUTPUT);
  pinMode(MR_CONTROL_PIN_B,OUTPUT);
  pinMode(ML_CONTROL_PIN_A,OUTPUT);
  pinMode(ML_CONTROL_PIN_B,OUTPUT);
  Serial.begin(4800);

}

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

  forward(MOTOR_RIGHT);
  forward(MOTOR_LEFT);
  delay(5000);
  stopMotor(MOTOR_RIGHT);
  stopMotor(MOTOR_LEFT);
  delay(1000);
  backward(MOTOR_RIGHT);
  backward(MOTOR_LEFT);
  delay(5000);
  stopMotor(MOTOR_RIGHT);
  stopMotor(MOTOR_LEFT);
  delay(1000);

}
/////////////////////////////////////////////////////////////////////
//Forward

  void forward(int motorNo)
  {

  Serial.print("\r\n Forward : ");
  Serial.print(motorNo);

  switch(motorNo)
  {
    case MOTOR_RIGHT:
    digitalWrite(MR_CONTROL_PIN_A,HIGH);
    digitalWrite(MR_CONTROL_PIN_B,LOW);
    break;

    case MOTOR_LEFT:
    digitalWrite(ML_CONTROL_PIN_A,HIGH);
    digitalWrite(ML_CONTROL_PIN_B,LOW);
    break;

  default:
    Serial.print("\r\n Error :Invalid Motor No ");
    Serial.print(motorNo);
   }
  }

//////////////////////////////////////////////////////////////////////
  void backward(int motorNo)
  {
   Serial.print("\r\n Backward : ");
   Serial.print(motorNo);
  switch(motorNo)
  {
    case MOTOR_RIGHT:
    digitalWrite(MR_CONTROL_PIN_A,LOW);
    digitalWrite(MR_CONTROL_PIN_B,HIGH);
    break;

    case MOTOR_LEFT:
    digitalWrite(ML_CONTROL_PIN_A,LOW);
    digitalWrite(ML_CONTROL_PIN_B,HIGH);
    break;

  default:
    Serial.print("\r\n Error :Invalid Motor No : ");
    Serial.print(motorNo);
   }

  }

///////////////////////////////////////////////////////////////////////
  void stopMotor(int motorNo)
  {
   Serial.print("\r\n STOP : ");
   Serial.print(motorNo);
  switch(motorNo)
  {
    case MOTOR_RIGHT:
    digitalWrite(MR_CONTROL_PIN_A,HIGH);
    digitalWrite(MR_CONTROL_PIN_B,HIGH);
    break;

    case MOTOR_LEFT:
    digitalWrite(ML_CONTROL_PIN_A,LOW);
    digitalWrite(ML_CONTROL_PIN_B,LOW);
    break;

  default:
    Serial.print("\r\n Error :Invalid Motor No : ");
    Serial.print(motorNo);
   }

  }

Is there something wrong with my L298N ? How can I test it?


texts: Arduino Ethernet Shield: May I connect it to a PC connected to the internet via wifi?

texts:
I have an Arduino Ethernet shield.

May I connect it to a machine that´s connected wirelessly to the internet in order to get the arduino into the internet?

Or do I need to connect it only to a router?


texts: HC-05 will NOT pair in Master mode (AT+ROLE=1). Same module will pair in slave mode (AT+ROLE=0)

texts:
I have a HC-05 Bluetooth module Version (+VERSION:2.0-20100601).
I am using Linux Mint Rosa on an Acer laptop
Section 1 - How it's wired
Wiring
HC-05       Arduino
VCC         5V
GND         GND
TX          pin 1
RX          GND via voltage divider (GND to 2k resistor{2k to HC-05 RX and a 1k resistor} 1k to pin 0)

Section 2 - Sequence to get into AT command state
The sequence I use to get the BT module in AT command state

Unplug the Arduino Uno
Unplug both the RX and TX
Press the button on the HC-05
Plug in the Arduino
HC-05 LED flashes 1 time every 2 seconds
Initialize com ports via Linux terminal - sudo chmod 0777 /dev/ttyACM*
Upload an empty sketch
Plug in the HC-05 RX to Arduino pin 0, and TX to pin 1
Open the Serial monitor
Set Both NL & CR  and 38400 baud

Section 3 - AT commands issued
I use the following AT commands with the noted results.
AT                                  > OK
AT+ORGL                             > OK
AT+RMAAD                            > OK
AT+VERSION  +VERSION:2.0-20100601   > OK
AT+ADDR     +ADDR:98d3:b1:fd85b0    > OK
AT+NAME=Master1                     > OK
AT+UART  +UART:38400,0,0            > OK
AT+ROLE  +ROLE:0                    > OK

NOTE:HC-05 is set to slave and it will pair (see Section 4 below)
THE PROBLEM IS AFTER PAIRING, I RETURN TO AT COMMAND MODE (Section 2) and SET ROLE=1 (Section 5) BUT IT WILL NOT PAIR IN MASTER MODE.
Section 4 - Pairing
I do the following to pair the HC-05 to my phone

Unplug the Arduino
Plug the Arduino back in
HC-05 LED flashes quickly blink/blink/blink
Android phone>settings>connections>Bluetooth>Scan
1 device found > Master1 > pair 1234
Android app > Serial BT terminal>device>Master1>connected
Once Android app connects:
HC-05 LED flashes blink/blink 2 seconds then blink/blink
Remove the RX and TX cables from Arduino and put a jumper to connect HC-05 TX to RX (loopback)
Serial BT terminal>hello>send
Output both green and blue - which means the data was sent via RX and returned via TX.

Section 5 - change ROLE=0 (slave) to ROLE=1 (Master)
I then follow the same sequence that I used previously in Section 2 to return to AT command state.
Issue the following AT commands
AT                      > OK
AT+ROLE  +ROLE:0        > OK
AT+ROLE=1               > OK

Since I changed the configuration I unpair the device on my phone.
I then follow the same sequence that I previously used in Section 4 to pair the HC-05 to my phone

HC-05 LED flashes quickly blink/blink/blink
Android phone>settings>connections>Bluetooth>Scan - CAN'T FIND THE DEVICE.

If I return to AT Command mode and change AT+ROLE=0 it will Pair.
In Master mode:

I tried to swap the TX and RX pins - won't pair.
I tried to pair with the TX and RX removed from the Arduino - won't pair.
I tried NOT UNpairing the device on the phone but it won't communicate with it via the android app once I change it to Master (Section 5).
As I mentioned above if I return to AT Command mode and change AT+ROLE=0 it will Pair.

Lastly I have 2 other HC-05 modules and they all fail to pair when set to Master mode, so I'm thinking I'm missing something but can't figure out what it is.
I would appreciate hearing from anyone with the same problem and anyone who can determine what I'm doing incorrectly.


texts:
I'm new to the Arduino and do not quite understand the F() macro yet.

In my code, I have a String, and as I want to transfer it via WebServer, I need to write it to the answer.

Somehow I need to convert the String, to fit it into the fastrprintln() function.

String weather_json = getWeatherData();
char weather[2048];
weather_json.toCharArray(weather,2048);
client.fastrprintln(F(weather));

Do you have any idea for me?


texts:
I am trying to use Timer2 on an Elegoo Nano to produce a "tick" interrupt every 10uS. My plan was to set Timer2 to CTC mode with a /8 prescaler (to get a timer clock of 2MHz from the 16MHz chip clock) and a compare value of 19 (to reset the timer every 20 counts) which should trigger the compareA ISR at 100KHz (every 10us). The problem is that only prescale values of 64 or greater work as expected. Setting the prescaler  to any value lower than 64 actually results in the "tick" interval getting much longer (10 times the interval or more). I have carefully studied the ATmega628 datasheet to see if I am configuring every register correctly, but I don't see anything wrong with what I am doing. Here is my code...

void initTimer() {

    // ---Disable interrupts during timer initialization
    cli();

    // ---Counter compare value (make CTC interrupt fire every 10uS)
    OCR2A = 19;

    // ---Clear TCCR A register (not used)
    TCCR2A = 0;

    // ---Enable CTC mode with divide-by-8 prescaler
    TCCR2B = _BV( WGM22 ) | _BV( CS21 );

    // ---Enable Timer2 CTC interrupts for compare A match
    TIMSK2 |= _BV( OCIE2A );

    // ---Initialize timer 2 to zero (not really needed in my situation)
    TCNT2 = 0;

    // ---Turn interrupts back on
   sei();
}

SIGNAL( TIMER2_COMPA_vect ) {

    /*
    ** This should execute every 10uS, but for prescaler values
    ** below 64 the interval is many times longer than expected.
    */
}

Can anyone point out my mistake?


texts: Output pin low used to complete 12V LED circuit?

texts:
I have a project that (in part) will drive 3 LEDs where the LED
anodes are at 12V.  The thought is to drive each LED by connecting
each cathode to a 650 ohm resistor, and connect that to an Arduino DIO pin which, when needed, is set to output LOW.  Arduino VIN = same 12V with
common ground.  Am I going to have an Arduino problem of any sort?


texts:
Sorry for my code is long and my English is not good.

I'm working with 8x8x8 LED cube project using Arduino nano. I tried to understand code, but I don't understand how cube[][] data write on pins.

I just want to know, how write the data from cube[8][8] to hardware using SPI. code download using this link.

Thanks in advance.

My code is here :

#define AXIS_X 1
#define AXIS_Y 2
#define AXIS_Z 3
#define REFRESH_RATE 120

int CUBE_SIZE = 8;
int SPI_CS = 10;// This SPI Chip Select pin controls the MAX72xx
byte value[8];

volatile unsigned char cube[8][8];
volatile int current_layer = 0;

void setup()
{
  Serial.begin (115200);
  Serial.println("jolliFactory 8x8x8 jolliCube Demo example 1.0");

  pinMode(SPI_CS, OUTPUT);

  SPI.begin();

  maxTransferAll(0x0F, 0x00);   // 00 - Turn off Test mode
  maxTransferAll(0x09, 0x00);   // Register 09 - BCD Decoding  // 0 = No decoding
  maxTransferAll(0x0B, 0x07);   // Register B - Scan limit 1-7  // 7 = All LEDS
  maxTransferAll(0x0C, 0x01);   // 01 = on 00 = Power saving mode or shutdown
  maxTransferAll(0x0A, 0x0F);   // Set Brightness Intensity

  setUpInterrupts();
}

// Get the current status of a voxel
unsigned char getvoxel(int x, int y, int z)
{
    if (inrange(x,y,z))
    {
        if (cube[z][y] & (1 << x))
        {
            return 0x01;
        } else
        {
            return 0x00;
        }
    } else
    {
        return 0x00;
    }
}

void maxTransferAll(uint8_t address, uint8_t value)
{
  digitalWrite(SPI_CS, LOW);

    for ( int c=1; c<= CUBE_SIZE;c++) {
        SPI.transfer(address);
        SPI.transfer(value);
    }

  digitalWrite(SPI_CS, HIGH);
}

void maxTransferOne(uint8_t whichMax, uint8_t address, uint8_t value)
{
  byte noop_reg = 0x00;    //max72xx No op register
  byte noop_value = 0x00;  //value

  digitalWrite(SPI_CS, LOW);

  for (int i=CUBE_SIZE; i>0; i--)   // Loop through our number of Max72xx ICs
  {
    if (i==whichMax)
    {
      SPI.transfer(address);
      SPI.transfer(value);
    }
    else
    {
      SPI.transfer(noop_reg);
      SPI.transfer(noop_value);
    }
  }

  digitalWrite(SPI_CS, HIGH);
}

void maxTransferLEDCube(uint8_t address)
{
  digitalWrite(SPI_CS, LOW);

  for (int i=0; i<CUBE_SIZE; i++)   // Loop through our number of Max72xx ICs
  {
      SPI.transfer(address);
      SPI.transfer(value[CUBE_SIZE-i-1]);
  }

  digitalWrite(SPI_CS, HIGH);
}

void setUpInterrupts()
{
  cli();//stop interrupts while we set them up
  //set up an interrupt with timer1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;
  OCR1A = (16000000/REFRESH_RATE/1024/CUBE_SIZE -1);
  TCCR1B |= (1 << WGM12);
  // Set to CS10 and CS12 so we have the 1024
  TCCR1B |= (1 << CS12) | (1 << CS10);
  TIMSK1 |= (1 << OCIE1A);
  sei();//re-allow interrupts
}

ISR(TIMER1_COMPA_vect)
{
  for(byte y = 0 ; y < CUBE_SIZE ; y++)
  {
    byte b = 0;

    for(byte x = 0 ; x < CUBE_SIZE ; x++)
    {
      //form data byte
      b = b << 1;

      if (getvoxel(x,y,current_layer)==1)
      {
        b |= 1;
      }
    }
        value[y] = b;
  }

  maxTransferLEDCube(CUBE_SIZE - current_layer);

  current_layer++;

  if (current_layer == 8)
    current_layer = 0;
}


texts: It is possible to revive my Arduino Leonardo (mini beetle) board?

texts:
I have this board:

It has the atmega32u4 chip.

I have updated its code several times, and used it without issues for several months. Today, while updating (using Arduino IDE) it started to throw some errors. At the end it said that the checksum didn't match, so I repeated again few more times with the same behavior until it reported "Uploaded" without errors. I used for few minutes and it was working as expected. Then, I had to do another update and the same happened (checksum didn't match). However this time I got to the point in which it was no longer detected by the OS (Ubuntu), and no LED is turning on.

Whenever I connect it to the USB port, I can only see in the logs:

usb 1-9.4: new full-speed USB device number 9 using xhci_hcd

However /dev/ttyACM0 is not longer created.

I'm trying to use avrdude to reset it, but it is reporting:

avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory

which make sense as /dev/ttyACM0 doesn't exists. So, what are my options? Is there anything I can do to make it work again?

UPDATE

I didn't realize that this board has a reset marked as "RES". Following Juraj recommendation I bridged RES and GND. The LED marked as "SDA" turns ON after I release the contact and I can read in the logs:

[1212051.679205] usb 1-9.4: USB disconnect, device number 22
[1212058.532030] usb 1-9.4: new full-speed USB device number 23 using xhci_hcd
[1212058.621972] usb 1-9.4: New USB device found, idVendor=2341, idProduct=0036
[1212058.621982] usb 1-9.4: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[1212058.621988] usb 1-9.4: Product: Arduino Leonardo
[1212058.621994] usb 1-9.4: Manufacturer: Arduino LLC
[1212058.622933] cdc_acm 1-9.4:1.0: ttyACM0: USB ACM device

Which I think its good news. However, it seems ttyACM0 becomes available for few seconds. I was able to upload the Blink example into the chip and I can confirm its working because its blinking. Still the ttyACM0 disappears after few seconds.

Output of avrdude -c avr109 -p atmega32u4 -P /dev/ttyACM0 :

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.00s
avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: safemode: Fuses OK (E:FB, H:D8, L:FF)
avrdude done.  Thank you.


texts: Webserver on Arduino Mega with Ethernet Shield

texts:
I am working with an official Arduino Mega. I have mounted an officiel Ethernet Shield rev 2.

Everything works great, i have wrote a very basic webserver.

I wanted to host a bootstrap css file on my webserver. This file has a size of about 150 kilo-bytes. So i have inserted an SD card on the Ehternet Shield. I have put my css file on this SD card.

I am writing the content of my css file with this code:

File myFile = SD.open("bootstrap.min.css");
if (myFile)
{
    byte clientBuf[2048];
    int clientCount = 0;
    while (myFile.available())
    {
        clientBuf[clientCount] = myFile.read();
        clientCount++;

        if(clientCount > 2048-1)
        {
            client.write(clientBuf,2048);
            clientCount = 0;
        }
     }
     if(clientCount > 0) client.write(clientBuf,clientCount);
     myFile.close();
 }

It works, but it is very slow.
It takes about 30-40 seconds to load file into my browser.
I have tried to change clientBuf size but this is the optimal value i've set.

Any idea ?

Thanks


texts:
I'm a bit confused about the ESP8266 launching and GPIO behaviour.

When I'm programming the ESP8266 I have to set GPIO2 high and GPIO0 low.
But when I want to use the ESP8266 in my project I have to set GPIO2 and GPIO0 to HIGH, but if they are both high I can't use them as inputs or outputs. So my question is how can I use atleast of the GPIO as an output and starting the ESP8266 without reprogramming it.


texts: How detect I2C errors with requestFrom()

texts:
I am going to use MCP23017 chips, and some of them will be cabled with a 1 meter max unshielded cable. I am expecting that certain transmissions may toss errors. So I want to tackle this problems by using the built in error detection of I2C, polling the inputs frequently (every 20ms or so) and by debouncing the received data in code by comparing the previous state to the current state of every input pin.
If you write bytes to an I2C slave with the Wire library. You can use the return value of Wire.endTransmission(); to test if the slave has acknowledged the message.
How does this work when you are requesting bytes using Wire.requestFrom( address, 3 ); for example. This function does return the amount of received bytes. Can we check this value with the value of the amount of bytes we requested?
I have read the TI document over how I2C works

The master will continue sending out the clockpulses, but will release the SDA line, so that the slave can transmit data. At the end of every byte of data, the master will send an ACK to the slave, letting the slave know that it is ready for more data. Once the master has received the number of bytes it is expecting, it will send a NACK, signaling to the slave to halt communications and release the bus. The master will follow this up with a STOP condition

So the master either ACKs or NACKs a read-in byte. Does the Wire library automatically make several attempts with reading? Oris there something in the Wire library which we can use to detect a failed read operation?
Is it perhaps so that the requestFrom() function may return a different amount of bytes than you requested with which would indicate that atleast 1 read operation failed?
So could I attempt something like
doItAllAgain:

for(int i = 0 ; i < 5 ; i ++ )
{
    Wire.beginTransmission( address ) ;
    Wire.write( register ) ;
    if( !Wire.endTransmission() ) break ; // if no error, break out of for loop
    Serial.println(F("write operation failed");
}

Serial.println(F("write operation succes");

byte requestedBytes = 3 ;
byte returnedBytes = Wire.requestFrom( address, requestedBytes ) ;

if( requestedBytes != returnedBytes )
{
    Serial.println(F("read operation failed");
    goto doItAllAgain ;
}
else
{
    Serial.println(F("read operation also succes");
    byte byte1 = Wire.read() ;
    byte byte2 = Wire.read() ;
    byte byte3 = Wire.read() ;
}


texts: Doubt with the library esp8266wifi and Station Mode

texts:
I have been working for a while with the ESP8266 I have a question:

According to the online documentation of GitHub from the esp8266wifi library I can initialize the WiFi in Station mode to (obviously) connect to a nearby AP, I can initialize the station mode in 3 "different ways":

WiFi.begin (): The module initializes the Station mode and connects to the last network that is connected, because the credentials (SSID and Password) are stored in its internal memory (flash?).
WiFi.begin (ssid, password): The module initializes the Station mode and connects to the network with "ssid" and "password".
WiFi.begin (ssid, password, channel, bssid, connect): The same as the previous one, only that you pass more parameters: the one that interests me is the bssid, which is the MAC address of the AP to which I am going to connect.

Now comes the question: if I wanted to use the last mode, because I want to make sure that the ESP connects ONLY to an AP (a kind of MAC filtering), I also have to specify the channel and set the connect parameter? Or I can simply use something like this:

WiFi.begin ("MyOwnNetwork", "123456789", "00: 1B: 44: 11: 3A: B7")

I can not prove it right now, I do not have the module in my hands.


texts: Is this the right way of using an RF communication?

texts:
I have a 433Mhz Superheterodyne receiver and a hand set remote of similar frequency, I'm using the RC-Switch library and I couldn't find a better way than using the "numbers" that I'm receiving like this:

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
  pinMode(13, OUTPUT);
}

void loop() {
  if (mySwitch.getReceivedValue() == 7264305) {
    digitalWrite(13, LOW);
  }
  if (mySwitch.getReceivedValue() == 7264308) {
    digitalWrite(13, HIGH);
  }
  if (mySwitch.getReceivedValue() == 7264306) {
    mySwitch.resetAvailable();
  }
}

Is there any other (better?) way than just using the "numbers" simply like that or everyone are using their remote commands like I'm using?


texts:
I have an MP3 shield on a Arduino Uno. When using "File Player" I can get the tracks to play by keyboard entry with three digits (001-009).

The problem is that I want to use (SFEMP3Shield > examples > MP3ButtonPlayer2) that is looking for files 1-9. Any file numbers other than 1,2,3,4,5,6,7,8,9 doesn’t work. Any suggestions?


texts: How can I stock data, and send them over by serial?

texts:
I want to make an array with data from the sensor. In data, I have displacement in x/y axis. I want to send them in the array, because in my python code I don't send them one by one, slow down really quickly program.

Arduino code responsible for sensor

class MouseRptParser : public MouseReportParser
{
protected:
 void OnMouseMove (MOUSEINFO *mi);
};

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{

    Serial.print(mi ->dX, DEC);
    Serial.print(",");
    Serial.println(mi ->dY, DEC);

};

I tried to do something on my own, but I get stuck with an error about data not in the scope. I try some variant placing it, but I don't succeed .

class MouseRptParser : public MouseReportParser {

 void OnMouseMove (MOUSEINFO *mi); };

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{ int i;   for (i=0;i<10;i+2)   {
        data[i]=(mi ->dX, DEC);
        data[i+1]=(mi ->dY, DEC);   }
  Serial.println(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8],data[9]);

    delay(20); };

EDIT:  I have now program that's making an array of 10 cells, but values in it are constatnt 10.

#include <hidboot.h>
#include <usbhub.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
int data[10];

class MouseRptParser : public MouseReportParser
{
protected:
 void OnMouseMove (MOUSEINFO *mi);
};

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{

    for (int i=0; i<10; i=i+2)
  {
    data[i]=(mi->dX, DEC);
    data[i+1]=(mi->dY, DEC);

  }
  for(int j=0; j<10; j=j+1)
  {
  Serial.print(data[j]);
  Serial.print(",");
}
Serial.println();
  delay(100);
};

USB     Usb;
USBHub     Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser Prs;

void setup()
{
    Serial.begin( 9600 );
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    //Serial.println("Start");

    if (Usb.Init() == -1)
        Serial.println("OSC did not start.");

    HidMouse.SetReportParser(0, &Prs);
}

void loop()
{

  Usb.Task();

}


texts: Format hour and minute integers to HH:MM format (char*)

texts:
In Arduino code, I'm calling the getTextBounds() and print() API methods on my TFT handler object which accepts char* parameters and I have two integers holding a specific time's hour and minute part, for example:

int _hour = 7;
int _minute = 30;

I need to construct a char* variable that holds this string: 07:30.
What is the simplest way to do that?

I tried this:

char* timestr = (_hour < 10 ? '0' : '') + _hour + ':' + (_minute < 10 ? '0' : '') + _minute;

But it gives me two kind of errors:

error: empty character constant
error: invalid conversion from 'int' to 'char*' [-fpermissive]


texts: PHP/My SQL Database -> to Arduino Serial Monitor

texts:
I'm using this domain http://www.decathlon.commonarchitecture.ca/ to host my phpmyadmin database and php code. I would like to read a specific column of the database in the serial monitor, displaying each number one right after the other. I'm unsure of whether to work with a GSM shield, an Ethernet shield or an Arduino wifi shield. Here is my php code (indents are off I know):

<?php

 $dbhost = "mysql.commonarchitecture.ca";
 $username = "arduinodb";
 $password = "*******";
 $db = "arduinodb" ;

    mysql_connect("$dbhost" , "$username" , "$password");
     //echo "Connected" ;

    //select db
    mysql_select_db($db);
    //echo "Connected to db" ;

  $sql="SELECT * FROM data";

  $records=mysql_query($sql);

 ?>

 <!DOCTYPE html>

 <title> Consumption Data </title>

 Day
 Date
 Water Consumption (liters per person)

 <?php

    while($data=mysql_fetch_assoc($records)) {

         echo "
";

         echo "".$data['id']."	";

         echo "".$data['date']."	";

         echo "".$data['value']."	";

         echo "
";

     }//end while

     ?>

The code works, however I'm unsure of how to go about reading the data on an Arduino (very new to Arduino)

Here's my Arduino code paired with an ethernet shield

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress ip(192, 168, *, *);

EthernetClient client;

char server[] = "www.decathlon.commonarchitecture.ca";

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

  // attempt a DHCP connection:
  Serial.println("Attempting to get an IP address using DHCP:");
  if (!Ethernet.begin(mac)) {
  // if DHCP fails, start with a hard-coded address:
  Serial.println("failed to get an IP address using DHCP, trying
  manually");
     Ethernet.begin(mac, ip);
  }

  Serial.print("My address:");
  Serial.println(Ethernet.localIP());
}

void loop()
{
    // connect to the server
    if (client.connect(server, 80))
    {
        // print to serial monitor
        Serial.println("connected...");
        Serial.println("ARDUINO: forming HTTP request message");

        // send data the server through GET request
        client.print("GET /index.php?value");
        client.println(" HTTP/1.1");
        client.print("HOST:  ");
        client.println(server);

        Serial.println("ARDUINO: HTTP message sent");

        // give server time to receive request
        delay(1000);

        // get the response from the page and print it to serial port
        // to ascertain that request was received properly
        if(client.available())
        {
            Serial.println("ARDUINO: HTTP message received");
            Serial.println("ARDUINO: printing received headers and
script response...\n");

            while(client.available())
            {
                char c = client.read();
                Serial.print(c);
            }
        }
        else
        {
            Serial.println("ARDUINO: no response received / no response
received in time");
        }

        client.stop();
    }
    // do nothing forever after:
    while(true);
}

My issue now is in getting the Arduino to read my php data, can I not use an http GET request to display data in my serial monitor? Am I using this function properly? There's a ton of documentation on posting Arduino sensor data to the web using php/my sql but not as much on retrieval of set data back into the serial monitor. Here's what the monitor reads currently...

Attempting to get an IP address using DHCP:
My address:192.168.*.*
connected...
ARDUINO: forming HTTP request message
ARDUINO: HTTP message sent
ARDUINO: no response received / no response received in time


texts:
I'd like to print a bitmap on my TFT.

I setup my screen with this library: http://forum.arduino.cc/index.php?topic=292777.0

It is like the Adafruit_GFX library (only a little bit changed). Everything works.

With the tool Img2Code I converted my image into a bitmap.

void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
                               const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

How to include this code and print the bitmap on the tft?


texts: HC-SR04 Echo Pin Fails To Go Low After Trigger Pulse

texts: I have implemented an HC-SR04 distance sensor using an Arduino.  After power up, the sensor operates well when objects are within range of the sensor.  However, if the distance to be measured exceeds the maximum (about 15 feet) distance, the sensor times out (which is what I expect).  However, after a time-out and with the distance between the object and the sensor in range, the Echo pin fails to be set low after a trigger pulse is generated.  The only way to fix this condition is to power down the sensor and power it back up again.  (I have verified the state of the Echo pin by using an oscilloscope.)


texts:
I have used with partial success I2C with the ESP8266.  When it works, it works well, with many devices on the bus.  I've examined the signals on a 'scope to assure Vlo, Vhi, Tr, and Tf.

However, often it works not at all.  No I2C devices (even if there is only one connected) are detected.  This condition is determined by some unknown factor, and it stays in this condition for some time (days?) before it starts working again.  Power cycle, reset-by-button, and reset-by-reflashing do not restore operation until it works again.

This has occurred with at least three ESP8266 modules from two different manufacturers with different pinouts.  It affects all connected I2C devices.  They are all slaves to the ESP8266.

What should I try next?


texts: Will an Arduino UNO operating at 16mHz communicate with UART / I2C with an STM32 operating at a different frequency?

texts:
I plan to connect Arduino UNO via I2C / UART with a controller based on STM32F334K8T6, whose frequency will be about 20mHz or higher.

Tell me, does the difference in clock frequencies of microcontrollers affect the operation of buses between them?

The tire speed will be equal. (UART 115200 Baud / I2C 100kHz)


texts: Interfacing accelerometer LSM303DLH with Arduino UNO using I2C

texts:
I am trying to connet a tri axis accelerometer LSM303DLH to arduino UNO using the libraries taken from the following links (https://github.com/adafruit/Adafruit_LSM303DLHC and/or https://github.com/ryantm/LSM303DLH) but none of them work.
Using the following connection:
SCL on A5,
SDA on A4,
Vin on 5V,
Gng on Gnd.

I should be able to see the values of the accelerometer but the serial monitor is empty.

I've tried inserting a few print in the libraries to understand where the execution stops, basically after a Wire.endTrasmission() the program doesn't go forward.
How can I connect the accelerometer using I2C?


texts: How to start a dendrometry dimension build (Dimensions of Trees) for research?

texts: I am looking to build a device that can measure the dendrometry fluctuations of trees (etc). I essentially want to build this https://publiclab.org/notes/kinasmith/09-09-2016/dendrometers to a t but I don't know where to start. I have admittedly pretty limited knowledge of arduino/microcontrollers and microcontroller kits and sensors.


texts: Cannot connect to mBot after using Arduino IDE

texts:
Today I bought an mBot (from Makeblock) the one that uses 2.4G serial connection. After assembling it, I connected to it using mBlock (software based of Scratch) and I could control it using keyboard triggers. Then I went in Arduino IDE and used it to run some scripts on the mBot.

Next I tried to switch back to mBlock software, but now it cannot connect to the mBot anymore. Whatever Scratch-like scrips I build, they don't run anymore in mBlock.

Did I miss anything? Is there anything I can do so I can start using mBlock again?


texts: Various Bluetooth HC-06 modules erratic in different ways

texts:
I am trying to make a Bluetooth controlled robot and have troubles with the Bluetooth modules. I used  3 HC-06 Bluetooth module. All of them have different problems.

I could not find the 1st HC-06 under the list of Bluetooth devices in the settings.
The 2nd HC-06 could be paired with the phone but I could not send the message on the Bluetooth terminal app (The error message from the app is below).
The 3rd HC-06 could be paired and I could send a message but the message was not registered on the Arduino nor on serial monitor. On the Bluetooth terminal app, the message was received but not replied.

What could be the problem? I'm pretty sure my connections are correct as I have checked them and they used to work.


texts: Arduino on battery getting unstable if temperature falls

texts:
i am building an outdoor sensor with a combination of a custom Arduino board and a battery (+solar charging). I experience strange behavior when the temperature falls below a certain value (i can reproduce it by putting it in the freezer), regardless which type of battery i am using. The custom Arduino runs without power-regulation, straight from the 3.7volts the battery can provide.
How can i prevent this to happen? I guess a little heating would be not really a solution as i am trying to consume as less energy as possible.
Would a (step up) regulator possibly help? Any other ideas?

---Update---
Thanks to your comments here i figured out, that the AVR 328p should not be operated below a voltage of 3.7v if run at 16Mhz. As i am running with a 3.7v LiPo Battery that could easily explain my problem i guess. My first try to decrease the processor speed to 8Mhz with a Prescaler worked, but the GSM Fona does not seem to like it. So i would like to try something in between like 10Mhz or 12Mhz. As the prescaler does not support this, my question is: can i just use another crystal or would i have to modify something in the code/bootloader as well?


texts:
I'm working on Arduino uno and trying to use more then one timer.
I'm using timer1 for my software watchdog (I needed bigger interval for that, so my program won't reset itself after 8 seconds).
In addition, I'm using timer2 for regular interrupt like turn off pin after 8 seconds.
The problem is that the timer1's interrupt override timer2's interrupt.

Is it possible to to use both of them?


texts: How to send HTTP requests using wifi of Arduino Primo board?

texts: I have bought an Arduino Primo board. I have configured it to connect to my wifi router and changed it to STA mode. Now, how do I program it to send HTTP requests to a server? Which library file I should use? Any tutorial?


texts: If (serial.available()) conditional statement

texts:
I am very new to Arduino and I have a question I would like to clarify on Serial.Available()

According to Arduino documentation, Available() returns the number of bytes that are stored in the buffer, ready to be read. Why then, both If function below works, when there are data in the buffer? For Scenario A, it appears to me that there is no conditional statement, how then, would the IF function evaluates to TRUE?

Scenario A: IF(Serial.Available())

compare with

Scenario B: IF(Serial.Available()>0)

Thanks in advance!


texts:
I have written a class for generating a 25khz pwm signal for the Arduino Nano. This works great (pin 9 and 10 only) on the Nano. I want to switch to Arduino Every; this code does no longer work (the registers are unknown ‘not declared in this scope’ is the compiler error). The Every is suppose to be a drop in replacement for the Nano; how to generate a 25KHz PWM on the Arduino Every?

#include <Arduino.h>
#include "HixPinPWM25KHz.h"

HixPinPWM25KHz::HixPinPWM25KHz(int nPinNumber): HixPin(nPinNumber) {
}

void HixPinPWM25KHz::begin() {
  //25KHz PWM only supported on ping 9 and 10
  if ( (m_nPinNumber != 9) && (m_nPinNumber != 10) ) {
    return;
  }
  // Configure Timer 1 for PWM @ 25 kHz.
  TCCR1A = 0;           // undo the configuration done by...
  TCCR1B = 0;           // ...the Arduino core library
  TCNT1  = 0;           // reset timer
  TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
           | _BV(COM1B1)  // same on ch; B
           | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
  TCCR1B = _BV(WGM13)   // ditto
           | _BV(CS10);   // prescaler = 1
  ICR1   = 320;         // TOP = 320
  pinMode(m_nPinNumber, OUTPUT);
  analogWrite(50);
}

void HixPinPWM25KHz::analogWrite(float percent) {
  int value = (int) ( (percent * (float)320) / (float)100 );
  switch (m_nPinNumber) {
    case 9:
      OCR1A = value;
      break;
    case 10:
      OCR1B = value;
      break;
    default:
      // no other pin will work
      break;
  }
}