MCP9600 : the thermocouplereading() give the same value during a long time - python

i use an MCP9600 sensor to know the temperature. I use an ATmega 2560 and i communicate from my laptop with python with the library serial.
this is my arduino
#include <Wire.h>
#include <Adafruit_I2CDevice.h>
#include <Adafruit_I2CRegister.h>
#include "Adafruit_MCP9600.h"
#include <SimpleCLI.h>
#define I2C_ADDRESS (0x67)
Adafruit_MCP9600 mcp;
uint8_t filtcoeff;
// Create CLI Object
SimpleCLI cli;
// Commands
Command type;
Command filter;
Command temp;
Command fanspeed;
Command Tmax;
Command tolerance;
//Call function
void overheat();
void deltatemp();
// Callback function
void typeCallback();
void filterCallback();
void temperatureCallback();
void FanCallback();
void overheatCallback();
void toleranceCallback();
int broche_PWM = 2; // Déclaration de la Pin 10 Arduino
int Valeur_PWM = 128; // Variable
int timedelay = 300;
int tempTolerance = 10;
int tempmax = 50;
void setup() {
// put your setup code here, to run once:
pinMode(broche_PWM, OUTPUT); // Pin 2 Arduino en sortie PWM
Serial.begin(115200);
while (!Serial) {
delay(10);
}
cli.setOnError(errorCallback); // Set error Callback
/* Initialise the driver with I2C_ADDRESS and the default I2C bus. */
if (! mcp.begin(I2C_ADDRESS)) {
Serial.println("Sensor not found. Check wiring!");
while (1);
}
mcp.setADCresolution(MCP9600_ADCRESOLUTION_12);
switch (mcp.getADCresolution()) {
case MCP9600_ADCRESOLUTION_18: ; break;
case MCP9600_ADCRESOLUTION_16: ; break;
case MCP9600_ADCRESOLUTION_14: ; break;
case MCP9600_ADCRESOLUTION_12: ; break;
}
mcp.setThermocoupleType(MCP9600_TYPE_K);
switch (mcp.getThermocoupleType()) {
case MCP9600_TYPE_K: ; break;
case MCP9600_TYPE_J: ; break;
case MCP9600_TYPE_T: ; break;
case MCP9600_TYPE_N: ; break;
case MCP9600_TYPE_S: ; break;
case MCP9600_TYPE_E: ; break;
case MCP9600_TYPE_B: ; break;
case MCP9600_TYPE_R: ; break;
}
mcp.setFilterCoefficient(3);
mcp.setAlertTemperature(1, 30);
mcp.configureAlert(1, true, true); // alert 1 enabled, rising temp
mcp.enable(true);
type = cli.addBoundlessCommand("type", typeCallback);
filter = cli.addBoundlessCommand("filter", filterCallback);
temp = cli.addBoundlessCommand("temp", temperatureCallback);
fanspeed = cli.addBoundlessCommand("fanspeed", FanCallback);
Tmax = cli.addBoundlessCommand("Tmax", overheatCallback);
tolerance = cli.addBoundlessCommand("Tolerance", toleranceCallback);
Serial.println("I am ready"); // avoid to have a void monitor (avoiding blocking in python code)
}
void loop() {
// put your main code here, to run repeatedly:
// Check if user typed something into the serial monitor
if (Serial.available()) {
// Read out string from the serial monitor
String input = Serial.readStringUntil('\n');
// Parse the user input into the CLI
cli.parse(input);
}
if (cli.errored()) {
CommandError cmdError = cli.getError();
Serial.print("ERROR: ");
Serial.println(cmdError.toString());
if (cmdError.hasCommand()) {
Serial.print("Did you mean \"");
Serial.print(cmdError.getCommand().toString());
Serial.println("\"?");
}
}
if (mcp.readThermocouple() > tempmax){
overheat();
}
if (abs(mcp.readThermocouple()-mcp.readAmbient())> tempTolerance){
//deltatemp();
}
analogWrite(broche_PWM,Valeur_PWM); // Envoi du signal PWM sur la sortie numérique 10
delay(timedelay);
}
void temperatureCallback(cmd* c){
Command cmd(c); // Create wrapper object
Serial.print("Hot Junction: ");
Serial.print("x");
Serial.print(mcp.readThermocouple());
Serial.print("x");
Serial.print("Cold Junction: ");
Serial.print("x");
Serial.print(mcp.readAmbient());
Serial.print("x");
Serial.print("ADC (uV): ");
Serial.print("x");
Serial.println(mcp.readADC() * 2);
}
void filterCallback(cmd* c){
Command cmd(c); // Create wrapper object
Argument arg;
String argValue = "";
int i=0;
int IntValue;
arg = cmd.getArg(i);
argValue = arg.getValue();
IntValue = argValue.toInt();
mcp.setFilterCoefficient(IntValue);
Serial.print("Filter coefficient value set to: ");
Serial.println(mcp.getFilterCoefficient());
}
}
and the python code, i use to extract the data from the ATmega
import numpy as np
import serial
import time
def get_temperature(serial_port):
phrase = b'temp'
# print("str.encode(phrase)",str.encode(phrase))
serial_port.write(phrase)
exitloop = 0
while exitloop == 0:
if serial_port.inWaiting() > 0:
arduino_data = serial_port.readline()
print(arduino_data)
serial_port.flushOutput()
exitloop = 1
serial_port.flushOutput()
serial_port.flushInput()
return arduino_data
the thermocouple is a K type. the problem is that the value coming from the sensor give constant during a long time when i see from the arduino serial monitor and from my python code. Normally, the value must change constantly when i compare with another device but give the same value a long time like 5 min.
Someone can give a solution?

I found the problem. It comes from the ADC_resolution, i gave back at 18.
Thanks

Related

Arduino/Python Serial communication

I want to send data from python to may Arduino Mega via serial output. The Arduino's RX Led blinks, when I run the Python script. However, the Serial.available() = false. This is just an example code. The real project is building a speedometer for sim racing games (using UDP data). Any idea why it isn't working?
Here is the code:
Python:
import time
import serial
port = "COM3"
Arduino = serial.Serial(port ,9600, timeout=1);
i = 0
while i<= 9999 :
time.sleep(1/10)
i+=1
print(i)
Arduino.write(i)
Arduino:
#include <Arduino.h>
#include <TM1637Display.h>
#define CLK 2
#define DIO 3
int i=0;
int Number;
TM1637Display display(CLK, DIO);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
display.setBrightness(0x0f);
display.showNumberDec(9999);
delay(3000);
}
void loop() {
Number= Serial.read();
if (Serial.available()>0){
display.setBrightness(0x0f);
display.showNumberDec(Number);
}
if (Serial.available() == false){
display.setBrightness(0x0f);
display.showNumberDec(0000);
}
}
This is how it works. Big thanks to csongoose from reddit who helped me a lot. Also thanks to all your replies on this.
Python:
import time
import serial
port = "COM3"
Arduino = serial.Serial(port ,9600, timeout=1);
i = 0
while i<= 9999 :
time.sleep(1)
i+=1
print(i)
#converts int i to string b
b = "%s" %i
Arduino.write(bytes(b, 'utf-8'))
#the Arduino waits for this and can seperate the numbers
Arduino.write(b'\n')
Arduino:
#include <Arduino.h>
#include <TM1637Display.h>
#define CLK 2
#define DIO 3
#define D1 5
#define D2 7
int Number;
String b;
//i am using a 7-digit display to show the numbers
TM1637Display display(CLK, DIO);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
pinMode(D1 ,OUTPUT);
pinMode(D2 ,OUTPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available()>0){
//looks for new numbers, which are sperated with '\n'
b = Serial.readStringUntil('\n');
//converts string b to integer Number
Number = b.toInt();
display.setBrightness(0x0f);
display.showNumberDec(Number);
//delay equals the same rate as python sends data
delay(1000);
}
//this indicates if the data is available and if the Arduino has rebooted
//you need to wait for it and then start your Python stream
if (Serial.available() == 0){
digitalWrite( D1, HIGH);}
else digitalWrite(D1, LOW);
if (Number != 0){
digitalWrite( D2, HIGH);}
else digitalWrite(D2, LOW);
}

python 3.x pyserial communication with arduino uno (servo control)

i have a trouble with serial communicate (python 3.x -> arduino uno).
when i run this code in python 2.5
python 2.5:
import serial
usbport = 'COM3'
ser = serial.Serial(usbport, 9600, timeout=1)
def move(servo, angle):
if (0 <= angle <= 180):
ser.write(chr(255))
ser.write(chr(servo))
ser.write(chr(angle))
else:
print("angle : between 0 and 180 \n")
when i simply type 'move(1,40)', servo1 (which is attached in pin9) moves to 40 angle.
But when i run the same code in python 3.6 , there is a error.
error means that i have to write class not .
so i encoded '255','servo','angle' to 'utf-8'
python 3.6.6
import serial
usbport = 'COM3'
ser = serial.Serial(usbport,9600,timeout = 1)
def move(servo,angle):
start = 255
start_b = str(start).encode()
ser.write(start_b)
a = str(servo).encode()
b = str(angle).encode()
ser.write(a)
ser.write(b)
But servo doesn't move.
Here is a arduino code
arduino uno
#include <Servo.h>
Servo servo1;
int minPulse = 600;
int maxPulse = 2400;
int userInput[3];
int startbyte;
int servo;
int pos;
int i;
void setup()
{
servo1.attach(9, minPulse, maxPulse);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if (Serial.available() > 2) {
// Read the first byte
startbyte = Serial.read();
// If it is really the startbyte (255) ...
if (startbyte == 255) {
for (i=0;i<2;i++) {
userInput[i] = Serial.read();
}
servo = userInput[0];
pos = userInput[1];
if (pos == 255) { servo = 255; }
switch (servo) {
case 1:
servo1.write(pos); // move servo1 to 'pos'
break;
case 99:
if (pos == 180) {
if (pinState == LOW) { pinState = HIGH; }
else { pinState = LOW; }
}
if (pos == 0) {
pinState = LOW;
}
digitalWrite(ledPin, pinState);
break;
}
}
}
}
there is a error.
Can you provide the error message? And of course the code will not run directly from Python 2 to 3 until you do the modification from importing the PySerial Library. Python runs and finds the library, but it cannot be used for Python 3, that's why they made 2 libraries for PySerial.
after Serial.begin(9600); write ser.begin(9600);

Cannot send/receive number through USB to Arduino to control a motor

I'm having a project to use pyserial to send a number to an Arduino. This number is RPM (round per minute). Arduino will receive this number to control the motor (in here I use PID Controller) and then send the number Arduino received back to Python console. The problem is, I tried to send float number to Arduino, but it receives nothing. Here is the problem:
#include <TimerOne.h>
#include <Encoder.h>
#define A 2 //Encoder pins
#define B 3
Encoder encoder(2,3);
//Config pins for motor control:
int pinAIN1 = 9; //Direction
int pinAIN2 = 8; //Direction
int pinPWMA = 5; //Speed
int pinSTBY = 4; //Stanby
float receive;
float tsamp = 0.01;
float xung = 0;
float last_xung = 0;
float current_speed = 0;
float ref_speed ; //The reference speed
float error = 0;
float last_error = 0;
float PID,last_PID;
float Kp =0.15 , Ki =0, Kd = 0.01;
void dotocdo()
{
if ( ref_speed >= 0)
{
digitalWrite(pinAIN1, 1);
digitalWrite(pinAIN2, 0);
analogWrite(pinPWMA, PID);
}
if ( ref_speed < 0)
{
digitalWrite(pinAIN1, 0);
digitalWrite(pinAIN2, 1);
analogWrite(pinPWMA, abs(PID));
}
float P;
static float I,D;
current_speed = 60*(xung-last_xung)/(tsamp*374*4);
last_xung = xung;
Serial.println(current_speed);
error=abs(ref_speed)-abs(current_speed);
P = Kp*error;
D = Kd*(error - last_error)/tsamp;
I = Ki*error*tsamp;
PID = last_PID + P + I + D;
last_error = error;
last_PID = PID;
if (PID >= 255) {PID = 255;}
if (PID <= -255) {PID = -255;}
}
void setup() {
Serial.begin(115200);
pinMode(pinPWMA, OUTPUT);
pinMode(pinAIN1, OUTPUT);
pinMode(pinAIN2, OUTPUT);
pinMode(pinSTBY, OUTPUT);
pinMode(A, INPUT);
pinMode(B, INPUT);
digitalWrite(pinSTBY, 1);
Timer1.initialize(10000);
Timer1.attachInterrupt(dotocdo);
}
void loop()
{
if (Serial.available())
{
receive= Serial.parseFloat();
ref_speed=receive;
Serial.println(receive);
}
xung=encoder.read();
}
And here is the Python code on Raspberry:
import time
import socket
import sys
import serial
import struct
UNO_1 = serial.Serial('/dev/ttyUSB0', 115200)
while (1):
n=float(25)
UNO_1.write(bytes(b'%f'%n))
receive=UNO_1.readline()
print(receive)
This is the error (Arduino receives nothing):
Does anyone know how to fix this problem?
Has any communication worked before?
Double-check your connections (swapped TX and RX, forgot GND)
Try using a serial terminal (I think pyserial has a demo included) to send data manually.
Your Python script may just be timing out.
Your Python script might be sending too many zeroes or control characters that Serial.parseFloat() does not like (it stops if it does not like something).
Alternativley, just get started with echo programs that don't actually try to parse numbers to see if any data comes through: try this.

Talking SMBus between RaspberryPi and ATMEGA 324PA - AVR not clock stretching

I'm trying to get an ATMEGA 324PA to run as an SMBus slave.
I'm using the following code on the Pi:
import smbus as smbus
i2c = smbus.SMBus(1)
i2c_addr = 0x30
result = i2c.read_block_data( i2c_addr, reg )
On the AVR, I'm using:
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include "smb_slave.h"
#define SMB_COMMAND_RETURN_VENDOR_STRING 0x10
int main(void)
{
// Set data direction of PORTB as output and turn off LEDs.
DDRA = 0xff;
PORTA = 0xff;
// Initialize SMBus
SMBusInit();
SMBEnable();
// Enable interrupts globally
sei();
for (;;)
{
}
return 0;
}
void ProcessReceiveByte(SMBData *smb)
{
smb->txBuffer[0] = ~PIND;
smb->txLength = 1;
}
static void ReturnVendorString(SMBData *smb)
{
unsigned char *vendor = (unsigned char*) "Vendor\0";
unsigned char i;
unsigned char temp;
i = 0;
// Copy vendor ID string from EEPROM.
while ((temp = vendor[i]) != '\0')
{
i++;
smb->txBuffer[i] = temp;
}
smb->txBuffer[0] = i; // Byte count.
smb->txLength = i + 1; // Number of bytes to be transmitted including byte count.
smb->state = SMB_STATE_WRITE_READ_REQUESTED;
PORTA ^= 0x40; // debug
}
static void UndefinedCommand(SMBData *smb)
{
// Handle undefined requests here.
smb->error = TRUE;
smb->state = SMB_STATE_IDLE;
}
void ProcessMessage(SMBData *smb)
{
if (smb->state == SMB_STATE_WRITE_REQUESTED)
{
switch (smb->rxBuffer[0]) // Command code.
{
case SMB_COMMAND_RETURN_VENDOR_STRING: // Block read, vendor ID.
ReturnVendorString(smb);
break;
default:
UndefinedCommand(smb);
break;
}
}
else
{
smb->state = SMB_STATE_IDLE;
}
}
With a (gcc-adapted) version of: http://www.atmel.com/images/AVR316.zip from http://www.atmel.com/devices/ATMEGA324A.aspx?tab=documents
Something's partially working, as my logic analyser shows:
But I assume I'm doing something wrong as the AVR is not ACK'ing the READ, nor clock-stretching nor sending a response.
Where should I look next?
Can I have confidence in the Python smbus module on the RasPi?
Could what I'm seeing be related to https://github.com/raspberrypi/linux/issues/254 ?
The issue you linked is the problem -- i2c clock stretching is simply broken on the Raspberry Pi. More info: http://www.advamation.com/knowhow/raspberrypi/rpi-i2c-bug.html
If a sensor has alternative output such as UART sometimes that's an option but for some projects I've had to use a micro or Beaglebone or some other thing.
I tried using SMBus from a Beaglebone instead (replacing the Raspberry Pi).
This worked perfectly, after I added some 10K pull-up resistors to the i2c bus. (The Raspberry Pi has internal pull-ups on the i2c pins.)

How to execute Python script from CreateProcess in C on Windows?

I have managed to get C code calling Python scripts happily on Unix using PIPES within the C code. I now need to do the same on Windows.
Essentially I would like to write scripts in different scripting languages like Python / Lua etc on Windows and be able to execute them using STDIN / STDOUT etc.
I have been looking at the "CreateProcess" call at:
http://msdn.microsoft.com/en-us/library/ms682425(VS.85).aspx
and although I can get it to work with a "child written in C", I cannot get it to call a Python script.
Below is the "parent / sender code" on my windows box:
#include<windows.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib, "User32.lib")
void DisplayError(char *pszAPI);
void readFromPipe(HANDLE hPipeRead);
void createChildProcess(char *commandLine,
HANDLE hChildStdOut,
HANDLE hChildStdIn,
HANDLE hChildStdErr);
DWORD WINAPI writeToPipe(LPVOID lpvThreadParam);
HANDLE hChildProcess = NULL;
HANDLE hStdIn = NULL;
BOOL bRunThread = TRUE;
char *inputStream;
int main(int argc, char *argv[]){
HANDLE hOutputReadTmp,hOutputRead,hOutputWrite;
HANDLE hInputWriteTmp,hInputRead,hInputWrite;
HANDLE hErrorWrite;
HANDLE hThread;
DWORD ThreadId;
SECURITY_ATTRIBUTES sa;
int streamLen;
sa.nLength= sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hOutputReadTmp,&hOutputWrite,&sa,0))
return 1;
if (!DuplicateHandle(GetCurrentProcess(),hOutputWrite,
GetCurrentProcess(),&hErrorWrite,0,
TRUE,DUPLICATE_SAME_ACCESS))
return 1;
if (!CreatePipe(&hInputRead,&hInputWriteTmp,&sa,0))
return 1;
if (!DuplicateHandle(GetCurrentProcess(),hOutputReadTmp,
GetCurrentProcess(),
&hOutputRead,
0,FALSE,
DUPLICATE_SAME_ACCESS))
return 1;
if (!DuplicateHandle(GetCurrentProcess(),hInputWriteTmp,
GetCurrentProcess(),
&hInputWrite,
0,FALSE,
DUPLICATE_SAME_ACCESS))
return 1;
if (!CloseHandle(hOutputReadTmp)) return 1;;
if (!CloseHandle(hInputWriteTmp)) return 1;;
if ( (hStdIn = GetStdHandle(STD_INPUT_HANDLE)) == INVALID_HANDLE_VALUE )
return 1;
if (argc == 2){
createChildProcess(argv[1], hOutputWrite,hInputRead,hErrorWrite);
}else{
puts("No process name / input stream specified\n");
return 1;
}
if (!CloseHandle(hOutputWrite)) return 1;;
if (!CloseHandle(hInputRead )) return 1;;
if (!CloseHandle(hErrorWrite)) return 1;;
hThread = CreateThread(NULL,0,writeToPipe,
(LPVOID)hInputWrite,0,&ThreadId);
if (hThread == NULL)
return 1;;
readFromPipe(hOutputRead);
if (!CloseHandle(hStdIn))
return 1;
bRunThread = FALSE;
if (WaitForSingleObject(hThread,INFINITE) == WAIT_FAILED)
return 1;;
if (!CloseHandle(hOutputRead)) return 1;;
if (!CloseHandle(hInputWrite)) return 1;;
}
void createChildProcess(char *commandLine,
HANDLE hChildStdOut,
HANDLE hChildStdIn,
HANDLE hChildStdErr){
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory(&si,sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hChildStdOut;
si.hStdInput = hChildStdIn;
si.hStdError = hChildStdErr;
if (!CreateProcess(NULL,commandLine,NULL,NULL,TRUE,
NULL,NULL,NULL,&si,&pi))
hChildProcess = pi.hProcess;
if (!CloseHandle(pi.hThread)) return 1;;
}
void readFromPipe(HANDLE hPipeRead)
{
CHAR lpBuffer[256];
DWORD nBytesRead;
DWORD nCharsWritten;
while(TRUE)
{
if (!ReadFile(hPipeRead,lpBuffer,sizeof(lpBuffer),
&nBytesRead,NULL) || !nBytesRead)
{
if (GetLastError() == ERROR_BROKEN_PIPE)
break; // pipe done - normal exit path.
else
return 1; // Something bad happened.
}
if (!WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE),lpBuffer,
nBytesRead,&nCharsWritten,NULL))
return 1;;
}
}
DWORD WINAPI writeToPipe(LPVOID lpvThreadParam)
{
CHAR read_buff[256];
DWORD nBytesRead,nBytesWrote;
HANDLE hPipeWrite = (HANDLE)lpvThreadParam;
while (bRunThread){
nBytesRead = 21;
strncpy(read_buff, "hello from the paren\n",21);
read_buff[nBytesRead] = '\0';
if (!WriteFile(hPipeWrite,read_buff,nBytesRead,&nBytesWrote,NULL)){
if (GetLastError() == ERROR_NO_DATA)
break; //Pipe was closed (normal exit path).
else
return 1;;
}
}
return 1;
}
Quite a bit of the above code is "hardcoded" just for testing purposes...essentially I passing some text like "hello from the paren" to be sent to a "child.exe"....
Here is the code for the child.c...a simple ECHO of what is sent to it
#include<windows.h>
#include<stdio.h>
#include<string.h>
void main (){
CHAR szInput[1024];
ZeroMemory(szInput,1024);
gets(szInput);
puts(szInput);
fflush(NULL);
}
To run the app I send "CallSubProcess.exe Child.exe" and it works 100%
Next I want to change "child.c" to be a PYTHON SCRIPT...
import sys
if __name__ == "__main__":
inStream = sys.stdin.read()
outStream = inStream
sys.stdout.write(outStream)
sys.stdout.flush()
So how can I change the CreateProcess call to execute this script?
if (!CreateProcess("C:\\Python26\\python.exe", "echo.py",NULL, NULL,FALSE, 0,NULL,NULL,&si,&pi)){
But it never works.
Any ideas how I can get this to work? Any help will be greatly appreciated.
My application posts a string to a python script, and the python script posts the string back to the c
application. It works well.
//c code
#pragma comment(lib, "json_vc71_libmtd.lib")
#include <windows.h>
#include <iostream>
#include <io.h>
#include "./json/json.h"
using namespace std;
DWORD WINAPI threadproc(PVOID pParam);
HANDLE hRead, hWrite, hRead1, hWrite1;
int main()
{
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead, &hWrite, &sa, 0)){
::MessageBox(NULL, L"can't create pipe", L"error", MB_OK);
return -1;
}
if (!CreatePipe(&hRead1, &hWrite1, &sa, 0)){
::MessageBox(NULL, L"can't create pipe1", L"error", MB_OK);
return -1;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
GetStartupInfo(&si);
si.cb = sizeof(STARTUPINFO);
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.hStdInput = hRead1;
si.wShowWindow = SW_SHOW;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
WCHAR szCmdLine[] = L"\"D:\\tools\\python\\python.exe\" D:\\code\\test\\pipeCallCore\\pipeCallCore\\json_wraper.py";
if (!CreateProcess(NULL, szCmdLine, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)){
::MessageBox(NULL, L"can't create process", L"error", MB_OK);
return -1;
}
CloseHandle(hWrite);
CloseHandle(hRead1);
const int cBufferSize = 4096;
char buffer[cBufferSize] = {0};
DWORD bytes;
int i = 0;
while (true){
cout << "come !" << endl;
ZeroMemory(buffer, sizeof(buffer));
sprintf(buffer, "{\"write\":%d}\n", i ++);
if (NULL == WriteFile(hWrite1, buffer, strlen(buffer), &bytes, NULL)){
::MessageBox(NULL, L"write file failed!", L"error", MB_OK);
break;
}
ZeroMemory(buffer, sizeof(buffer));
if (NULL == ReadFile(hRead, buffer, cBufferSize - 1, &bytes, NULL)){
::MessageBox(NULL, L"readfile failed", L"error", MB_OK);
return -1;
}
cout <<"yes " << buffer << endl;
Sleep(2000);
}
return 0;
}
//python code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
while True:
try:
s = sys.stdin.readline()
sys.stdout.write(s)
sys.stdout.flush()
except EOFError, KeyboardInterrupt:
break
Maybe
if (!CreateProcess("C:\\Python26\\python.exe",
"echo.py 'hello from parent'",
NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
CreateProcess is kind of tricky to use.
From the MSDN documentation:
If both lpApplicationName and lpCommandLine are non-NULL, ... lpApplicationName specifies the module to execute, and ... lpCommandLine specifies the command line.... Console processes written in C can use the argc and argv arguments to parse the command line. Because argv[0] is the module name, C programmers generally repeat the module name as the first token in the command line.
To avoid the weirdness, I recommend always passing NULL for the first argument and to pass the full command-line as the second:
CreateProcess(NULL, "\"C:\\Python26\\python.exe\" echo.py", ...);

Categories