ESP32 changing clock frequency (C) - c

I am programming an ESP32 with C (with the toolchain for ESP32) and I'm trying to change the clock frequency of my ESP32 but I'm quite unsure if I'm doing it right (I used the documenation https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/power_management.html#_CPPv418esp_pm_lock_type_t but I didn't find any code examples). I think I've done the program part right but I think it still doesn't work. Is there a way to figure out the the clock frequency that is set?
I'm also unsure about this part in documentation:
"ESP_PM_CPU_FREQ_MAX
Require CPU frequency to be at the maximum value set via esp_pm_configure. Argument is unused and should be set to 0."
Does the last part mean I shouldn't use this makro?
Last but not least I didnt't understand if I have to change my sdkconfig or is there a way to do everything in C?
I have to measure for a project times in region of ns hence I need maximum performance of esp32.
Code:
// ____________________________________________________________________________
esp_pm_config_esp32_t config_clock_struct;
// ____________________________________________________________________________
esp_pm_config_esp32_t* pointer_config_clock = &config_clock_struct;
// ____________________________________________________________________________
esp_pm_lock_handle_t handle;
void config_clock(int max_cpu_freq, int min_cpu_freq, bool light_sleep_enable,
esp_pm_config_esp32_t* pointer_config_clock) {
pointer_config_clock->max_freq_mhz = max_cpu_freq;
pointer_config_clock->min_freq_mhz = min_cpu_freq;
pointer_config_clock->light_sleep_enable = light_sleep_enable;
esp_err_t status = esp_pm_configure(pointer_config_clock);
if (status == ESP_OK) {
return;
} else if (status == ESP_ERR_INVALID_ARG) {
printf("Error %d: Configuration values aren't correct.", status);
exit(1);
} else if (status == ESP_ERR_NOT_SUPPORTED) {
printf("Error %d: Combination of values aren't supported or CONFIG_PM_ENABLE isn't enabled in sdkconfig.",
status);
exit(1);
}
}
// ____________________________________________________________________________
void init_clock(int max_cpu_freq, int min_cpu_freq, bool light_sleep_enable,
esp_pm_lock_type_t lock_type, int arg, const char* name,
esp_pm_config_esp32_t* pointer_config_clock, esp_pm_lock_handle_t* out_handle) {
config_clock(max_cpu_freq, min_cpu_freq, light_sleep_enable, pointer_config_clock);
esp_err_t status = esp_pm_lock_create(lock_type, arg, name, out_handle);
if (status == ESP_OK) {
return;
} else if (status == ESP_ERR_NO_MEM) {
printf("Error %d: Struct can't allocated.", status);
} else if (status == ESP_ERR_INVALID_ARG) {
printf("Error: %d: Invalid arguments.", status);
} else if(ESP_ERR_NOT_SUPPORTED == status) {
printf("Error %d: config pm is not enabled in sdkconfig.", status);
}
}
And the relevant part of the main function:
#define MAX_FREQUENCY 240
#define MIN_FREQUENCY 40
#define DISABLE_SLEEP 0
init_clock(MAX_FREQUENCY, MIN_FREQUENCY, DISABLE_SLEEP, ESP_PM_CPU_FREQ_MAX, ESP_PM_CPU_FREQ_MAX,
"measure mode", pointer_config_clock, &handle);
esp_err_t status_acquire = esp_pm_lock_acquire(handle);

When one changes MCU clock frequency it alters all frequency dependent buses. For instance UART and I2C. Here's a neat hack to demonstrate how changing of clock frequency affects serial.print output. Mind you calculated Serial baud rates differ for each clock speed set.
//function takes the following frequencies as valid values:
// 240, 160, 80 <<< For all XTAL types
// 40, 20, 10 <<< For 40MHz XTAL
// 26, 13 <<< For 26MHz XTAL
// 24, 12 <<< For 24MHz XTAL
// 32Bit MCUs . change for 16bit
uint32_t Freq = 0;
int MCU_FREQUENCY_SERIAL_SPEED=115200;
int SERIAL_DEFAULT_SPEED = 115200;
void changeMcuFreq(int Freq){
delay(500);
setCpuFrequencyMhz(Freq);
changeSerialBaudRate(Freq);
delay(500);
}
void serialMcuFreq(){
Freq = getCpuFrequencyMhz();
Serial.print("CPU Freq = ");
Serial.print(Freq);
Serial.println(" MHz");
Freq = getXtalFrequencyMhz();
Serial.print("XTAL Freq = ");
Serial.print(Freq);
Serial.println(" MHz");
Freq = getApbFrequency();
Serial.print("APB Freq = ");
Serial.print(Freq/1000000);
Serial.println(" MHz");
}
void changeSerialBaudRate(uint32_t Freq){
if (Freq < 80) {
MCU_FREQUENCY_SERIAL_SPEED = 80 / Freq * SERIAL_DEFAULT_SPEED;
}
else {
MCU_FREQUENCY_SERIAL_SPEED = SERIAL_DEFAULT_SPEED;
}
Serial.end();
delay(1000);
Serial.begin(MCU_FREQUENCY_SERIAL_SPEED);
delay(1000);
Serial.print("\nSerial Baud Rate Speed is ");
Serial.println(MCU_FREQUENCY_SERIAL_SPEED);
}
void setup()
{
Serial.begin(MCU_FREQUENCY_SERIAL_SPEED);
}
void loop()
{
changeMcuFreq(240);
serialMcuFreq();
delay(2000);
changeMcuFreq(160);
serialMcuFreq();
delay(2000);
changeMcuFreq(80);
serialMcuFreq();
delay(2000);
changeMcuFreq(40);
serialMcuFreq();
delay(2000);
changeMcuFreq(20);
serialMcuFreq();
delay(2000);
changeMcuFreq(10);
serialMcuFreq();
delay(2000);
}

Related

How to update the LED on a TI board and report to the server every second via UART

I am modifying a code in embedded C language and trying to make it to where it checks buttons every 200ms, checks the temperature every 500ms, and update the LED and report to the server every second. My code appears to be complete but when I run it, nothing outputs to the console, and my LED light neither turns off or on when I press either buttons on the side of the TI board. Is there something wrong with my nested while loop? Here is my code:
/*
* ======== gpiointerrupt.c ========
*/
#include <stdint.h>
#include <stddef.h>
/* Driver Header files */
#include <ti/drivers/GPIO.h>
#include <ti/drivers/I2C.h>
#include <ti/drivers/UART.h>
/* Driver configuration */
#include "ti_drivers_config.h"
/* Driver timer */
#include <ti/drivers/Timer.h>
#define TRUE 1
#define FALSE 0
#define NUMBER_OF_TASKS 3
#define GLOBAL_PERIOD 100 //milliseconds
#define DISPLAY(x) UART_write(uart, &output, x);
// UART Global Variables
char output[64];
int bytesToSend;
// Driver Handles - Global variables
UART_Handle uart;
// Init variables
int buttonCheckTime = 0;
int tempCheckTime = 0;
int displayCheckTime = 0;
int buttonCheckPeriod = 200;
int tempCheckPeriod = 500;
int displayCheckPeriod = 1000;
int setpoint = 25;
int heat = 0;
int seconds = 0;
int temperature = 0;
int firstButtonWasPressed = FALSE; // It is initally false that the button was pressed
int secondButtonWasPressed = FALSE; // It is initally false that the button was pressed
int global_period = GLOBAL_PERIOD; // Global period to be used initTimer()
void initUART(void)
{
UART_Params uartParams;
// Init the driver
UART_init();
// Configure the driver
UART_Params_init(&uartParams);
uartParams.writeDataMode = UART_DATA_BINARY;
uartParams.readDataMode = UART_DATA_BINARY;
uartParams.readReturnMode = UART_RETURN_FULL;
uartParams.baudRate = 115200;
// Open the driver
uart = UART_open(CONFIG_UART_0, &uartParams);
if (uart == NULL)
{
/* UART_open() failed */
while (1)
;
}
}
// I2C Global Variables
static const struct
{
uint8_t address;
uint8_t resultReg;
char *id;
} sensors[3] = { { 0x48, 0x0000, "11X" }, { 0x49, 0x0000, "116" }, { 0x41,
0x0001,
"006" } };
uint8_t txBuffer[1];
uint8_t rxBuffer[2];
I2C_Transaction i2cTransaction;
// Driver Handles - Global variables
I2C_Handle i2c;
// Initialize the I2C peripheral
// Make sure you call initUART() before calling this function.
void initI2C(void)
{
int8_t i, found;
I2C_Params i2cParams;
DISPLAY(snprintf(output, 64, "Initializing I2C Driver - "))
// Init the driver
I2C_init();
// Configure the driver
I2C_Params_init(&i2cParams);
i2cParams.bitRate = I2C_400kHz;
// Open the driver
i2c = I2C_open(CONFIG_I2C_0, &i2cParams);
if (i2c == NULL)
{
DISPLAY(snprintf(output, 64, "Failed\n\r"))
while (1)
;
}
DISPLAY(snprintf(output, 32, "Passed\n\r"))
// Boards were shipped with different sensors.
// Welcome to the world of embedded systems.
// Try to determine which sensor we have.
// Scan through the possible sensor addresses
/* Common I2C transaction setup */
i2cTransaction.writeBuf = txBuffer;
i2cTransaction.writeCount = 1;
i2cTransaction.readBuf = rxBuffer;
i2cTransaction.readCount = 0;
found = false;
for (i = 0; i < 3; ++i)
{
i2cTransaction.slaveAddress = sensors[i].address;
txBuffer[0] = sensors[i].resultReg;
DISPLAY(snprintf(output, 64, "Is this %s? ", sensors[i].id))
if (I2C_transfer(i2c, &i2cTransaction))
{
DISPLAY(snprintf(output, 64, "Found\n\r"))
found = true;
break;
}
DISPLAY(snprintf(output, 64, "No\n\r"))
}
if (found)
{
DISPLAY(snprintf(output, 64, "Detected TMP%s I2C address: %x\n\r",
sensors[i].id, i2cTransaction.slaveAddress))
}
else
{
DISPLAY(snprintf(output, 64,
"Temperature sensor not found, contact professor\n\r"))
}
}
int16_t readTemp(void)
{
int j;
int16_t temperature = 0;
i2cTransaction.readCount = 2;
if (I2C_transfer(i2c, &i2cTransaction))
{
/*
* Extract degrees C from the received data;
* see TMP sensor datasheet
*/
temperature = (rxBuffer[0] << 8) | (rxBuffer[1]);
temperature *= 0.0078125;
/*
* If the MSB is set '1', then we have a 2's complement
* negative value which needs to be sign extended
*/
if (rxBuffer[0] & 0x80)
{
temperature |= 0xF000;
}
}
else
{
DISPLAY(snprintf(output, 64, "Error reading temperature sensor (%d)\n\r", i2cTransaction.status))
DISPLAY(snprintf(output,64, "Please power cycle your board by unplugging USB and plugging back in.\n\r"))
}
return temperature;
}
// Driver Handles - Global variables
Timer_Handle timer0;
volatile unsigned char TimerFlag = 0;
// A single task in the task list.
struct task_entry
{
void (*f)(); // Function to call to perform the task
int elapsed_time; // Amount of time since last triggered
int period; // Period of the task in ms
char triggered; // Whether or not the task was triggered
};
// Forward declaration
void task_one();
void task_two();
void task_three();
void task_one()
{
// Processing for task_one takes place
/* Every 200ms, check button presses */
if (buttonCheckTime >= buttonCheckPeriod) // Button check time equals or exceeds period
{
if (firstButtonWasPressed == TRUE) // Button on one side raises setpoint (thermostat setting) by 1
{
setpoint += 1; // Increment thermostat
firstButtonWasPressed = FALSE; // Reset button to FALSE
}
if (secondButtonWasPressed == TRUE) // Button on the other side lowers setpoint (thermostat setting) by 1
{
setpoint -= 1; // Decrement thermostat
secondButtonWasPressed = FALSE; // Reset button to FALSE
}
}
}
void task_two()
{
// Processing for task_two takes place
if (tempCheckTime >= tempCheckPeriod) // Temperature check time equals or exceeds period
{
temperature = readTemp();
if (temperature > setpoint) {
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_OFF);
heat = 0;
}
else {
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
heat = 1;
}
}
}
void task_three()
{
// Processing for task_three takes place
if (displayCheckTime == displayCheckPeriod) {
DISPLAY(snprintf(output, 64, "<%02d,%02d,%d,%04d>\n\r", temperature,
setpoint, heat, seconds));
++seconds;
}
}
// The task list
struct task_entry tasks[NUMBER_OF_TASKS] = { { FALSE, &task_one, 500, 500 }, {FALSE, &task_two, 1500, 1500 }, { FALSE, &task_three, 2000, 2000 } };
void timerCallback(Timer_Handle myHandle, int_fast16_t status)
{
int x = 0;
// Walk through each task.
for (x = 0; x < NUMBER_OF_TASKS; x++)
{
// Check if task's interval has expire
if (tasks[x].elapsed_time >= tasks[x].period)
{
// Bing! This task's timer is up
// Set it's flag, and the global flag
tasks[x].triggered = TRUE;
TimerFlag = TRUE;
// Reset the elapsed_time
tasks[x].elapsed_time = 0;
}
else
{
tasks[x].elapsed_time += global_period;
}
}
}
void initTimer(void)
{
Timer_Params params;
// Init the driver
Timer_init();
// Configure the driver
Timer_Params_init(&params);
params.period = 1000000;
params.periodUnits = Timer_PERIOD_US;
params.timerMode = Timer_CONTINUOUS_CALLBACK;
params.timerCallback = timerCallback;
// Open the driver
timer0 = Timer_open(CONFIG_TIMER_0, &params);
if (timer0 == NULL)
{
/* Failed to initialized timer */
while (1)
{
}
}
if (Timer_start(timer0) == Timer_STATUS_ERROR)
{
/* Failed to start timer */
while (1)
{
}
}
}
/*
* ======== gpioButtonFxn0 ========
* Callback function for the GPIO interrupt on CONFIG_GPIO_BUTTON_0.
*
* Note: GPIO interrupts are cleared prior to invoking callbacks.
*/
void gpioButtonFxn0(uint_least8_t index)
{
/* Toggle an LED */
//GPIO_toggle(CONFIG_GPIO_LED_0);
firstButtonWasPressed = TRUE; // It is true that the button was pressed
}
/*
* ======== gpioButtonFxn1 ========
* Callback function for the GPIO interrupt on CONFIG_GPIO_BUTTON_1.
* This may not be used for all boards.
*
* Note: GPIO interrupts are cleared prior to invoking callbacks.
*/
void gpioButtonFxn1(uint_least8_t index)
{
/* Toggle an LED */
//GPIO_toggle(CONFIG_GPIO_LED_1);
secondButtonWasPressed = TRUE;
}
/*
* ======== mainThread ========
*/
void* mainThread(void *arg0)
{
/* Call driver init functions */
GPIO_init();
/* Configure the LED and button pins */
GPIO_setConfig(CONFIG_GPIO_LED_0, GPIO_CFG_OUT_STD | GPIO_CFG_OUT_LOW);
//GPIO_setConfig(CONFIG_GPIO_BUTTON_0;
//GPIO_CFG_IN_PU | GPIO_CFG_IN_INT_FALLING);
/* Turn on user LED */
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
/* Install Button callback */
GPIO_setCallback(CONFIG_GPIO_BUTTON_0, gpioButtonFxn0);
/* Enable interrupts */
GPIO_enableInt(CONFIG_GPIO_BUTTON_0);
/*
* If more than one input pin is available for your device, interrupts
* will be enabled on CONFIG_GPIO_BUTTON1.
*/
if (CONFIG_GPIO_BUTTON_0 != CONFIG_GPIO_BUTTON_1)
{
/* Configure BUTTON1 pin */
GPIO_setConfig(CONFIG_GPIO_BUTTON_1,
GPIO_CFG_IN_PU | GPIO_CFG_IN_INT_FALLING);
/* Install Button callback */
GPIO_setCallback(CONFIG_GPIO_BUTTON_1, gpioButtonFxn1);
/* Enable interrupts */
GPIO_enableInt(CONFIG_GPIO_BUTTON_1);
}
// Call driver init functions
initUART(); // The UART must be initialized before calling initI2C()
initI2C();
initTimer();
// Loop Forever
while (TRUE)
{
readTemp();
// Every 200ms check the button flags
task_one();
// Every 500ms read the temperature and update the LED
task_two();
// Every second output the following to the UART
// "<%02d,%02d,%d,%04d>, temperature, setpoint, heat, seconds
task_three();
// Wait for task intervals (periods) to elapse
while (!TimerFlag)
{
} // Wait for timer period
// Process the tasks for which the interval has expired
int x = 0;
for (x = 0; x < NUMBER_OF_TASKS; x++)
{
if (tasks[x].triggered)
{
tasks[x].f();
// reset
tasks[x].triggered = FALSE;
}
}
// Reset everything (e.g. flags) and go back to the beginning
TimerFlag = FALSE; // Lower flag raised by timer
++global_period;
}
}

SPI Communication between ATMEGA 324PB and Arduino Nano

Here I'm trying to Send the SPI command from the master (Arduino Nano) to the slave(ATMEGA324PB).
First Master receives a command from the serial monitor. When the serial message receives completely, the Master passes the message to the Slave. Whenever the slave has a message to send, it will interrupt the Arduino nano using pin 3. However, in the first round slave send messages to master, and master can read it successfully. But in the second round It couldn't happen. I was unable to find the issue. I will attach the codes below.
User message is like in this manner XF01600#.
Send X (or Y)
Send F (or B)
Send 01600
Send #
This is my Master Code :
` #include <SPI.h>`
char Direction;
char Axis;
char TxCommand;
char TxEnd;
bool stringComplete = false; // Is receive complete ?
bool TxComplete=false;
int k=0;
int j=0;
String StepCount;
SPISettings setting(200000,MSBFIRST,SPI_MODE0);
void setup() {
Serial.begin(9600);
pinMode(10,OUTPUT);
pinMode(9,OUTPUT);
pinMode(2,OUTPUT);
attachInterrupt(digitalPinToInterrupt(3),SlaveReceive,RISING);
SPI.begin();
}
void SlaveReceive(){
SPI.begin();
SPI.beginTransaction(setting);
digitalWrite(10,LOW);
TxCommand=SPI.transfer(0xFF);//dummy
TxEnd=SPI.transfer(0xFF);//dummy
digitalWrite(10,HIGH);
SPI.endTransaction();
Serial.print("Received Command-");
Serial.println(TxCommand );
Serial.print("Received End-");
Serial.println(TxEnd);
if(TxEnd=='~'){
TxComplete=true;
}
}
void SPI_Transfer(){
SPI.transfer(Direction);//transfer direction
delay(5);
SPI.transfer(StepCount.length());//transfer incoming step length
delay(5);
for(int i=0;i<StepCount.length();i++){//transfer step count;
SPI.transfer(StepCount[i]);
Serial.println(StepCount[i]);
delay(5);
}
SPI.transfer('#');
delay(5);
}
void loop() {
if (stringComplete) {
if(Direction=='F'){
digitalWrite(2,HIGH);
}
else if(Direction=='B'){
digitalWrite(2,LOW);
}
Serial.print("Direction-");
Serial.println(Direction);
Serial.println(StepCount);
Serial.println(StepCount.length());
SPI.beginTransaction(setting);
if(Axis=='X'){ // Chip Select line for X axis driver is pin 10;
digitalWrite(10,LOW);
SPI_Transfer();
digitalWrite(10,HIGH);
}
else if(Axis=='Y'){ /// Chip select line for Y axis driver is pin 9;
digitalWrite(9,LOW);
SPI_Transfer();
digitalWrite(9,HIGH);
}
SPI.endTransaction();
stringComplete = false;
k=0;
}
if(TxComplete){
if(TxCommand=='S'){
digitalWrite(2,LOW);
TxComplete=false;
}
}
}
void serialEvent() {
while (Serial.available()>0) {
if(k==0){
Axis = Serial.read();
k++;
}
else if(k==1){
Direction=Serial.read();
k++;
}
else if(Serial.read()!='#'){
//StepCount[k-1]=Serial.readString();
StepCount=Serial.parseInt();
k++;
}
else{
stringComplete = true;
}
}
}
Slave Main Command :
while(1){
if(SPI_RECEIVE_COMPLETE){
SPI_RECEIVE_COMPLETE=false;
PORTA |=(1<<4);
Decode_SPI_Command();
switch (SPI_Command)
{
case 'F':
_Run_Motor(SPI_Data, true, 1, 0.3);//10 CYCLE
SlaveSendData(0x53);//S
break;
case 'B':
_Run_Motor(SPI_Data, false, 1, 0.3);
SlaveSendData(0x53);//S
break;
}
for(uint8_t i=0;i<15;i++){
SPI_Received_Data[i]=0;
}
SPI_Data=0;
SPI_BYTES_Transfer=0;
}
PORTA &=~(1<<4);
}
The Slave data send function:
void SlaveSendData(uint8_t SlaveCommand){
SPI_BYTES_Transfer=0;
SPI_Data_TX=true;
SPDR1=SlaveCommand;
SPI_Transmit_Data[0]=0x7E;//~
PORTA |=(1<<3);
_delay_ms(10);
PORTA &=~(1<<3);
}
Slave SPI interrupt function:
ISR(SPI1_STC_vect){
if(SPI_Data_TX){//slave is transmitting data
SPDR1 = SPI_Transmit_Data[SPI_BYTES_Transfer];
SPI_BYTES_Transfer++;
if(SPI_Received_Data[SPI_BYTES_Transfer-1]=='~'){
SPI_Data_TX=false;
//SPDR1=0x00;
SPI_BYTES_Transfer=0;
}
}
else{
SPI_Received_Data[SPI_BYTES_Transfer] = SPDR1;
SPI_BYTES_Transfer++;
if(SPI_Received_Data[SPI_BYTES_Transfer-1]=='#'){
SPI_RECEIVE_COMPLETE=true;
SPDR1=0x00;
}
}
}
Here I have found that in the else part SPI_RECEIVE_COMPLETE=true; never occurs on the second try. But I couldn't find where the issue is..?
serial monitor
Arduino Serial Monitor
Could you please take a look, Thank you.

Project: NodeMCU esp8266-esp12e to connect to another esp8266-esp12e - social distancing

I need to ring the buzzer within the range of 1 meter only, my esp8266 is connected to a buzzer but the buzzer will ring on and off within the range of 1 meter using two esp8266, or sometimes it does not ring at all. The project is social distancing, what else should I do? Here is the code I am using:
#include <ESP8266WiFi.h>
const char* APssid = "Social Distancing"; //acess point of the device
const char* APpassword = "qwertyuiop";
const int RSSI_MAX = -37;//maximum strength of signal in dBm
const int RSSI_MIN =-100;//minimum strength of signal in dBm
void setup()
{
WiFi.mode(WIFI_OFF);
WiFi.disconnect();
delay(50); //this part turns off the wifi and resets it if it was already on
Serial.begin(115200);
pinMode(14,OUTPUT);
Serial.println();
WiFi.mode(WIFI_AP_STA); //configuring the board in hybrid mode
Serial.print("Configuring access point...");
WiFi.softAP(APssid, APpassword);
Serial.println(WiFi.softAPIP());
}
void loop()
{
Serial.println("Wifi is scanning");
int n = WiFi.scanNetworks();
Serial.println("Wifi scan ended");
if (n == 0)
{
Serial.println("no networks found");
}
else
{
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i)
{
//Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(") ");
Serial.print(WiFi.SSID(i));//SSID
Serial.print(WiFi.RSSI(i));//Signal strength in dBm
Serial.print("dBm (");
if(WiFi.SSID(i) == "Social Distancing")
{
if(WiFi.RSSI(i) > -37)//THIS -37 (RSSI) is the threshold value, this value is set
according to the distance of 1m
{
digitalWrite(14,HIGH);//(Generic esp8266 : (14,HIGH) , NodeMCU : (D5,HIGH) )
Serial.println("Social Distancing");
break;
}
}
else
{
digitalWrite(14,LOW);
}
}
delay(50);
}
Serial.println("");
delay(50);
WiFi.scanDelete();
}
Hi Lisa I have modified your code and I have added a 64x48 OLED display connected to the I2C connections, to visualize the results and it works beautifully. Moreover I have used the built in led (see: LED_BUILTIN) instead of the buzzer.
You have had a great idea. Now it works great and you can interrogate any Access point.
Please find attached the code:
//OLED
#include <Arduino.h>
#include <U8g2lib.h>
#include <U8x8lib.h> //this one in use
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
U8X8_SSD1306_64X48_ER_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); // EastRising 0.66" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered
// End of constructor list
#define U8LOG_WIDTH 16
#define U8LOG_HEIGHT 8
uint8_t u8log_buffer[U8LOG_WIDTH*U8LOG_HEIGHT];
U8X8LOG u8x8log;
//OLED end
#include <ESP8266WiFi.h>
const char* APssid = "My_SSID"; //acess point of the device
const char* APpassword = "My_Password";
//const char* myconstcharstarstring = "------------------------------";
const int RSSI_MAX = -37;//maximum strength of signal in dBm
const int RSSI_MIN =-100;//minimum strength of signal in dBm
void setup()
{
//OLED
u8x8.begin();
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8log.begin(u8x8, U8LOG_WIDTH, U8LOG_HEIGHT, u8log_buffer);
u8x8log.setRedrawMode(1); // 0: Update screen with newline, 1: Update screen for every char
//OLED end
WiFi.mode(WIFI_OFF);
WiFi.disconnect();
delay(50); //this part turns off the wifi and resets it if it was already on
Serial.begin(115200);
pinMode(LED_BUILTIN,OUTPUT);
Serial.println();
WiFi.mode(WIFI_AP_STA); //configuring the board in hybrid mode
Serial.print("Configuring access point...");
WiFi.softAP(APssid, APpassword);
Serial.println(WiFi.softAPIP());
}
void loop()
{
digitalWrite(LED_BUILTIN,LOW);
Serial.println("Wifi is scanning");
int n = WiFi.scanNetworks();
Serial.println("Wifi scan ended");
if (n == 0)
{
Serial.println("no networks found");
}
else
{
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i)
{
//Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(") ");
Serial.print(WiFi.SSID(i));//SSID
Serial.print(WiFi.RSSI(i));//Signal strength in dBm
Serial.print("dBm (");
if(WiFi.RSSI(i) > -37)//THIS -37 (RSSI) is the threshold value, this value is set according to the distance of 1m
{
digitalWrite(LED_BUILTIN,HIGH);//(Generic esp8266 : (14,HIGH) , NodeMCU : (D5,HIGH) )
Serial.println("Social Distancing");
delay(500);
}
//OLED
u8x8log.print(WiFi.SSID(i));
u8x8log.print("\n");
u8x8log.print(WiFi.RSSI(i));
u8x8log.print("\n");
u8x8log.print("-------------");
u8x8log.print("\n");
delay(2000);
}
Serial.println("");
delay(50);
WiFi.scanDelete();
}
}
Hope this answers All the best
Hi Lisa please add digitalWrite(14,HIGH); at the beginning of the loop, it will work:
void loop()
{
digitalWrite(14,HIGH);
/... rest of your code...
I don't know how you have wired your buzzer, try forcing your ouput pin HIGH or LOW depending on your circuit.
Hope this helps All the best

Arduino serial works fine with Debian but hangs with Raspbian

I'm working on a personal home automation project.
On the server side, I have an Arduino Pro Mini with:
a 433 MHz TX module on pin 2
a 433 MHz RX module on pin 3
a DHT22 probe on pin 4 (with 10k pull-up)
a DHT22 probe on pin 5 (with 10k pull-up)
I have two absolutely identical of these modules; one will be the radio relay (and DHT "server") and the other a secondary DHT "server".
When it is linked to my laptop (Debian Wheezy) through an FTDI cable, it can read both local probes and switch my wall plugs on/off thanks to a C program I wrote. I'd like to use it from a Raspberry Pi. But on the Raspberry Pi (with the same FTDI cable on USB), it executes the first command I send and then hangs my terminal, forcing me to use CTRL+C.
Here is the sketch on the Arduino side (header) :
/**
* probe.h
*
* #author David Mézière <...>
*/
/**
* DHT probe result
*
*/
struct Probe {
float temperature;
float humidity;
};
Main file :
/**
* probe.ino
*
* #author David Mézière <...>
*/
#include "probe.h"
/**
* Uses DHT sensor library, from Adafruit.
* #see https://github.com/adafruit/DHT-sensor-library
*/
#include <DHT.h>
/**
* Uses RC Switch library, from sui77.
* #see https://github.com/sui77/rc-switch
*/
#include <RCSwitch.h>
// Pinout definitions
#define TX 2 // 433 MHz transmitter pin number
#define RX 3 // 433 MHz receiver pin number
#define PROBE1 4 // First DHT22 probe pin number
#define PROBE2 5 // Second DHT22 probe pin number
#define LED 13 // On-board status LED pin number
RCSwitch radio = RCSwitch();
// DHT probes definition
DHT dht1(PROBE1, DHT22);
DHT dht2(PROBE2, DHT22);
// Incomming command buffer
byte cmd[9];
/**
* Setup
*
* #return void
*/
void setup()
{
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
Serial.begin(9600);
Serial.setTimeout(1000); // doesn't fix the problem
// Attach receiver to interrupt 1, meaning pin 3
radio.enableReceive(1);
radio.enableTransmit(TX);
dht1.begin();
dht2.begin();
// Debug: Internal LED will blink 3 times rapidly to show when a reboot occurs.
for (int i = 0; i < 3; i++) {
digitalWrite(LED, HIGH);
delay(250);
digitalWrite(LED, LOW);
delay(250);
}
}
/**
* Loop
*
* #return void
*/
void loop()
{
if (Serial.available() == 9 && readCommand()) {
// Lights-up internal LED to show when a command has been executed
digitalWrite(LED, HIGH);
delay(1000);
digitalWrite(LED, LOW);
}
}
/**
* Query probe
*
* Query provided [dht] probe until [retry] times for both temperature and humidity.
*
* #param DHT dht Pointer to DHT object
* #param int retry Number of tries
* #return Probe Probe result (float temperature in °C, float humidity in %)
*/
Probe queryProbe(DHT* dht, int retry)
{
Probe probe;
// Query DHT22 probe for temperature, a maximum of [retry] times.
for (int t = 0; t < retry; t++) {
probe.temperature = dht->readTemperature(false);
if (!isnan(probe.temperature)) {
break;
}
delay(50);
}
// Query DHT22 probe for humidity, a maximum of [retry] times.
for (int h = 0; h < retry; h++) {
probe.humidity = dht->readHumidity();
if (!isnan(probe.humidity)) {
break;
}
delay(50);
}
return probe;
}
/**
* Read command
*
* If serial buffer contains 2 bytes, move them to a local buffer and return true. else return false.
*
* #return boolean
*/
boolean readCommand()
{
// Reads the current buffer
Serial.readBytes(cmd, 9);
// Calculates the check sum of payload
int sum = cmd[2] ^ cmd[3] ^ cmd[4] ^ cmd[5] ^ cmd[6] ^ cmd[7];
// Checking header and checksum a header of 0xBA 0xB1 means DHT query
if (cmd[0] == 0xBA && cmd[1] == 0xB1 && cmd[8] == sum) {
unsigned int module = cmd[2];
unsigned int probe = (cmd[4] << 24) + (cmd[5] << 16) + (cmd[6] << 8) + cmd[7];
Probe result;
switch (module) {
case 1:
// Selects the right probe
if (probe == 1) {
result = queryProbe(&dht1, 3);
} else if (probe == 2) {
result = queryProbe(&dht2, 3);
}
// Send status repport to client
Serial.print("1;");
Serial.print(module);
Serial.print(";");
Serial.print(probe);
Serial.print(";");
Serial.print(result.temperature);
Serial.print(";");
Serial.println(result.humidity);
Serial.flush(); // Doesn't fix the problem
break;
}
return true;
// A header of 0xBA 0xB2 means rf wall plugs query
} else if (cmd[0] == 0xBA && cmd[1] == 0xB2 && cmd[8] == sum) {
unsigned int proto = cmd[2];
unsigned int length = cmd[3];
unsigned int value = (cmd[4] << 24) + (cmd[5] << 16) + (cmd[6] << 8) + cmd[7];
radio.send(value, length);
// Send status repport to client
Serial.print("2;");
Serial.print(proto);
Serial.print(";");
Serial.print(length);
Serial.print(";");
Serial.print(value);
Serial.print(";");
Serial.println("OK");
Serial.flush(); // Doesn't fix the problem
return true;
} else {
Serial.println("KO");
Serial.flush(); // Doesn't fix the problem
return false;
}
}
And on the client side :
/**
* probe.c
*
* #author David Mézière <...>
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <getopt.h>
const char* device;
static int module = 0; // uint_8 ?
static int probe = 0; // uint_8 ?
const char* proto;
static int length = 0; // uint_8 ?
static int value = 0; // uint_32 ?
static int verbose = 0; // uint_8 ?
void help()
{
printf("usage:\n");
printf("\n");
printf("probe [options] [arguments]\n");
printf("\n");
printf("options:\n");
printf(" -h|--help: Displays this help and exit\n");
printf(" -v|--verbose: Be more verbose\n");
printf("\n");
printf("arguments:\n");
printf(" -d|--device: string Serial device to use (ex: /dev/ttyUSB0)\n");
printf(" -m|--module: integer DHT22 module to query\n");
printf(" -p|--probe: integer DHT22 probe to query\n");
printf(" -r|--proto: string Radio / IR protocol\n");
printf(" -l|--length: integer Radio / IR value length in bits\n");
printf(" -a|--value: integer Radio / IR value\n");
printf("\n");
printf("examples:\n");
printf(" probe --device /dev/ttyUSB0 --module 1 --probe 1 : Will query first DHT22 probe of first module\n");
printf(" probe --proto radio1 --length 12 --value 5393 : Will send value 5393 on 12 bits over the air using protocol 1\n");
printf(" probe --proto ir11 --length 64 --value 3772793023 : Will send value 3772793023 on 64 bits by infra red using protocol 11\n");
}
void parseArgs(int argc, char **argv)
{
int c;
while (1) {
static struct option long_options[] = {
{"device", required_argument, 0, 'd'},
{"help", no_argument, 0, 'h'},
{"module", required_argument, 0, 'm'},
{"probe", required_argument, 0, 'p'},
{"proto", required_argument, 0, 'r'},
{"length", required_argument, 0, 'l'},
{"value", required_argument, 0, 'a'},
{"verbose", no_argument, 0, 'v'},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long(argc, argv, "d:hm:p:v", long_options, &option_index);
/* Detect the end of the options. */
if (c == -1) {
break;
}
switch (c) {
case 0:
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0) {
break;
}
printf("option %s", long_options[option_index].name);
if (optarg) {
printf (" with arg %s", optarg);
}
printf("\n");
break;
case 'd':
device = optarg;
break;
case 'h':
help();
exit(0);
break;
case 'm':
module = atoi(optarg);
break;
case 'p':
probe = atoi(optarg);
break;
case 'r':
proto = optarg;
break;
case 'l':
length = atoi(optarg);
break;
case 'a':
value = atoi(optarg);
break;
case 'v':
verbose = 1;
break;
case '?':
/* getopt_long already printed an error message. */
break;
default:
abort();
}
}
/* Print any remaining command line arguments (not options). */
if (optind < argc) {
printf("non-option ARGV-elements: ");
while (optind < argc) {
printf("%s ", argv[optind++]);
}
putchar('\n');
}
if (&device[0] == '\0') {
fprintf(stderr, "--device is mandatory\n");
exit(1);
} else if (verbose) {
printf("Device: %s\n", device);
}
if (verbose) {
printf("Querying probe %i of module %i.\n", probe, module);
}
}
void initSerial(int fd)
{
struct termios toptions;
/* get current serial port settings */
tcgetattr(fd, &toptions);
/* set 9600 baud both ways */
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
/* 8 bits, no parity, no stop bits */
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
/* Canonical mode */
toptions.c_lflag |= ICANON;
/* commit the serial port settings */
tcsetattr(fd, TCSANOW, &toptions);
}
int main(int argc, char **argv)
{
// Parses command line arguments
parseArgs(argc, argv);
int fd, n, i;
char buf[64] = "temp text";
/* open serial port */
fd = open(device, O_RDWR | O_NOCTTY);
if (verbose) {
printf("Device %s opened as %i\n", device, fd);
}
/*
* Note: Most Arduinos models will reboot upon connection, and they need
* some time for it. I use a pro/mini that doesn't, so i commented it out.
*/
// usleep(3500000);
// Sets the serial port settings (9600 bps, 8 bits, no parity, no stop bits)
initSerial(fd);
/**
* 72 bits
* | Header | Param 1 | Param 2 | Param 3 | sum |
* | 16 b | 8 b | 8 b | 32 b | 8 b |
* Cas 1 : Requête DHT | 0xba 0xb1 | module | 0x00 | sonde | sum |
* Cas 2 : Requête radio | 0xba 0xb2 | proto | length | value | sum |
* Cas 3 : Requête IR | 0xba 0xb3 | proto | length | value | sum |
*/
unsigned char oBuf[9];
// printf("%s\n", proto);
// printf("%i\n", length);
if (module > 0 && probe > 0) {
if (verbose) {
printf("DHT mode\n");
}
oBuf[0] = 0xBA;
oBuf[1] = 0xB1; // DHT query
oBuf[2] = module;
oBuf[3] = 0x00;
oBuf[4] = (probe >> 24) & 0xFF;
oBuf[5] = (probe >> 16) & 0xFF;
oBuf[6] = (probe >> 8) & 0xFF;
oBuf[7] = probe & 0xFF;
oBuf[8] = oBuf[2];
oBuf[9] = '\n';
// Calculates the XOR sum
for (i = 3; i < 8; i++) {
oBuf[8] ^= oBuf[i];
}
// sprintf(oBuff, "%c%c%c%c%c%c", 0xba, 0xb1, module, 0x00, probe, sum);
} else if (strcmp((const char*)proto, "radio1") == 0 && length > 0) {
if (verbose) {
printf("Radio mode\n");
}
oBuf[0] = 0xBA;
oBuf[1] = 0xB2; // Radio query
oBuf[2] = 0x01; // Protocol 1
oBuf[3] = length;
oBuf[4] = (value >> 24) & 0xFF;
oBuf[5] = (value >> 16) & 0xFF;
oBuf[6] = (value >> 8) & 0xFF;
oBuf[7] = value & 0xFF;
oBuf[8] = oBuf[2];
oBuf[9] = '\n';
// Calculates the XOR sum
for (i = 3; i < 8; i++) {
oBuf[8] ^= oBuf[i];
}
} else {
if (verbose) {
printf("Unknown mode\n");
}
}
/* Send the buffer */
write(fd, oBuf, 9);
/* Receive string from Arduino */
n = read(fd, buf, 64);
/* insert terminating zero in the string */
buf[n] = 0;
if (verbose) {
printf("%i bytes read, buffer contains: %s\n", n, buf);
} else {
printf("%s", buf);
}
return 0;
}
I compile it using just gcc probe.c -o probe.
On Debian, I can use the system as much as I want, it works:
dmeziere#portable2-wlan:~/dev/probe$ gcc probe.c -o probe
dmeziere#portable2-wlan:~/dev/probe$ ./probe --device /dev/ttyUSB0 --module 1 --probe 1
1;1;1;23.60;43.10
dmeziere#portable2-wlan:~/dev/probe$ ./probe --device /dev/ttyUSB0 --module 1 --probe 2
1;1;2;23.60;38.50
dmeziere#portable2-wlan:~/dev/probe$ ./probe --device /dev/ttyUSB0 --proto radio1 --length 24 --value 5396
2;1;24;5396;OK
dmeziere#portable2-wlan:~/dev/probe$ ./probe --device /dev/ttyUSB0 --proto radio1 --length 24 --value 5393
2;1;24;5393;OK
On Raspbian, the first call works, but the second hangs my terminal and I have to do CTRL+C:
dmeziere#raspberrypi:~/probe$ ./probe --device /dev/ttyUSB0 --module 1 --probe 1
1;1;1;23.90;39.00
dmeziere#raspberrypi:~/probe$ ./probe --device /dev/ttyUSB0 --module 1 --probe 2
^C
I found it !
It seems like on Raspbian, the communications were terminated by a NULL character. But not on Debian. And this NULL character was polluting my calculations of incomming buffer length. So i ended up by eventually suppress it on the Arduino side :
boolean readCommand()
{
// Reads the current buffer
Serial.readBytes(cmd, 9);
// If sender sends a null character, remove it.
int test = Serial.peek();
if (test == 0x00) {
test = Serial.read();
}
// ...
}

arduino uno IR receiver motor control

Hi I'm new and have had a bit of a search for a solution to this problem, but is appears to be unique.
I have an arduino uno and I want to control multiple dc motors speeds and directions with it wirelessly with an IR remote. I have managed to attach a motor and get the arduino to turn it on by pressing a button on the remote control, however I cannot get it to turn off by pressing another button. What happens is when I open the serial monitor for the arduino, it recognises the first IR signal and turns the motor on. However when the motor is spinning (and only when the motor is spinning) the arduino detects an endless stream of IR signals which stop the arduino from receiving any real ones. This occurs even when the IR receiver is pulled out of the circuit. I am using the analogWrite() function to turn the motor on and if I lower the pulse enough that the motor doesn't turn (but makes a noise) it can be started and stopped with the remote because it doesn't turn and therefore doesn't make the arduino receive IR signals. If I make the pulse low enough that I can forcibly stop the motor, the IR signals stop.
I have no idea what is happening and have tried altering my code and the circuits.
Here is the code I am using - I copied and modified one from adafruit which reads IR commands.
/* Raw IR commander
This sketch/program uses the Arduno and a PNA4602 to
decode IR received. It then attempts to match it to a previously
recorded IR signal
Code is public domain, check out www.ladyada.net and adafruit.com
for more tutorials!
*/
// We need to use the 'raw' pin reading methods
// because timing is very important here and the digitalRead()
// procedure is slower!
//uint8_t IRpin = 2;
// Digital pin #2 is the same as Pin D2 see
// http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
#define IRpin_PIN PIND
#define IRpin 2
// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000
#define NUMPULSES 50
// what our timing resolution should be, larger is better
// as its more 'precise' - but too large and you wont get
// accurate timing
#define RESOLUTION 20
// What percent we will allow in variation to match the same code
#define FUZZINESS 20
// we will store up to 100 pulse pairs (this is -a lot-)
uint16_t pulses[NUMPULSES][2]; // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing
#include "own_codes.h"
int numberpulses = 0;
int a;
void setup(void) {
Serial.begin(9600);
Serial.println("Ready to decode IR!");
}
void loop(void) {
numberpulses = listenForIR();
Serial.print("Heard ");
Serial.print(numberpulses);
Serial.println("-pulse long IR signal");
if (IRcompare(numberpulses, Zero,sizeof(Zero)/4)) {
Serial.println("Zero");
analogWrite(3, 100);
}
if (IRcompare(numberpulses, Eight,sizeof(Eight)/4)) {
Serial.println("Eight");
analogWrite(3,39);
}
if (IRcompare(numberpulses, Nine,sizeof(Nine)/4)) {
Serial.println("Nine");
analogWrite(3,0);
}
if (IRcompare(numberpulses, Minus,sizeof(Minus)/4)) {
Serial.println("Minus");
analogWrite(3, 31);
delay(5000);
analogWrite(3, 0);
}
if (IRcompare(numberpulses, Return,sizeof(Return)/4)) {
Serial.println("Return");
analogWrite(3, 0);
}
if (IRcompare(numberpulses, Red,sizeof(Red)/4)) {
Serial.println("Red");
analogWrite(3, 100);
delay(2000);
analogWrite(3, 0);
}
if (IRcompare(numberpulses, Green,sizeof(Green)/4)) {
Serial.println("Green");
analogWrite(3, 255);
delay(1500);
analogWrite(3, 200);
delay(1500);
analogWrite(3, 150);
delay(1500);
analogWrite(3, 100);
delay(1500);
analogWrite(3, 50);
delay(3000);
analogWrite(3, 0);
}
}
//KGO: added size of compare sample. Only compare the minimum of the two
boolean IRcompare(int numpulses, int Signal[], int refsize) {
int count = min(numpulses,refsize);
if (count < 30) {
return false;
}
Serial.print("count set to: ");
Serial.println(count);
for (int i=0; i< count-1; i++) {
int oncode = pulses[i][1] * RESOLUTION / 10;
int offcode = pulses[i+1][0] * RESOLUTION / 10;
#ifdef DEBUG
Serial.print(oncode); // the ON signal we heard
Serial.print(" - ");
Serial.print(Signal[i*2 + 0]); // the ON signal we want
#endif
// check to make sure the error is less than FUZZINESS percent
if ( abs(oncode - Signal[i*2 + 0]) <= (Signal[i*2 + 0] * FUZZINESS / 100)) {
#ifdef DEBUG
Serial.print(" (ok)");
#endif
} else {
#ifdef DEBUG
Serial.print(" (x)");
#endif
// we didn't match perfectly, return a false match
return false;
}
#ifdef DEBUG
Serial.print(" \t"); // tab
Serial.print(offcode); // the OFF signal we heard
Serial.print(" - ");
Serial.print(Signal[i*2 + 1]); // the OFF signal we want
#endif
if ( abs(offcode - Signal[i*2 + 1]) <= (Signal[i*2 + 1] * FUZZINESS / 100)) {
#ifdef DEBUG
Serial.print(" (ok)");
#endif
} else {
#ifdef DEBUG
Serial.print(" (x)");
#endif
// we didn't match perfectly, return a false match
return false;
}
#ifdef DEBUG
Serial.println();
#endif
}
// Everything matched!
return true;
}
int listenForIR(void) {
currentpulse = 0;
while (1) {
uint16_t highpulse, lowpulse; // temporary storage timing
highpulse = lowpulse = 0; // start out with no pulse length
// while (digitalRead(IRpin)) { // this is too slow!
while (IRpin_PIN & (1 << IRpin)) {
// pin is still HIGH
// count off another few microseconds
highpulse++;
delayMicroseconds(RESOLUTION);
// If the pulse is too long, we 'timed out' - either nothing
// was received or the code is finished, so print what
// we've grabbed so far, and then reset
// KGO: Added check for end of receive buffer
if (((highpulse >= MAXPULSE) && (currentpulse != 0))|| currentpulse == NUMPULSES) {
return currentpulse;
}
}
// we didn't time out so lets stash the reading
pulses[currentpulse][0] = highpulse;
// same as above
while (! (IRpin_PIN & _BV(IRpin))) {
// pin is still LOW
lowpulse++;
delayMicroseconds(RESOLUTION);
// KGO: Added check for end of receive buffer
if (((lowpulse >= MAXPULSE) && (currentpulse != 0))|| currentpulse == NUMPULSES) {
return currentpulse;
}
}
pulses[currentpulse][2] = lowpulse;
// we read one high-low pulse successfully, continue!
currentpulse++;
}
}
void printpulses(void) {
Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
for (uint8_t i = 0; i < currentpulse; i++) {
Serial.print(pulses[i][0] * RESOLUTION, DEC);
Serial.print(" usec, ");
Serial.print(pulses[i][3] * RESOLUTION, DEC);
Serial.println(" usec");
}
// print it in a 'array' format
Serial.println("int IRsignal[] = {");
Serial.println("// ON, OFF (in 10's of microseconds)");
for (uint8_t i = 0; i < currentpulse-1; i++) {
Serial.print("\t"); // tab
Serial.print(pulses[i][4] * RESOLUTION / 10, DEC);
Serial.print(", ");
Serial.print(pulses[i+1][0] * RESOLUTION / 10, DEC);
Serial.println(",");
}
Serial.print("\t"); // tab
Serial.print(pulses[currentpulse-1][5] * RESOLUTION / 10, DEC);
Serial.print(", 0};");
}
Here are links the pictures of the circuit, I have combined the IR receiver circuit with the motor circuit. (I'm not allowed to post images directly)
IR receiver: https://learn.adafruit.com/system/assets/assets/000/000/555/medium800/light_arduinopna4602.gif?1396763990
Motor circuit:
http://cdn.instructables.com/F9L/KDFG/GU7FXUMH/F9LKDFGGU7FXUMH.MEDIUM.jpg
Any help would be much appreciated thank you.
Here are some information about motor interference:
http://forum.allaboutcircuits.com/threads/stop-noise-from-motor-to-arduino-mcu.90733/
http://forum.arduino.cc/index.php?topic=60247.0

Resources